babylon.max.js 2.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. 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);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = 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. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.subtract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. 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]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. 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);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. 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);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. 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);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. 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);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. 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)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. 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;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. 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)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0.0, 0.0, 0.0, 0.0),
  3307. new Quaternion(0.0, 0.0, 0.0, 0.0)]; // 2 temp Quaternion at once should be enough
  3308. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero(),
  3311. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3312. BABYLON.Tmp = Tmp;
  3313. })(BABYLON || (BABYLON = {}));
  3314. //# sourceMappingURL=babylon.math.js.map
  3315. //# sourceMappingURL=babylon.mixins.js.map
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. function generateSerializableMember(type, sourceName) {
  3319. return function (target, propertyKey) {
  3320. if (!target.__serializableMembers) {
  3321. target.__serializableMembers = {};
  3322. }
  3323. if (!target.__serializableMembers[propertyKey]) {
  3324. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3325. }
  3326. };
  3327. }
  3328. function serialize(sourceName) {
  3329. return generateSerializableMember(0, sourceName); // value member
  3330. }
  3331. BABYLON.serialize = serialize;
  3332. function serializeAsTexture(sourceName) {
  3333. return generateSerializableMember(1, sourceName); // texture member
  3334. }
  3335. BABYLON.serializeAsTexture = serializeAsTexture;
  3336. function serializeAsColor3(sourceName) {
  3337. return generateSerializableMember(2, sourceName); // color3 member
  3338. }
  3339. BABYLON.serializeAsColor3 = serializeAsColor3;
  3340. function serializeAsFresnelParameters(sourceName) {
  3341. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3342. }
  3343. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3344. function serializeAsVector2(sourceName) {
  3345. return generateSerializableMember(4, sourceName); // vector2 member
  3346. }
  3347. BABYLON.serializeAsVector2 = serializeAsVector2;
  3348. function serializeAsVector3(sourceName) {
  3349. return generateSerializableMember(5, sourceName); // vector3 member
  3350. }
  3351. BABYLON.serializeAsVector3 = serializeAsVector3;
  3352. function serializeAsMeshReference(sourceName) {
  3353. return generateSerializableMember(6, sourceName); // mesh reference member
  3354. }
  3355. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3356. function serializeAsColorCurves(sourceName) {
  3357. return generateSerializableMember(7, sourceName); // color curves
  3358. }
  3359. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3360. var SerializationHelper = (function () {
  3361. function SerializationHelper() {
  3362. }
  3363. SerializationHelper.Serialize = function (entity, serializationObject) {
  3364. if (!serializationObject) {
  3365. serializationObject = {};
  3366. }
  3367. // Tags
  3368. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3369. // Properties
  3370. for (var property in entity.__serializableMembers) {
  3371. var propertyDescriptor = entity.__serializableMembers[property];
  3372. var targetPropertyName = propertyDescriptor.sourceName || property;
  3373. var propertyType = propertyDescriptor.type;
  3374. var sourceProperty = entity[property];
  3375. if (sourceProperty !== undefined && sourceProperty !== null) {
  3376. switch (propertyType) {
  3377. case 0:
  3378. serializationObject[targetPropertyName] = sourceProperty;
  3379. break;
  3380. case 1:
  3381. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3382. break;
  3383. case 2:
  3384. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3385. break;
  3386. case 3:
  3387. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3388. break;
  3389. case 4:
  3390. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3391. break;
  3392. case 5:
  3393. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3394. break;
  3395. case 6:
  3396. serializationObject[targetPropertyName] = sourceProperty.id;
  3397. break;
  3398. case 7:
  3399. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. return serializationObject;
  3405. };
  3406. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3407. var destination = creationFunction();
  3408. // Tags
  3409. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3410. // Properties
  3411. for (var property in destination.__serializableMembers) {
  3412. var propertyDescriptor = destination.__serializableMembers[property];
  3413. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3414. var propertyType = propertyDescriptor.type;
  3415. if (sourceProperty !== undefined && sourceProperty !== null) {
  3416. switch (propertyType) {
  3417. case 0:
  3418. destination[property] = sourceProperty;
  3419. break;
  3420. case 1:
  3421. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3422. break;
  3423. case 2:
  3424. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3425. break;
  3426. case 3:
  3427. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3428. break;
  3429. case 4:
  3430. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3431. break;
  3432. case 5:
  3433. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3434. break;
  3435. case 6:
  3436. destination[property] = scene.getLastMeshByID(sourceProperty);
  3437. break;
  3438. case 7:
  3439. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3440. break;
  3441. }
  3442. }
  3443. }
  3444. return destination;
  3445. };
  3446. SerializationHelper.Clone = function (creationFunction, source) {
  3447. var destination = creationFunction();
  3448. // Tags
  3449. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3450. // Properties
  3451. for (var property in destination.__serializableMembers) {
  3452. var propertyDescriptor = destination.__serializableMembers[property];
  3453. var sourceProperty = source[property];
  3454. var propertyType = propertyDescriptor.type;
  3455. if (sourceProperty !== undefined && sourceProperty !== null) {
  3456. switch (propertyType) {
  3457. case 0: // Value
  3458. case 6:
  3459. destination[property] = sourceProperty;
  3460. break;
  3461. case 1: // Texture
  3462. case 2: // Color3
  3463. case 3: // FresnelParameters
  3464. case 4: // Vector2
  3465. case 5: // Vector3
  3466. case 7:
  3467. destination[property] = sourceProperty.clone();
  3468. break;
  3469. }
  3470. }
  3471. }
  3472. return destination;
  3473. };
  3474. return SerializationHelper;
  3475. }());
  3476. BABYLON.SerializationHelper = SerializationHelper;
  3477. })(BABYLON || (BABYLON = {}));
  3478. //# sourceMappingURL=babylon.decorators.js.map
  3479. var BABYLON;
  3480. (function (BABYLON) {
  3481. /**
  3482. * A class serves as a medium between the observable and its observers
  3483. */
  3484. var EventState = (function () {
  3485. /**
  3486. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3487. */
  3488. function EventState(mask, skipNextObservers) {
  3489. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3490. this.initalize(mask, skipNextObservers);
  3491. }
  3492. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3493. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3494. this.mask = mask;
  3495. this.skipNextObservers = skipNextObservers;
  3496. return this;
  3497. };
  3498. return EventState;
  3499. }());
  3500. BABYLON.EventState = EventState;
  3501. /**
  3502. * Represent an Observer registered to a given Observable object.
  3503. */
  3504. var Observer = (function () {
  3505. function Observer(callback, mask) {
  3506. this.callback = callback;
  3507. this.mask = mask;
  3508. }
  3509. return Observer;
  3510. }());
  3511. BABYLON.Observer = Observer;
  3512. /**
  3513. * The Observable class is a simple implementation of the Observable pattern.
  3514. * 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.
  3515. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3516. * 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).
  3517. * 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.
  3518. */
  3519. var Observable = (function () {
  3520. function Observable() {
  3521. this._observers = new Array();
  3522. this._eventState = new EventState(0);
  3523. }
  3524. /**
  3525. * Create a new Observer with the specified callback
  3526. * @param callback the callback that will be executed for that Observer
  3527. * @param mask the mask used to filter observers
  3528. * @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.
  3529. */
  3530. Observable.prototype.add = function (callback, mask, insertFirst) {
  3531. if (mask === void 0) { mask = -1; }
  3532. if (insertFirst === void 0) { insertFirst = false; }
  3533. if (!callback) {
  3534. return null;
  3535. }
  3536. var observer = new Observer(callback, mask);
  3537. if (insertFirst) {
  3538. this._observers.unshift(observer);
  3539. }
  3540. else {
  3541. this._observers.push(observer);
  3542. }
  3543. return observer;
  3544. };
  3545. /**
  3546. * Remove an Observer from the Observable object
  3547. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3548. */
  3549. Observable.prototype.remove = function (observer) {
  3550. var index = this._observers.indexOf(observer);
  3551. if (index !== -1) {
  3552. this._observers.splice(index, 1);
  3553. return true;
  3554. }
  3555. return false;
  3556. };
  3557. /**
  3558. * Remove a callback from the Observable object
  3559. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3560. */
  3561. Observable.prototype.removeCallback = function (callback) {
  3562. for (var index = 0; index < this._observers.length; index++) {
  3563. if (this._observers[index].callback === callback) {
  3564. this._observers.splice(index, 1);
  3565. return true;
  3566. }
  3567. }
  3568. return false;
  3569. };
  3570. /**
  3571. * Notify all Observers by calling their respective callback with the given data
  3572. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3573. * @param eventData
  3574. * @param mask
  3575. */
  3576. Observable.prototype.notifyObservers = function (eventData, mask) {
  3577. if (mask === void 0) { mask = -1; }
  3578. var state = this._eventState;
  3579. state.mask = mask;
  3580. state.skipNextObservers = false;
  3581. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3582. var obs = _a[_i];
  3583. if (obs.mask & mask) {
  3584. obs.callback(eventData, state);
  3585. }
  3586. if (state.skipNextObservers) {
  3587. return false;
  3588. }
  3589. }
  3590. return true;
  3591. };
  3592. /**
  3593. * return true is the Observable has at least one Observer registered
  3594. */
  3595. Observable.prototype.hasObservers = function () {
  3596. return this._observers.length > 0;
  3597. };
  3598. /**
  3599. * Clear the list of observers
  3600. */
  3601. Observable.prototype.clear = function () {
  3602. this._observers = new Array();
  3603. };
  3604. /**
  3605. * Clone the current observable
  3606. */
  3607. Observable.prototype.clone = function () {
  3608. var result = new Observable();
  3609. result._observers = this._observers.slice(0);
  3610. return result;
  3611. };
  3612. return Observable;
  3613. }());
  3614. BABYLON.Observable = Observable;
  3615. })(BABYLON || (BABYLON = {}));
  3616. //# sourceMappingURL=babylon.observable.js.map
  3617. var BABYLON;
  3618. (function (BABYLON) {
  3619. var Database = (function () {
  3620. function Database(urlToScene, callbackManifestChecked) {
  3621. // Handling various flavors of prefixed version of IndexedDB
  3622. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3623. this.callbackManifestChecked = callbackManifestChecked;
  3624. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3625. this.db = null;
  3626. this.enableSceneOffline = false;
  3627. this.enableTexturesOffline = false;
  3628. this.manifestVersionFound = 0;
  3629. this.mustUpdateRessources = false;
  3630. this.hasReachedQuota = false;
  3631. if (!Database.IDBStorageEnabled) {
  3632. this.callbackManifestChecked(true);
  3633. }
  3634. else {
  3635. this.checkManifestFile();
  3636. }
  3637. }
  3638. Database.prototype.checkManifestFile = function () {
  3639. var _this = this;
  3640. function noManifestFile() {
  3641. that.enableSceneOffline = false;
  3642. that.enableTexturesOffline = false;
  3643. that.callbackManifestChecked(false);
  3644. }
  3645. var that = this;
  3646. var timeStampUsed = false;
  3647. var manifestURL = this.currentSceneUrl + ".manifest";
  3648. var xhr = new XMLHttpRequest();
  3649. if (navigator.onLine) {
  3650. // Adding a timestamp to by-pass browsers' cache
  3651. timeStampUsed = true;
  3652. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3653. }
  3654. xhr.open("GET", manifestURL, true);
  3655. xhr.addEventListener("load", function () {
  3656. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3657. try {
  3658. var manifestFile = JSON.parse(xhr.response);
  3659. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3660. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3661. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3662. _this.manifestVersionFound = manifestFile.version;
  3663. }
  3664. if (_this.callbackManifestChecked) {
  3665. _this.callbackManifestChecked(true);
  3666. }
  3667. }
  3668. catch (ex) {
  3669. noManifestFile();
  3670. }
  3671. }
  3672. else {
  3673. noManifestFile();
  3674. }
  3675. }, false);
  3676. xhr.addEventListener("error", function (event) {
  3677. if (timeStampUsed) {
  3678. timeStampUsed = false;
  3679. // Let's retry without the timeStamp
  3680. // It could fail when coupled with HTML5 Offline API
  3681. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3682. xhr.open("GET", retryManifestURL, true);
  3683. xhr.send();
  3684. }
  3685. else {
  3686. noManifestFile();
  3687. }
  3688. }, false);
  3689. try {
  3690. xhr.send();
  3691. }
  3692. catch (ex) {
  3693. BABYLON.Tools.Error("Error on XHR send request.");
  3694. that.callbackManifestChecked(false);
  3695. }
  3696. };
  3697. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3698. var _this = this;
  3699. function handleError() {
  3700. that.isSupported = false;
  3701. if (errorCallback)
  3702. errorCallback();
  3703. }
  3704. var that = this;
  3705. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3706. // Your browser doesn't support IndexedDB
  3707. this.isSupported = false;
  3708. if (errorCallback)
  3709. errorCallback();
  3710. }
  3711. else {
  3712. // If the DB hasn't been opened or created yet
  3713. if (!this.db) {
  3714. this.hasReachedQuota = false;
  3715. this.isSupported = true;
  3716. var request = this.idbFactory.open("babylonjs", 1);
  3717. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3718. request.onerror = function (event) {
  3719. handleError();
  3720. };
  3721. // executes when a version change transaction cannot complete due to other active transactions
  3722. request.onblocked = function (event) {
  3723. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3724. handleError();
  3725. };
  3726. // DB has been opened successfully
  3727. request.onsuccess = function (event) {
  3728. _this.db = request.result;
  3729. successCallback();
  3730. };
  3731. // Initialization of the DB. Creating Scenes & Textures stores
  3732. request.onupgradeneeded = function (event) {
  3733. _this.db = (event.target).result;
  3734. try {
  3735. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3736. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3737. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3738. }
  3739. catch (ex) {
  3740. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3741. handleError();
  3742. }
  3743. };
  3744. }
  3745. else {
  3746. if (successCallback)
  3747. successCallback();
  3748. }
  3749. }
  3750. };
  3751. Database.prototype.loadImageFromDB = function (url, image) {
  3752. var _this = this;
  3753. var completeURL = Database.ReturnFullUrlLocation(url);
  3754. var saveAndLoadImage = function () {
  3755. if (!_this.hasReachedQuota && _this.db !== null) {
  3756. // the texture is not yet in the DB, let's try to save it
  3757. _this._saveImageIntoDBAsync(completeURL, image);
  3758. }
  3759. else {
  3760. image.src = url;
  3761. }
  3762. };
  3763. if (!this.mustUpdateRessources) {
  3764. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3765. }
  3766. else {
  3767. saveAndLoadImage();
  3768. }
  3769. };
  3770. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3771. if (this.isSupported && this.db !== null) {
  3772. var texture;
  3773. var transaction = this.db.transaction(["textures"]);
  3774. transaction.onabort = function (event) {
  3775. image.src = url;
  3776. };
  3777. transaction.oncomplete = function (event) {
  3778. var blobTextureURL;
  3779. if (texture) {
  3780. var URL = window.URL || window.webkitURL;
  3781. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3782. image.onerror = function () {
  3783. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3784. image.src = url;
  3785. };
  3786. image.src = blobTextureURL;
  3787. }
  3788. else {
  3789. notInDBCallback();
  3790. }
  3791. };
  3792. var getRequest = transaction.objectStore("textures").get(url);
  3793. getRequest.onsuccess = function (event) {
  3794. texture = (event.target).result;
  3795. };
  3796. getRequest.onerror = function (event) {
  3797. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3798. image.src = url;
  3799. };
  3800. }
  3801. else {
  3802. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3803. image.src = url;
  3804. }
  3805. };
  3806. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3807. var _this = this;
  3808. if (this.isSupported) {
  3809. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3810. var generateBlobUrl = function () {
  3811. var blobTextureURL;
  3812. if (blob) {
  3813. var URL = window.URL || window.webkitURL;
  3814. try {
  3815. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3816. }
  3817. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3818. catch (ex) {
  3819. blobTextureURL = URL.createObjectURL(blob);
  3820. }
  3821. }
  3822. image.src = blobTextureURL;
  3823. };
  3824. if (Database.IsUASupportingBlobStorage) {
  3825. var xhr = new XMLHttpRequest(), blob;
  3826. xhr.open("GET", url, true);
  3827. xhr.responseType = "blob";
  3828. xhr.addEventListener("load", function () {
  3829. if (xhr.status === 200) {
  3830. // Blob as response (XHR2)
  3831. blob = xhr.response;
  3832. var transaction = _this.db.transaction(["textures"], "readwrite");
  3833. // the transaction could abort because of a QuotaExceededError error
  3834. transaction.onabort = function (event) {
  3835. try {
  3836. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3837. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3838. _this.hasReachedQuota = true;
  3839. }
  3840. }
  3841. catch (ex) { }
  3842. generateBlobUrl();
  3843. };
  3844. transaction.oncomplete = function (event) {
  3845. generateBlobUrl();
  3846. };
  3847. var newTexture = { textureUrl: url, data: blob };
  3848. try {
  3849. // Put the blob into the dabase
  3850. var addRequest = transaction.objectStore("textures").put(newTexture);
  3851. addRequest.onsuccess = function (event) {
  3852. };
  3853. addRequest.onerror = function (event) {
  3854. generateBlobUrl();
  3855. };
  3856. }
  3857. catch (ex) {
  3858. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3859. if (ex.code === 25) {
  3860. Database.IsUASupportingBlobStorage = false;
  3861. }
  3862. image.src = url;
  3863. }
  3864. }
  3865. else {
  3866. image.src = url;
  3867. }
  3868. }, false);
  3869. xhr.addEventListener("error", function (event) {
  3870. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3871. image.src = url;
  3872. }, false);
  3873. xhr.send();
  3874. }
  3875. else {
  3876. image.src = url;
  3877. }
  3878. }
  3879. else {
  3880. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3881. image.src = url;
  3882. }
  3883. };
  3884. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3885. var _this = this;
  3886. var updateVersion = function (event) {
  3887. // the version is not yet in the DB or we need to update it
  3888. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3889. };
  3890. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3891. };
  3892. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3893. var _this = this;
  3894. if (this.isSupported) {
  3895. var version;
  3896. try {
  3897. var transaction = this.db.transaction(["versions"]);
  3898. transaction.oncomplete = function (event) {
  3899. if (version) {
  3900. // If the version in the JSON file is > than the version in DB
  3901. if (_this.manifestVersionFound > version.data) {
  3902. _this.mustUpdateRessources = true;
  3903. updateInDBCallback();
  3904. }
  3905. else {
  3906. callback(version.data);
  3907. }
  3908. }
  3909. else {
  3910. _this.mustUpdateRessources = true;
  3911. updateInDBCallback();
  3912. }
  3913. };
  3914. transaction.onabort = function (event) {
  3915. callback(-1);
  3916. };
  3917. var getRequest = transaction.objectStore("versions").get(url);
  3918. getRequest.onsuccess = function (event) {
  3919. version = (event.target).result;
  3920. };
  3921. getRequest.onerror = function (event) {
  3922. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3923. callback(-1);
  3924. };
  3925. }
  3926. catch (ex) {
  3927. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3928. callback(-1);
  3929. }
  3930. }
  3931. else {
  3932. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3933. callback(-1);
  3934. }
  3935. };
  3936. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3937. var _this = this;
  3938. if (this.isSupported && !this.hasReachedQuota) {
  3939. try {
  3940. // Open a transaction to the database
  3941. var transaction = this.db.transaction(["versions"], "readwrite");
  3942. // the transaction could abort because of a QuotaExceededError error
  3943. transaction.onabort = function (event) {
  3944. try {
  3945. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3946. _this.hasReachedQuota = true;
  3947. }
  3948. }
  3949. catch (ex) { }
  3950. callback(-1);
  3951. };
  3952. transaction.oncomplete = function (event) {
  3953. callback(_this.manifestVersionFound);
  3954. };
  3955. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3956. // Put the scene into the database
  3957. var addRequest = transaction.objectStore("versions").put(newVersion);
  3958. addRequest.onsuccess = function (event) {
  3959. };
  3960. addRequest.onerror = function (event) {
  3961. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3962. };
  3963. }
  3964. catch (ex) {
  3965. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3966. callback(-1);
  3967. }
  3968. }
  3969. else {
  3970. callback(-1);
  3971. }
  3972. };
  3973. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3974. var _this = this;
  3975. var completeUrl = Database.ReturnFullUrlLocation(url);
  3976. var saveAndLoadFile = function (event) {
  3977. // the scene is not yet in the DB, let's try to save it
  3978. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3979. };
  3980. this._checkVersionFromDB(completeUrl, function (version) {
  3981. if (version !== -1) {
  3982. if (!_this.mustUpdateRessources) {
  3983. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3984. }
  3985. else {
  3986. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3987. }
  3988. }
  3989. else {
  3990. errorCallback();
  3991. }
  3992. });
  3993. };
  3994. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3995. if (this.isSupported) {
  3996. var targetStore;
  3997. if (url.indexOf(".babylon") !== -1) {
  3998. targetStore = "scenes";
  3999. }
  4000. else {
  4001. targetStore = "textures";
  4002. }
  4003. var file;
  4004. var transaction = this.db.transaction([targetStore]);
  4005. transaction.oncomplete = function (event) {
  4006. if (file) {
  4007. callback(file.data);
  4008. }
  4009. else {
  4010. notInDBCallback();
  4011. }
  4012. };
  4013. transaction.onabort = function (event) {
  4014. notInDBCallback();
  4015. };
  4016. var getRequest = transaction.objectStore(targetStore).get(url);
  4017. getRequest.onsuccess = function (event) {
  4018. file = (event.target).result;
  4019. };
  4020. getRequest.onerror = function (event) {
  4021. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4022. notInDBCallback();
  4023. };
  4024. }
  4025. else {
  4026. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4027. callback();
  4028. }
  4029. };
  4030. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4031. var _this = this;
  4032. if (this.isSupported) {
  4033. var targetStore;
  4034. if (url.indexOf(".babylon") !== -1) {
  4035. targetStore = "scenes";
  4036. }
  4037. else {
  4038. targetStore = "textures";
  4039. }
  4040. // Create XHR
  4041. var xhr = new XMLHttpRequest(), fileData;
  4042. xhr.open("GET", url, true);
  4043. if (useArrayBuffer) {
  4044. xhr.responseType = "arraybuffer";
  4045. }
  4046. xhr.onprogress = progressCallback;
  4047. xhr.addEventListener("load", function () {
  4048. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4049. // Blob as response (XHR2)
  4050. //fileData = xhr.responseText;
  4051. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4052. if (!_this.hasReachedQuota) {
  4053. // Open a transaction to the database
  4054. var transaction = _this.db.transaction([targetStore], "readwrite");
  4055. // the transaction could abort because of a QuotaExceededError error
  4056. transaction.onabort = function (event) {
  4057. try {
  4058. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4059. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4060. _this.hasReachedQuota = true;
  4061. }
  4062. }
  4063. catch (ex) { }
  4064. callback(fileData);
  4065. };
  4066. transaction.oncomplete = function (event) {
  4067. callback(fileData);
  4068. };
  4069. var newFile;
  4070. if (targetStore === "scenes") {
  4071. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4072. }
  4073. else {
  4074. newFile = { textureUrl: url, data: fileData };
  4075. }
  4076. try {
  4077. // Put the scene into the database
  4078. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4079. addRequest.onsuccess = function (event) {
  4080. };
  4081. addRequest.onerror = function (event) {
  4082. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4083. };
  4084. }
  4085. catch (ex) {
  4086. callback(fileData);
  4087. }
  4088. }
  4089. else {
  4090. callback(fileData);
  4091. }
  4092. }
  4093. else {
  4094. callback();
  4095. }
  4096. }, false);
  4097. xhr.addEventListener("error", function (event) {
  4098. BABYLON.Tools.Error("error on XHR request.");
  4099. callback();
  4100. }, false);
  4101. xhr.send();
  4102. }
  4103. else {
  4104. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4105. callback();
  4106. }
  4107. };
  4108. return Database;
  4109. }());
  4110. Database.IsUASupportingBlobStorage = true;
  4111. Database.IDBStorageEnabled = true;
  4112. Database.parseURL = function (url) {
  4113. var a = document.createElement('a');
  4114. a.href = url;
  4115. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4116. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4117. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4118. return absLocation;
  4119. };
  4120. Database.ReturnFullUrlLocation = function (url) {
  4121. if (url.indexOf("http:/") === -1) {
  4122. return (Database.parseURL(window.location.href) + url);
  4123. }
  4124. else {
  4125. return url;
  4126. }
  4127. };
  4128. BABYLON.Database = Database;
  4129. })(BABYLON || (BABYLON = {}));
  4130. //# sourceMappingURL=babylon.database.js.map
  4131. var BABYLON;
  4132. (function (BABYLON) {
  4133. var Internals;
  4134. (function (Internals) {
  4135. /*
  4136. * Based on jsTGALoader - Javascript loader for TGA file
  4137. * By Vincent Thibault
  4138. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4139. */
  4140. var TGATools = (function () {
  4141. function TGATools() {
  4142. }
  4143. TGATools.GetTGAHeader = function (data) {
  4144. var offset = 0;
  4145. var header = {
  4146. id_length: data[offset++],
  4147. colormap_type: data[offset++],
  4148. image_type: data[offset++],
  4149. colormap_index: data[offset++] | data[offset++] << 8,
  4150. colormap_length: data[offset++] | data[offset++] << 8,
  4151. colormap_size: data[offset++],
  4152. origin: [
  4153. data[offset++] | data[offset++] << 8,
  4154. data[offset++] | data[offset++] << 8
  4155. ],
  4156. width: data[offset++] | data[offset++] << 8,
  4157. height: data[offset++] | data[offset++] << 8,
  4158. pixel_size: data[offset++],
  4159. flags: data[offset++]
  4160. };
  4161. return header;
  4162. };
  4163. TGATools.UploadContent = function (gl, data) {
  4164. // Not enough data to contain header ?
  4165. if (data.length < 19) {
  4166. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4167. return;
  4168. }
  4169. // Read Header
  4170. var offset = 18;
  4171. var header = TGATools.GetTGAHeader(data);
  4172. // Assume it's a valid Targa file.
  4173. if (header.id_length + offset > data.length) {
  4174. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4175. return;
  4176. }
  4177. // Skip not needed data
  4178. offset += header.id_length;
  4179. var use_rle = false;
  4180. var use_pal = false;
  4181. var use_rgb = false;
  4182. var use_grey = false;
  4183. // Get some informations.
  4184. switch (header.image_type) {
  4185. case TGATools._TYPE_RLE_INDEXED:
  4186. use_rle = true;
  4187. case TGATools._TYPE_INDEXED:
  4188. use_pal = true;
  4189. break;
  4190. case TGATools._TYPE_RLE_RGB:
  4191. use_rle = true;
  4192. case TGATools._TYPE_RGB:
  4193. use_rgb = true;
  4194. break;
  4195. case TGATools._TYPE_RLE_GREY:
  4196. use_rle = true;
  4197. case TGATools._TYPE_GREY:
  4198. use_grey = true;
  4199. break;
  4200. }
  4201. var pixel_data;
  4202. var numAlphaBits = header.flags & 0xf;
  4203. var pixel_size = header.pixel_size >> 3;
  4204. var pixel_total = header.width * header.height * pixel_size;
  4205. // Read palettes
  4206. var palettes;
  4207. if (use_pal) {
  4208. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4209. }
  4210. // Read LRE
  4211. if (use_rle) {
  4212. pixel_data = new Uint8Array(pixel_total);
  4213. var c, count, i;
  4214. var localOffset = 0;
  4215. var pixels = new Uint8Array(pixel_size);
  4216. while (offset < pixel_total && localOffset < pixel_total) {
  4217. c = data[offset++];
  4218. count = (c & 0x7f) + 1;
  4219. // RLE pixels
  4220. if (c & 0x80) {
  4221. // Bind pixel tmp array
  4222. for (i = 0; i < pixel_size; ++i) {
  4223. pixels[i] = data[offset++];
  4224. }
  4225. // Copy pixel array
  4226. for (i = 0; i < count; ++i) {
  4227. pixel_data.set(pixels, localOffset + i * pixel_size);
  4228. }
  4229. localOffset += pixel_size * count;
  4230. }
  4231. else {
  4232. count *= pixel_size;
  4233. for (i = 0; i < count; ++i) {
  4234. pixel_data[localOffset + i] = data[offset++];
  4235. }
  4236. localOffset += count;
  4237. }
  4238. }
  4239. }
  4240. else {
  4241. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4242. }
  4243. // Load to texture
  4244. var x_start, y_start, x_step, y_step, y_end, x_end;
  4245. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4246. default:
  4247. case TGATools._ORIGIN_UL:
  4248. x_start = 0;
  4249. x_step = 1;
  4250. x_end = header.width;
  4251. y_start = 0;
  4252. y_step = 1;
  4253. y_end = header.height;
  4254. break;
  4255. case TGATools._ORIGIN_BL:
  4256. x_start = 0;
  4257. x_step = 1;
  4258. x_end = header.width;
  4259. y_start = header.height - 1;
  4260. y_step = -1;
  4261. y_end = -1;
  4262. break;
  4263. case TGATools._ORIGIN_UR:
  4264. x_start = header.width - 1;
  4265. x_step = -1;
  4266. x_end = -1;
  4267. y_start = 0;
  4268. y_step = 1;
  4269. y_end = header.height;
  4270. break;
  4271. case TGATools._ORIGIN_BR:
  4272. x_start = header.width - 1;
  4273. x_step = -1;
  4274. x_end = -1;
  4275. y_start = header.height - 1;
  4276. y_step = -1;
  4277. y_end = -1;
  4278. break;
  4279. }
  4280. // Load the specify method
  4281. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4282. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4283. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4284. };
  4285. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4286. var image = pixel_data, colormap = palettes;
  4287. var width = header.width, height = header.height;
  4288. var color, i = 0, x, y;
  4289. var imageData = new Uint8Array(width * height * 4);
  4290. for (y = y_start; y !== y_end; y += y_step) {
  4291. for (x = x_start; x !== x_end; x += x_step, i++) {
  4292. color = image[i];
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4295. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4296. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4297. }
  4298. }
  4299. return imageData;
  4300. };
  4301. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4302. var image = pixel_data;
  4303. var width = header.width, height = header.height;
  4304. var color, i = 0, x, y;
  4305. var imageData = new Uint8Array(width * height * 4);
  4306. for (y = y_start; y !== y_end; y += y_step) {
  4307. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4308. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4309. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4310. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4311. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4312. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4313. }
  4314. }
  4315. return imageData;
  4316. };
  4317. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4318. var image = pixel_data;
  4319. var width = header.width, height = header.height;
  4320. var i = 0, x, y;
  4321. var imageData = new Uint8Array(width * height * 4);
  4322. for (y = y_start; y !== y_end; y += y_step) {
  4323. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4324. imageData[(x + width * y) * 4 + 3] = 255;
  4325. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4326. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4327. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4328. }
  4329. }
  4330. return imageData;
  4331. };
  4332. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4333. var image = pixel_data;
  4334. var width = header.width, height = header.height;
  4335. var i = 0, x, y;
  4336. var imageData = new Uint8Array(width * height * 4);
  4337. for (y = y_start; y !== y_end; y += y_step) {
  4338. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4339. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4340. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4341. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4342. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4343. }
  4344. }
  4345. return imageData;
  4346. };
  4347. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4348. var image = pixel_data;
  4349. var width = header.width, height = header.height;
  4350. var color, i = 0, x, y;
  4351. var imageData = new Uint8Array(width * height * 4);
  4352. for (y = y_start; y !== y_end; y += y_step) {
  4353. for (x = x_start; x !== x_end; x += x_step, i++) {
  4354. color = image[i];
  4355. imageData[(x + width * y) * 4 + 0] = color;
  4356. imageData[(x + width * y) * 4 + 1] = color;
  4357. imageData[(x + width * y) * 4 + 2] = color;
  4358. imageData[(x + width * y) * 4 + 3] = 255;
  4359. }
  4360. }
  4361. return imageData;
  4362. };
  4363. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4364. var image = pixel_data;
  4365. var width = header.width, height = header.height;
  4366. var i = 0, x, y;
  4367. var imageData = new Uint8Array(width * height * 4);
  4368. for (y = y_start; y !== y_end; y += y_step) {
  4369. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4370. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4373. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4374. }
  4375. }
  4376. return imageData;
  4377. };
  4378. return TGATools;
  4379. }());
  4380. TGATools._TYPE_NO_DATA = 0;
  4381. TGATools._TYPE_INDEXED = 1;
  4382. TGATools._TYPE_RGB = 2;
  4383. TGATools._TYPE_GREY = 3;
  4384. TGATools._TYPE_RLE_INDEXED = 9;
  4385. TGATools._TYPE_RLE_RGB = 10;
  4386. TGATools._TYPE_RLE_GREY = 11;
  4387. TGATools._ORIGIN_MASK = 0x30;
  4388. TGATools._ORIGIN_SHIFT = 0x04;
  4389. TGATools._ORIGIN_BL = 0x00;
  4390. TGATools._ORIGIN_BR = 0x01;
  4391. TGATools._ORIGIN_UL = 0x02;
  4392. TGATools._ORIGIN_UR = 0x03;
  4393. Internals.TGATools = TGATools;
  4394. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4395. })(BABYLON || (BABYLON = {}));
  4396. //# sourceMappingURL=babylon.tools.tga.js.map
  4397. var BABYLON;
  4398. (function (BABYLON) {
  4399. var SmartArray = (function () {
  4400. function SmartArray(capacity) {
  4401. this.length = 0;
  4402. this._duplicateId = 0;
  4403. this.data = new Array(capacity);
  4404. this._id = SmartArray._GlobalId++;
  4405. }
  4406. SmartArray.prototype.push = function (value) {
  4407. this.data[this.length++] = value;
  4408. if (this.length > this.data.length) {
  4409. this.data.length *= 2;
  4410. }
  4411. if (!value.__smartArrayFlags) {
  4412. value.__smartArrayFlags = {};
  4413. }
  4414. value.__smartArrayFlags[this._id] = this._duplicateId;
  4415. };
  4416. SmartArray.prototype.pushNoDuplicate = function (value) {
  4417. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4418. return false;
  4419. }
  4420. this.push(value);
  4421. return true;
  4422. };
  4423. SmartArray.prototype.sort = function (compareFn) {
  4424. this.data.sort(compareFn);
  4425. };
  4426. SmartArray.prototype.reset = function () {
  4427. this.length = 0;
  4428. this._duplicateId++;
  4429. };
  4430. SmartArray.prototype.concat = function (array) {
  4431. if (array.length === 0) {
  4432. return;
  4433. }
  4434. if (this.length + array.length > this.data.length) {
  4435. this.data.length = (this.length + array.length) * 2;
  4436. }
  4437. for (var index = 0; index < array.length; index++) {
  4438. this.data[this.length++] = (array.data || array)[index];
  4439. }
  4440. };
  4441. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4442. if (array.length === 0) {
  4443. return;
  4444. }
  4445. if (this.length + array.length > this.data.length) {
  4446. this.data.length = (this.length + array.length) * 2;
  4447. }
  4448. for (var index = 0; index < array.length; index++) {
  4449. var item = (array.data || array)[index];
  4450. this.pushNoDuplicate(item);
  4451. }
  4452. };
  4453. SmartArray.prototype.indexOf = function (value) {
  4454. var position = this.data.indexOf(value);
  4455. if (position >= this.length) {
  4456. return -1;
  4457. }
  4458. return position;
  4459. };
  4460. return SmartArray;
  4461. }());
  4462. // Statics
  4463. SmartArray._GlobalId = 0;
  4464. BABYLON.SmartArray = SmartArray;
  4465. })(BABYLON || (BABYLON = {}));
  4466. //# sourceMappingURL=babylon.smartArray.js.map
  4467. var BABYLON;
  4468. (function (BABYLON) {
  4469. /**
  4470. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4471. * The underlying implementation relies on an associative array to ensure the best performances.
  4472. * The value can be anything including 'null' but except 'undefined'
  4473. */
  4474. var StringDictionary = (function () {
  4475. function StringDictionary() {
  4476. this._count = 0;
  4477. this._data = {};
  4478. }
  4479. /**
  4480. * This will clear this dictionary and copy the content from the 'source' one.
  4481. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4482. * @param source the dictionary to take the content from and copy to this dictionary
  4483. */
  4484. StringDictionary.prototype.copyFrom = function (source) {
  4485. var _this = this;
  4486. this.clear();
  4487. source.forEach(function (t, v) { return _this.add(t, v); });
  4488. };
  4489. /**
  4490. * Get a value based from its key
  4491. * @param key the given key to get the matching value from
  4492. * @return the value if found, otherwise undefined is returned
  4493. */
  4494. StringDictionary.prototype.get = function (key) {
  4495. var val = this._data[key];
  4496. if (val !== undefined) {
  4497. return val;
  4498. }
  4499. return undefined;
  4500. };
  4501. /**
  4502. * Get a value from its key or add it if it doesn't exist.
  4503. * This method will ensure you that a given key/data will be present in the dictionary.
  4504. * @param key the given key to get the matching value from
  4505. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4506. * The factory will only be invoked if there's no data for the given key.
  4507. * @return the value corresponding to the key.
  4508. */
  4509. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4510. var val = this.get(key);
  4511. if (val !== undefined) {
  4512. return val;
  4513. }
  4514. val = factory(key);
  4515. if (val) {
  4516. this.add(key, val);
  4517. }
  4518. return val;
  4519. };
  4520. /**
  4521. * Get a value from its key if present in the dictionary otherwise add it
  4522. * @param key the key to get the value from
  4523. * @param val if there's no such key/value pair in the dictionary add it with this value
  4524. * @return the value corresponding to the key
  4525. */
  4526. StringDictionary.prototype.getOrAdd = function (key, val) {
  4527. var curVal = this.get(key);
  4528. if (curVal !== undefined) {
  4529. return curVal;
  4530. }
  4531. this.add(key, val);
  4532. return val;
  4533. };
  4534. /**
  4535. * Check if there's a given key in the dictionary
  4536. * @param key the key to check for
  4537. * @return true if the key is present, false otherwise
  4538. */
  4539. StringDictionary.prototype.contains = function (key) {
  4540. return this._data[key] !== undefined;
  4541. };
  4542. /**
  4543. * Add a new key and its corresponding value
  4544. * @param key the key to add
  4545. * @param value the value corresponding to the key
  4546. * @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
  4547. */
  4548. StringDictionary.prototype.add = function (key, value) {
  4549. if (this._data[key] !== undefined) {
  4550. return false;
  4551. }
  4552. this._data[key] = value;
  4553. ++this._count;
  4554. return true;
  4555. };
  4556. StringDictionary.prototype.set = function (key, value) {
  4557. if (this._data[key] === undefined) {
  4558. return false;
  4559. }
  4560. this._data[key] = value;
  4561. return true;
  4562. };
  4563. /**
  4564. * Get the element of the given key and remove it from the dictionary
  4565. * @param key
  4566. */
  4567. StringDictionary.prototype.getAndRemove = function (key) {
  4568. var val = this.get(key);
  4569. if (val !== undefined) {
  4570. delete this._data[key];
  4571. --this._count;
  4572. return val;
  4573. }
  4574. return null;
  4575. };
  4576. /**
  4577. * Remove a key/value from the dictionary.
  4578. * @param key the key to remove
  4579. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4580. */
  4581. StringDictionary.prototype.remove = function (key) {
  4582. if (this.contains(key)) {
  4583. delete this._data[key];
  4584. --this._count;
  4585. return true;
  4586. }
  4587. return false;
  4588. };
  4589. /**
  4590. * Clear the whole content of the dictionary
  4591. */
  4592. StringDictionary.prototype.clear = function () {
  4593. this._data = {};
  4594. this._count = 0;
  4595. };
  4596. Object.defineProperty(StringDictionary.prototype, "count", {
  4597. get: function () {
  4598. return this._count;
  4599. },
  4600. enumerable: true,
  4601. configurable: true
  4602. });
  4603. /**
  4604. * Execute a callback on each key/val of the dictionary.
  4605. * Note that you can remove any element in this dictionary in the callback implementation
  4606. * @param callback the callback to execute on a given key/value pair
  4607. */
  4608. StringDictionary.prototype.forEach = function (callback) {
  4609. for (var cur in this._data) {
  4610. var val = this._data[cur];
  4611. callback(cur, val);
  4612. }
  4613. };
  4614. /**
  4615. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4616. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4617. * Note that you can remove any element in this dictionary in the callback implementation
  4618. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4619. */
  4620. StringDictionary.prototype.first = function (callback) {
  4621. for (var cur in this._data) {
  4622. var val = this._data[cur];
  4623. var res = callback(cur, val);
  4624. if (res) {
  4625. return res;
  4626. }
  4627. }
  4628. return null;
  4629. };
  4630. return StringDictionary;
  4631. }());
  4632. BABYLON.StringDictionary = StringDictionary;
  4633. })(BABYLON || (BABYLON = {}));
  4634. //# sourceMappingURL=babylon.stringDictionary.js.map
  4635. var BABYLON;
  4636. (function (BABYLON) {
  4637. // Screenshots
  4638. var screenshotCanvas;
  4639. var cloneValue = function (source, destinationObject) {
  4640. if (!source)
  4641. return null;
  4642. if (source instanceof BABYLON.Mesh) {
  4643. return null;
  4644. }
  4645. if (source instanceof BABYLON.SubMesh) {
  4646. return source.clone(destinationObject);
  4647. }
  4648. else if (source.clone) {
  4649. return source.clone();
  4650. }
  4651. return null;
  4652. };
  4653. var Tools = (function () {
  4654. function Tools() {
  4655. }
  4656. ;
  4657. Tools.Instantiate = function (className) {
  4658. var arr = className.split(".");
  4659. var fn = (window || this);
  4660. for (var i = 0, len = arr.length; i < len; i++) {
  4661. fn = fn[arr[i]];
  4662. }
  4663. if (typeof fn !== "function") {
  4664. return null;
  4665. }
  4666. return fn;
  4667. };
  4668. Tools.SetImmediate = function (action) {
  4669. if (window.setImmediate) {
  4670. window.setImmediate(action);
  4671. }
  4672. else {
  4673. setTimeout(action, 1);
  4674. }
  4675. };
  4676. Tools.IsExponentOfTwo = function (value) {
  4677. var count = 1;
  4678. do {
  4679. count *= 2;
  4680. } while (count < value);
  4681. return count === value;
  4682. };
  4683. Tools.GetExponentOfTwo = function (value, max) {
  4684. var count = 1;
  4685. do {
  4686. count *= 2;
  4687. } while (count < value);
  4688. if (count > max)
  4689. count = max;
  4690. return count;
  4691. };
  4692. Tools.GetFilename = function (path) {
  4693. var index = path.lastIndexOf("/");
  4694. if (index < 0)
  4695. return path;
  4696. return path.substring(index + 1);
  4697. };
  4698. Tools.GetDOMTextContent = function (element) {
  4699. var result = "";
  4700. var child = element.firstChild;
  4701. while (child) {
  4702. if (child.nodeType === 3) {
  4703. result += child.textContent;
  4704. }
  4705. child = child.nextSibling;
  4706. }
  4707. return result;
  4708. };
  4709. Tools.ToDegrees = function (angle) {
  4710. return angle * 180 / Math.PI;
  4711. };
  4712. Tools.ToRadians = function (angle) {
  4713. return angle * Math.PI / 180;
  4714. };
  4715. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4716. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4717. var output = "";
  4718. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4719. var i = 0;
  4720. var bytes = new Uint8Array(buffer);
  4721. while (i < bytes.length) {
  4722. chr1 = bytes[i++];
  4723. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4724. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4725. enc1 = chr1 >> 2;
  4726. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4727. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4728. enc4 = chr3 & 63;
  4729. if (isNaN(chr2)) {
  4730. enc3 = enc4 = 64;
  4731. }
  4732. else if (isNaN(chr3)) {
  4733. enc4 = 64;
  4734. }
  4735. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4736. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4737. }
  4738. return "data:image/png;base64," + output;
  4739. };
  4740. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4741. if (bias === void 0) { bias = null; }
  4742. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4743. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4744. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4745. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4746. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4747. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4748. }
  4749. if (bias) {
  4750. minimum.x -= minimum.x * bias.x + bias.y;
  4751. minimum.y -= minimum.y * bias.x + bias.y;
  4752. minimum.z -= minimum.z * bias.x + bias.y;
  4753. maximum.x += maximum.x * bias.x + bias.y;
  4754. maximum.y += maximum.y * bias.x + bias.y;
  4755. maximum.z += maximum.z * bias.x + bias.y;
  4756. }
  4757. return {
  4758. minimum: minimum,
  4759. maximum: maximum
  4760. };
  4761. };
  4762. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4763. if (bias === void 0) { bias = null; }
  4764. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4765. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4766. if (!stride) {
  4767. stride = 3;
  4768. }
  4769. for (var index = start; index < start + count; index++) {
  4770. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4771. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4772. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4773. }
  4774. if (bias) {
  4775. minimum.x -= minimum.x * bias.x + bias.y;
  4776. minimum.y -= minimum.y * bias.x + bias.y;
  4777. minimum.z -= minimum.z * bias.x + bias.y;
  4778. maximum.x += maximum.x * bias.x + bias.y;
  4779. maximum.y += maximum.y * bias.x + bias.y;
  4780. maximum.z += maximum.z * bias.x + bias.y;
  4781. }
  4782. return {
  4783. minimum: minimum,
  4784. maximum: maximum
  4785. };
  4786. };
  4787. Tools.Vector2ArrayFeeder = function (array) {
  4788. return function (index) {
  4789. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4790. var length = isFloatArray ? array.length / 2 : array.length;
  4791. if (index >= length) {
  4792. return null;
  4793. }
  4794. if (isFloatArray) {
  4795. var fa = array;
  4796. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4797. }
  4798. var a = array;
  4799. return a[index];
  4800. };
  4801. };
  4802. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4803. if (bias === void 0) { bias = null; }
  4804. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4805. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4806. var i = 0;
  4807. var cur = feeder(i++);
  4808. while (cur) {
  4809. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4810. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4811. cur = feeder(i++);
  4812. }
  4813. if (bias) {
  4814. minimum.x -= minimum.x * bias.x + bias.y;
  4815. minimum.y -= minimum.y * bias.x + bias.y;
  4816. maximum.x += maximum.x * bias.x + bias.y;
  4817. maximum.y += maximum.y * bias.x + bias.y;
  4818. }
  4819. return {
  4820. minimum: minimum,
  4821. maximum: maximum
  4822. };
  4823. };
  4824. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4825. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4826. return undefined;
  4827. return Array.isArray(obj) ? obj : [obj];
  4828. };
  4829. // Misc.
  4830. Tools.GetPointerPrefix = function () {
  4831. var eventPrefix = "pointer";
  4832. // Check if pointer events are supported
  4833. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4834. eventPrefix = "mouse";
  4835. }
  4836. return eventPrefix;
  4837. };
  4838. /**
  4839. * @param func - the function to be called
  4840. * @param requester - the object that will request the next frame. Falls back to window.
  4841. */
  4842. Tools.QueueNewFrame = function (func, requester) {
  4843. if (requester === void 0) { requester = window; }
  4844. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4845. /*if(requester.isPresenting) {
  4846. return;
  4847. } else*/ if (requester.requestAnimationFrame)
  4848. requester.requestAnimationFrame(func);
  4849. else if (requester.msRequestAnimationFrame)
  4850. requester.msRequestAnimationFrame(func);
  4851. else if (requester.webkitRequestAnimationFrame)
  4852. requester.webkitRequestAnimationFrame(func);
  4853. else if (requester.mozRequestAnimationFrame)
  4854. requester.mozRequestAnimationFrame(func);
  4855. else if (requester.oRequestAnimationFrame)
  4856. requester.oRequestAnimationFrame(func);
  4857. else {
  4858. window.setTimeout(func, 16);
  4859. }
  4860. };
  4861. Tools.RequestFullscreen = function (element) {
  4862. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4863. if (!requestFunction)
  4864. return;
  4865. requestFunction.call(element);
  4866. };
  4867. Tools.ExitFullscreen = function () {
  4868. if (document.exitFullscreen) {
  4869. document.exitFullscreen();
  4870. }
  4871. else if (document.mozCancelFullScreen) {
  4872. document.mozCancelFullScreen();
  4873. }
  4874. else if (document.webkitCancelFullScreen) {
  4875. document.webkitCancelFullScreen();
  4876. }
  4877. else if (document.msCancelFullScreen) {
  4878. document.msCancelFullScreen();
  4879. }
  4880. };
  4881. Tools.SetCorsBehavior = function (url, img) {
  4882. if (Tools.CorsBehavior) {
  4883. switch (typeof (Tools.CorsBehavior)) {
  4884. case "function":
  4885. var result = Tools.CorsBehavior(url);
  4886. if (result) {
  4887. return result;
  4888. }
  4889. break;
  4890. case "string":
  4891. default:
  4892. img.crossOrigin = Tools.CorsBehavior;
  4893. break;
  4894. }
  4895. }
  4896. };
  4897. // External files
  4898. Tools.CleanUrl = function (url) {
  4899. url = url.replace(/#/mg, "%23");
  4900. return url;
  4901. };
  4902. Tools.LoadImage = function (url, onload, onerror, database) {
  4903. if (url instanceof ArrayBuffer) {
  4904. url = Tools.EncodeArrayBufferTobase64(url);
  4905. }
  4906. url = Tools.CleanUrl(url);
  4907. var img = new Image();
  4908. if (url.substr(0, 5) !== "data:") {
  4909. Tools.SetCorsBehavior(url, img);
  4910. }
  4911. img.onload = function () {
  4912. onload(img);
  4913. };
  4914. img.onerror = function (err) {
  4915. Tools.Error("Error while trying to load image: " + url);
  4916. if (Tools.UseFallbackTexture) {
  4917. img.src = Tools.fallbackTexture;
  4918. onload(img);
  4919. }
  4920. else {
  4921. onerror();
  4922. }
  4923. };
  4924. var noIndexedDB = function () {
  4925. img.src = url;
  4926. };
  4927. var loadFromIndexedDB = function () {
  4928. database.loadImageFromDB(url, img);
  4929. };
  4930. //ANY database to do!
  4931. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4932. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4933. }
  4934. else {
  4935. if (url.indexOf("file:") === -1) {
  4936. noIndexedDB();
  4937. }
  4938. else {
  4939. var textureName = url.substring(5).toLowerCase();
  4940. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  4941. try {
  4942. var blobURL;
  4943. try {
  4944. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4945. }
  4946. catch (ex) {
  4947. // Chrome doesn't support oneTimeOnly parameter
  4948. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4949. }
  4950. img.src = blobURL;
  4951. }
  4952. catch (e) {
  4953. img.src = null;
  4954. }
  4955. }
  4956. else {
  4957. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  4958. img.src = Tools.fallbackTexture;
  4959. }
  4960. }
  4961. }
  4962. return img;
  4963. };
  4964. //ANY
  4965. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4966. url = Tools.CleanUrl(url);
  4967. var noIndexedDB = function () {
  4968. var request = new XMLHttpRequest();
  4969. var loadUrl = Tools.BaseUrl + url;
  4970. request.open('GET', loadUrl, true);
  4971. if (useArrayBuffer) {
  4972. request.responseType = "arraybuffer";
  4973. }
  4974. request.onprogress = progressCallBack;
  4975. request.onreadystatechange = function () {
  4976. if (request.readyState === 4) {
  4977. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4978. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4979. callback(!useArrayBuffer ? request.responseText : request.response);
  4980. }
  4981. else {
  4982. if (onError) {
  4983. onError();
  4984. }
  4985. else {
  4986. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4987. }
  4988. }
  4989. }
  4990. };
  4991. request.send(null);
  4992. };
  4993. var loadFromIndexedDB = function () {
  4994. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4995. };
  4996. if (url.indexOf("file:") !== -1) {
  4997. var fileName = url.substring(5).toLowerCase();
  4998. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  4999. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5000. }
  5001. else {
  5002. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5003. }
  5004. }
  5005. else {
  5006. // Caching all files
  5007. if (database && database.enableSceneOffline) {
  5008. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5009. }
  5010. else {
  5011. noIndexedDB();
  5012. }
  5013. }
  5014. };
  5015. /**
  5016. * Load a script (identified by an url). When the url returns, the
  5017. * content of this file is added into a new script element, attached to the DOM (body element)
  5018. */
  5019. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5020. var head = document.getElementsByTagName('head')[0];
  5021. var script = document.createElement('script');
  5022. script.type = 'text/javascript';
  5023. script.src = scriptUrl;
  5024. var self = this;
  5025. script.onload = function () {
  5026. if (onSuccess) {
  5027. onSuccess();
  5028. }
  5029. };
  5030. script.onerror = function () {
  5031. if (onError) {
  5032. onError();
  5033. }
  5034. };
  5035. head.appendChild(script);
  5036. };
  5037. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5038. var reader = new FileReader();
  5039. reader.onload = function (e) {
  5040. //target doesn't have result from ts 1.3
  5041. callback(e.target['result']);
  5042. };
  5043. reader.onprogress = progressCallback;
  5044. reader.readAsDataURL(fileToLoad);
  5045. };
  5046. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5047. var reader = new FileReader();
  5048. reader.onerror = function (e) {
  5049. Tools.Log("Error while reading file: " + fileToLoad.name);
  5050. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5051. };
  5052. reader.onload = function (e) {
  5053. //target doesn't have result from ts 1.3
  5054. callback(e.target['result']);
  5055. };
  5056. reader.onprogress = progressCallBack;
  5057. if (!useArrayBuffer) {
  5058. // Asynchronous read
  5059. reader.readAsText(fileToLoad);
  5060. }
  5061. else {
  5062. reader.readAsArrayBuffer(fileToLoad);
  5063. }
  5064. };
  5065. //returns a downloadable url to a file content.
  5066. Tools.FileAsURL = function (content) {
  5067. var fileBlob = new Blob([content]);
  5068. var url = window.URL || window.webkitURL;
  5069. var link = url.createObjectURL(fileBlob);
  5070. return link;
  5071. };
  5072. // Misc.
  5073. Tools.Format = function (value, decimals) {
  5074. if (decimals === void 0) { decimals = 2; }
  5075. return value.toFixed(decimals);
  5076. };
  5077. Tools.CheckExtends = function (v, min, max) {
  5078. if (v.x < min.x)
  5079. min.x = v.x;
  5080. if (v.y < min.y)
  5081. min.y = v.y;
  5082. if (v.z < min.z)
  5083. min.z = v.z;
  5084. if (v.x > max.x)
  5085. max.x = v.x;
  5086. if (v.y > max.y)
  5087. max.y = v.y;
  5088. if (v.z > max.z)
  5089. max.z = v.z;
  5090. };
  5091. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5092. for (var prop in source) {
  5093. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5094. continue;
  5095. }
  5096. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5097. continue;
  5098. }
  5099. var sourceValue = source[prop];
  5100. var typeOfSourceValue = typeof sourceValue;
  5101. if (typeOfSourceValue === "function") {
  5102. continue;
  5103. }
  5104. if (typeOfSourceValue === "object") {
  5105. if (sourceValue instanceof Array) {
  5106. destination[prop] = [];
  5107. if (sourceValue.length > 0) {
  5108. if (typeof sourceValue[0] == "object") {
  5109. for (var index = 0; index < sourceValue.length; index++) {
  5110. var clonedValue = cloneValue(sourceValue[index], destination);
  5111. if (destination[prop].indexOf(clonedValue) === -1) {
  5112. destination[prop].push(clonedValue);
  5113. }
  5114. }
  5115. }
  5116. else {
  5117. destination[prop] = sourceValue.slice(0);
  5118. }
  5119. }
  5120. }
  5121. else {
  5122. destination[prop] = cloneValue(sourceValue, destination);
  5123. }
  5124. }
  5125. else {
  5126. destination[prop] = sourceValue;
  5127. }
  5128. }
  5129. };
  5130. Tools.IsEmpty = function (obj) {
  5131. for (var i in obj) {
  5132. return false;
  5133. }
  5134. return true;
  5135. };
  5136. Tools.RegisterTopRootEvents = function (events) {
  5137. for (var index = 0; index < events.length; index++) {
  5138. var event = events[index];
  5139. window.addEventListener(event.name, event.handler, false);
  5140. try {
  5141. if (window.parent) {
  5142. window.parent.addEventListener(event.name, event.handler, false);
  5143. }
  5144. }
  5145. catch (e) {
  5146. }
  5147. }
  5148. };
  5149. Tools.UnregisterTopRootEvents = function (events) {
  5150. for (var index = 0; index < events.length; index++) {
  5151. var event = events[index];
  5152. window.removeEventListener(event.name, event.handler);
  5153. try {
  5154. if (window.parent) {
  5155. window.parent.removeEventListener(event.name, event.handler);
  5156. }
  5157. }
  5158. catch (e) {
  5159. }
  5160. }
  5161. };
  5162. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5163. if (mimeType === void 0) { mimeType = "image/png"; }
  5164. // Read the contents of the framebuffer
  5165. var numberOfChannelsByLine = width * 4;
  5166. var halfHeight = height / 2;
  5167. //Reading datas from WebGL
  5168. var data = engine.readPixels(0, 0, width, height);
  5169. //To flip image on Y axis.
  5170. for (var i = 0; i < halfHeight; i++) {
  5171. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5172. var currentCell = j + i * numberOfChannelsByLine;
  5173. var targetLine = height - i - 1;
  5174. var targetCell = j + targetLine * numberOfChannelsByLine;
  5175. var temp = data[currentCell];
  5176. data[currentCell] = data[targetCell];
  5177. data[targetCell] = temp;
  5178. }
  5179. }
  5180. // Create a 2D canvas to store the result
  5181. if (!screenshotCanvas) {
  5182. screenshotCanvas = document.createElement('canvas');
  5183. }
  5184. screenshotCanvas.width = width;
  5185. screenshotCanvas.height = height;
  5186. var context = screenshotCanvas.getContext('2d');
  5187. // Copy the pixels to a 2D canvas
  5188. var imageData = context.createImageData(width, height);
  5189. var castData = (imageData.data);
  5190. castData.set(data);
  5191. context.putImageData(imageData, 0, 0);
  5192. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5193. };
  5194. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5195. if (mimeType === void 0) { mimeType = "image/png"; }
  5196. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5197. if (successCallback) {
  5198. successCallback(base64Image);
  5199. }
  5200. else {
  5201. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5202. if (("download" in document.createElement("a"))) {
  5203. var a = window.document.createElement("a");
  5204. a.href = base64Image;
  5205. var date = new Date();
  5206. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5207. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5208. window.document.body.appendChild(a);
  5209. a.addEventListener("click", function () {
  5210. a.parentElement.removeChild(a);
  5211. });
  5212. a.click();
  5213. }
  5214. else {
  5215. var newWindow = window.open("");
  5216. var img = newWindow.document.createElement("img");
  5217. img.src = base64Image;
  5218. newWindow.document.body.appendChild(img);
  5219. }
  5220. }
  5221. };
  5222. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5223. if (mimeType === void 0) { mimeType = "image/png"; }
  5224. var width;
  5225. var height;
  5226. // If a precision value is specified
  5227. if (size.precision) {
  5228. width = Math.round(engine.getRenderWidth() * size.precision);
  5229. height = Math.round(width / engine.getAspectRatio(camera));
  5230. }
  5231. else if (size.width && size.height) {
  5232. width = size.width;
  5233. height = size.height;
  5234. }
  5235. else if (size.width && !size.height) {
  5236. width = size.width;
  5237. height = Math.round(width / engine.getAspectRatio(camera));
  5238. }
  5239. else if (size.height && !size.width) {
  5240. height = size.height;
  5241. width = Math.round(height * engine.getAspectRatio(camera));
  5242. }
  5243. else if (!isNaN(size)) {
  5244. height = size;
  5245. width = size;
  5246. }
  5247. else {
  5248. Tools.Error("Invalid 'size' parameter !");
  5249. return;
  5250. }
  5251. if (!screenshotCanvas) {
  5252. screenshotCanvas = document.createElement('canvas');
  5253. }
  5254. screenshotCanvas.width = width;
  5255. screenshotCanvas.height = height;
  5256. var renderContext = screenshotCanvas.getContext("2d");
  5257. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5258. var newWidth = width;
  5259. var newHeight = newWidth / ratio;
  5260. if (newHeight > height) {
  5261. newHeight = height;
  5262. newWidth = newHeight * ratio;
  5263. }
  5264. var offsetX = Math.max(0, width - newWidth) / 2;
  5265. var offsetY = Math.max(0, height - newHeight) / 2;
  5266. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5267. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5268. };
  5269. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5270. if (mimeType === void 0) { mimeType = "image/png"; }
  5271. var width;
  5272. var height;
  5273. //If a precision value is specified
  5274. if (size.precision) {
  5275. width = Math.round(engine.getRenderWidth() * size.precision);
  5276. height = Math.round(width / engine.getAspectRatio(camera));
  5277. size = { width: width, height: height };
  5278. }
  5279. else if (size.width && size.height) {
  5280. width = size.width;
  5281. height = size.height;
  5282. }
  5283. else if (size.width && !size.height) {
  5284. width = size.width;
  5285. height = Math.round(width / engine.getAspectRatio(camera));
  5286. size = { width: width, height: height };
  5287. }
  5288. else if (size.height && !size.width) {
  5289. height = size.height;
  5290. width = Math.round(height * engine.getAspectRatio(camera));
  5291. size = { width: width, height: height };
  5292. }
  5293. else if (!isNaN(size)) {
  5294. height = size;
  5295. width = size;
  5296. }
  5297. else {
  5298. Tools.Error("Invalid 'size' parameter !");
  5299. return;
  5300. }
  5301. var scene = camera.getScene();
  5302. var previousCamera = null;
  5303. if (scene.activeCamera !== camera) {
  5304. previousCamera = scene.activeCamera;
  5305. scene.activeCamera = camera;
  5306. }
  5307. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5308. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5309. texture.renderList = scene.meshes;
  5310. texture.onAfterRenderObservable.add(function () {
  5311. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5312. });
  5313. scene.incrementRenderId();
  5314. scene.resetCachedMaterial();
  5315. texture.render(true);
  5316. texture.dispose();
  5317. if (previousCamera) {
  5318. scene.activeCamera = previousCamera;
  5319. }
  5320. camera.getProjectionMatrix(true); // Force cache refresh;
  5321. };
  5322. // XHR response validator for local file scenario
  5323. Tools.ValidateXHRData = function (xhr, dataType) {
  5324. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5325. if (dataType === void 0) { dataType = 7; }
  5326. try {
  5327. if (dataType & 1) {
  5328. if (xhr.responseText && xhr.responseText.length > 0) {
  5329. return true;
  5330. }
  5331. else if (dataType === 1) {
  5332. return false;
  5333. }
  5334. }
  5335. if (dataType & 2) {
  5336. // Check header width and height since there is no "TGA" magic number
  5337. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5338. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5339. return true;
  5340. }
  5341. else if (dataType === 2) {
  5342. return false;
  5343. }
  5344. }
  5345. if (dataType & 4) {
  5346. // Check for the "DDS" magic number
  5347. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5348. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5349. return true;
  5350. }
  5351. else {
  5352. return false;
  5353. }
  5354. }
  5355. }
  5356. catch (e) {
  5357. }
  5358. return false;
  5359. };
  5360. /**
  5361. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5362. * Be aware Math.random() could cause collisions, but:
  5363. * "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"
  5364. */
  5365. Tools.RandomId = function () {
  5366. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5367. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5368. return v.toString(16);
  5369. });
  5370. };
  5371. Object.defineProperty(Tools, "NoneLogLevel", {
  5372. get: function () {
  5373. return Tools._NoneLogLevel;
  5374. },
  5375. enumerable: true,
  5376. configurable: true
  5377. });
  5378. Object.defineProperty(Tools, "MessageLogLevel", {
  5379. get: function () {
  5380. return Tools._MessageLogLevel;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Object.defineProperty(Tools, "WarningLogLevel", {
  5386. get: function () {
  5387. return Tools._WarningLogLevel;
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. Object.defineProperty(Tools, "ErrorLogLevel", {
  5393. get: function () {
  5394. return Tools._ErrorLogLevel;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Object.defineProperty(Tools, "AllLogLevel", {
  5400. get: function () {
  5401. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5402. },
  5403. enumerable: true,
  5404. configurable: true
  5405. });
  5406. Tools._AddLogEntry = function (entry) {
  5407. Tools._LogCache = entry + Tools._LogCache;
  5408. if (Tools.OnNewCacheEntry) {
  5409. Tools.OnNewCacheEntry(entry);
  5410. }
  5411. };
  5412. Tools._FormatMessage = function (message) {
  5413. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5414. var date = new Date();
  5415. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5416. };
  5417. Tools._LogDisabled = function (message) {
  5418. // nothing to do
  5419. };
  5420. Tools._LogEnabled = function (message) {
  5421. var formattedMessage = Tools._FormatMessage(message);
  5422. console.log("BJS - " + formattedMessage);
  5423. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5424. Tools._AddLogEntry(entry);
  5425. };
  5426. Tools._WarnDisabled = function (message) {
  5427. // nothing to do
  5428. };
  5429. Tools._WarnEnabled = function (message) {
  5430. var formattedMessage = Tools._FormatMessage(message);
  5431. console.warn("BJS - " + formattedMessage);
  5432. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5433. Tools._AddLogEntry(entry);
  5434. };
  5435. Tools._ErrorDisabled = function (message) {
  5436. // nothing to do
  5437. };
  5438. Tools._ErrorEnabled = function (message) {
  5439. Tools.errorsCount++;
  5440. var formattedMessage = Tools._FormatMessage(message);
  5441. console.error("BJS - " + formattedMessage);
  5442. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5443. Tools._AddLogEntry(entry);
  5444. };
  5445. Object.defineProperty(Tools, "LogCache", {
  5446. get: function () {
  5447. return Tools._LogCache;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Tools.ClearLogCache = function () {
  5453. Tools._LogCache = "";
  5454. Tools.errorsCount = 0;
  5455. };
  5456. Object.defineProperty(Tools, "LogLevels", {
  5457. set: function (level) {
  5458. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5459. Tools.Log = Tools._LogEnabled;
  5460. }
  5461. else {
  5462. Tools.Log = Tools._LogDisabled;
  5463. }
  5464. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5465. Tools.Warn = Tools._WarnEnabled;
  5466. }
  5467. else {
  5468. Tools.Warn = Tools._WarnDisabled;
  5469. }
  5470. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5471. Tools.Error = Tools._ErrorEnabled;
  5472. }
  5473. else {
  5474. Tools.Error = Tools._ErrorDisabled;
  5475. }
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5481. get: function () {
  5482. return Tools._PerformanceNoneLogLevel;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5488. get: function () {
  5489. return Tools._PerformanceUserMarkLogLevel;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5495. get: function () {
  5496. return Tools._PerformanceConsoleLogLevel;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5502. set: function (level) {
  5503. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5504. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5505. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5506. return;
  5507. }
  5508. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5509. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5510. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5511. return;
  5512. }
  5513. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5514. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5515. },
  5516. enumerable: true,
  5517. configurable: true
  5518. });
  5519. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5520. };
  5521. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5522. };
  5523. Tools._StartUserMark = function (counterName, condition) {
  5524. if (condition === void 0) { condition = true; }
  5525. if (!condition || !Tools._performance.mark) {
  5526. return;
  5527. }
  5528. Tools._performance.mark(counterName + "-Begin");
  5529. };
  5530. Tools._EndUserMark = function (counterName, condition) {
  5531. if (condition === void 0) { condition = true; }
  5532. if (!condition || !Tools._performance.mark) {
  5533. return;
  5534. }
  5535. Tools._performance.mark(counterName + "-End");
  5536. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5537. };
  5538. Tools._StartPerformanceConsole = function (counterName, condition) {
  5539. if (condition === void 0) { condition = true; }
  5540. if (!condition) {
  5541. return;
  5542. }
  5543. Tools._StartUserMark(counterName, condition);
  5544. if (console.time) {
  5545. console.time(counterName);
  5546. }
  5547. };
  5548. Tools._EndPerformanceConsole = function (counterName, condition) {
  5549. if (condition === void 0) { condition = true; }
  5550. if (!condition) {
  5551. return;
  5552. }
  5553. Tools._EndUserMark(counterName, condition);
  5554. if (console.time) {
  5555. console.timeEnd(counterName);
  5556. }
  5557. };
  5558. Object.defineProperty(Tools, "Now", {
  5559. get: function () {
  5560. if (window.performance && window.performance.now) {
  5561. return window.performance.now();
  5562. }
  5563. return new Date().getTime();
  5564. },
  5565. enumerable: true,
  5566. configurable: true
  5567. });
  5568. /**
  5569. * This method will return the name of the class used to create the instance of the given object.
  5570. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5571. * @param object the object to get the class name from
  5572. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5573. */
  5574. Tools.getClassName = function (object, isType) {
  5575. if (isType === void 0) { isType = false; }
  5576. var name = null;
  5577. if (!isType && object.getClassName) {
  5578. name = object.getClassName();
  5579. }
  5580. else {
  5581. if (object instanceof Object) {
  5582. var classObj = isType ? object : Object.getPrototypeOf(object);
  5583. name = classObj.constructor["__bjsclassName__"];
  5584. }
  5585. if (!name) {
  5586. name = typeof object;
  5587. }
  5588. }
  5589. return name;
  5590. };
  5591. Tools.first = function (array, predicate) {
  5592. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5593. var el = array_1[_i];
  5594. if (predicate(el)) {
  5595. return el;
  5596. }
  5597. }
  5598. };
  5599. /**
  5600. * This method will return the name of the full name of the class, including its owning module (if any).
  5601. * 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).
  5602. * @param object the object to get the class name from
  5603. * @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.
  5604. */
  5605. Tools.getFullClassName = function (object, isType) {
  5606. if (isType === void 0) { isType = false; }
  5607. var className = null;
  5608. var moduleName = null;
  5609. if (!isType && object.getClassName) {
  5610. className = object.getClassName();
  5611. }
  5612. else {
  5613. if (object instanceof Object) {
  5614. var classObj = isType ? object : Object.getPrototypeOf(object);
  5615. className = classObj.constructor["__bjsclassName__"];
  5616. moduleName = classObj.constructor["__bjsmoduleName__"];
  5617. }
  5618. if (!className) {
  5619. className = typeof object;
  5620. }
  5621. }
  5622. if (!className) {
  5623. return null;
  5624. }
  5625. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5626. };
  5627. /**
  5628. * 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.
  5629. * @param array
  5630. */
  5631. Tools.arrayOrStringFeeder = function (array) {
  5632. return function (index) {
  5633. if (index >= array.length) {
  5634. return null;
  5635. }
  5636. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5637. if (val && val.getHashCode) {
  5638. val = val.getHashCode();
  5639. }
  5640. if (typeof val === "string") {
  5641. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5642. }
  5643. return val;
  5644. };
  5645. };
  5646. /**
  5647. * Compute the hashCode of a stream of number
  5648. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5649. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5650. * @return the hash code computed
  5651. */
  5652. Tools.hashCodeFromStream = function (feeder) {
  5653. // Based from here: http://stackoverflow.com/a/7616484/802124
  5654. var hash = 0;
  5655. var index = 0;
  5656. var chr = feeder(index++);
  5657. while (chr != null) {
  5658. hash = ((hash << 5) - hash) + chr;
  5659. hash |= 0; // Convert to 32bit integer
  5660. chr = feeder(index++);
  5661. }
  5662. return hash;
  5663. };
  5664. return Tools;
  5665. }());
  5666. Tools.BaseUrl = "";
  5667. Tools.CorsBehavior = "anonymous";
  5668. Tools.UseFallbackTexture = true;
  5669. // Used in case of a texture loading problem
  5670. 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";
  5671. // Logs
  5672. Tools._NoneLogLevel = 0;
  5673. Tools._MessageLogLevel = 1;
  5674. Tools._WarningLogLevel = 2;
  5675. Tools._ErrorLogLevel = 4;
  5676. Tools._LogCache = "";
  5677. Tools.errorsCount = 0;
  5678. Tools.Log = Tools._LogEnabled;
  5679. Tools.Warn = Tools._WarnEnabled;
  5680. Tools.Error = Tools._ErrorEnabled;
  5681. // Performances
  5682. Tools._PerformanceNoneLogLevel = 0;
  5683. Tools._PerformanceUserMarkLogLevel = 1;
  5684. Tools._PerformanceConsoleLogLevel = 2;
  5685. Tools._performance = window.performance;
  5686. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5687. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5688. BABYLON.Tools = Tools;
  5689. /**
  5690. * This class is used to track a performance counter which is number based.
  5691. * The user has access to many properties which give statistics of different nature
  5692. *
  5693. * The implementer can track two kinds of Performance Counter: time and count
  5694. * 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.
  5695. * 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.
  5696. */
  5697. var PerfCounter = (function () {
  5698. function PerfCounter() {
  5699. this._startMonitoringTime = 0;
  5700. this._min = 0;
  5701. this._max = 0;
  5702. this._average = 0;
  5703. this._lastSecAverage = 0;
  5704. this._current = 0;
  5705. this._totalValueCount = 0;
  5706. this._totalAccumulated = 0;
  5707. this._lastSecAccumulated = 0;
  5708. this._lastSecTime = 0;
  5709. this._lastSecValueCount = 0;
  5710. }
  5711. Object.defineProperty(PerfCounter.prototype, "min", {
  5712. /**
  5713. * Returns the smallest value ever
  5714. */
  5715. get: function () {
  5716. return this._min;
  5717. },
  5718. enumerable: true,
  5719. configurable: true
  5720. });
  5721. Object.defineProperty(PerfCounter.prototype, "max", {
  5722. /**
  5723. * Returns the biggest value ever
  5724. */
  5725. get: function () {
  5726. return this._max;
  5727. },
  5728. enumerable: true,
  5729. configurable: true
  5730. });
  5731. Object.defineProperty(PerfCounter.prototype, "average", {
  5732. /**
  5733. * Returns the average value since the performance counter is running
  5734. */
  5735. get: function () {
  5736. return this._average;
  5737. },
  5738. enumerable: true,
  5739. configurable: true
  5740. });
  5741. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5742. /**
  5743. * Returns the average value of the last second the counter was monitored
  5744. */
  5745. get: function () {
  5746. return this._lastSecAverage;
  5747. },
  5748. enumerable: true,
  5749. configurable: true
  5750. });
  5751. Object.defineProperty(PerfCounter.prototype, "current", {
  5752. /**
  5753. * Returns the current value
  5754. */
  5755. get: function () {
  5756. return this._current;
  5757. },
  5758. enumerable: true,
  5759. configurable: true
  5760. });
  5761. Object.defineProperty(PerfCounter.prototype, "total", {
  5762. get: function () {
  5763. return this._totalAccumulated;
  5764. },
  5765. enumerable: true,
  5766. configurable: true
  5767. });
  5768. /**
  5769. * Call this method to start monitoring a new frame.
  5770. * 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.
  5771. */
  5772. PerfCounter.prototype.fetchNewFrame = function () {
  5773. this._totalValueCount++;
  5774. this._current = 0;
  5775. this._lastSecValueCount++;
  5776. };
  5777. /**
  5778. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5779. * @param newCount the count value to add to the monitored count
  5780. * @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.
  5781. */
  5782. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5783. this._current += newCount;
  5784. if (fetchResult) {
  5785. this._fetchResult();
  5786. }
  5787. };
  5788. /**
  5789. * Start monitoring this performance counter
  5790. */
  5791. PerfCounter.prototype.beginMonitoring = function () {
  5792. this._startMonitoringTime = Tools.Now;
  5793. };
  5794. /**
  5795. * Compute the time lapsed since the previous beginMonitoring() call.
  5796. * @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
  5797. */
  5798. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5799. if (newFrame === void 0) { newFrame = true; }
  5800. if (newFrame) {
  5801. this.fetchNewFrame();
  5802. }
  5803. var currentTime = Tools.Now;
  5804. this._current = currentTime - this._startMonitoringTime;
  5805. if (newFrame) {
  5806. this._fetchResult();
  5807. }
  5808. };
  5809. PerfCounter.prototype._fetchResult = function () {
  5810. this._totalAccumulated += this._current;
  5811. this._lastSecAccumulated += this._current;
  5812. // Min/Max update
  5813. this._min = Math.min(this._min, this._current);
  5814. this._max = Math.max(this._max, this._current);
  5815. this._average = this._totalAccumulated / this._totalValueCount;
  5816. // Reset last sec?
  5817. var now = Tools.Now;
  5818. if ((now - this._lastSecTime) > 1000) {
  5819. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5820. this._lastSecTime = now;
  5821. this._lastSecAccumulated = 0;
  5822. this._lastSecValueCount = 0;
  5823. }
  5824. };
  5825. return PerfCounter;
  5826. }());
  5827. BABYLON.PerfCounter = PerfCounter;
  5828. /**
  5829. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5830. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5831. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5832. * @param name The name of the class, case should be preserved
  5833. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5834. */
  5835. function className(name, module) {
  5836. return function (target) {
  5837. target["__bjsclassName__"] = name;
  5838. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5839. };
  5840. }
  5841. BABYLON.className = className;
  5842. /**
  5843. * An implementation of a loop for asynchronous functions.
  5844. */
  5845. var AsyncLoop = (function () {
  5846. /**
  5847. * Constroctor.
  5848. * @param iterations the number of iterations.
  5849. * @param _fn the function to run each iteration
  5850. * @param _successCallback the callback that will be called upon succesful execution
  5851. * @param offset starting offset.
  5852. */
  5853. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5854. if (offset === void 0) { offset = 0; }
  5855. this.iterations = iterations;
  5856. this._fn = _fn;
  5857. this._successCallback = _successCallback;
  5858. this.index = offset - 1;
  5859. this._done = false;
  5860. }
  5861. /**
  5862. * Execute the next iteration. Must be called after the last iteration was finished.
  5863. */
  5864. AsyncLoop.prototype.executeNext = function () {
  5865. if (!this._done) {
  5866. if (this.index + 1 < this.iterations) {
  5867. ++this.index;
  5868. this._fn(this);
  5869. }
  5870. else {
  5871. this.breakLoop();
  5872. }
  5873. }
  5874. };
  5875. /**
  5876. * Break the loop and run the success callback.
  5877. */
  5878. AsyncLoop.prototype.breakLoop = function () {
  5879. this._done = true;
  5880. this._successCallback();
  5881. };
  5882. /**
  5883. * Helper function
  5884. */
  5885. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5886. if (offset === void 0) { offset = 0; }
  5887. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5888. loop.executeNext();
  5889. return loop;
  5890. };
  5891. /**
  5892. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5893. * @param iterations total number of iterations
  5894. * @param syncedIterations number of synchronous iterations in each async iteration.
  5895. * @param fn the function to call each iteration.
  5896. * @param callback a success call back that will be called when iterating stops.
  5897. * @param breakFunction a break condition (optional)
  5898. * @param timeout timeout settings for the setTimeout function. default - 0.
  5899. * @constructor
  5900. */
  5901. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5902. if (timeout === void 0) { timeout = 0; }
  5903. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5904. if (breakFunction && breakFunction())
  5905. loop.breakLoop();
  5906. else {
  5907. setTimeout(function () {
  5908. for (var i = 0; i < syncedIterations; ++i) {
  5909. var iteration = (loop.index * syncedIterations) + i;
  5910. if (iteration >= iterations)
  5911. break;
  5912. fn(iteration);
  5913. if (breakFunction && breakFunction()) {
  5914. loop.breakLoop();
  5915. break;
  5916. }
  5917. }
  5918. loop.executeNext();
  5919. }, timeout);
  5920. }
  5921. }, callback);
  5922. };
  5923. return AsyncLoop;
  5924. }());
  5925. BABYLON.AsyncLoop = AsyncLoop;
  5926. })(BABYLON || (BABYLON = {}));
  5927. //# sourceMappingURL=babylon.tools.js.map
  5928. var BABYLON;
  5929. (function (BABYLON) {
  5930. var Internals;
  5931. (function (Internals) {
  5932. var _AlphaState = (function () {
  5933. /**
  5934. * Initializes the state.
  5935. */
  5936. function _AlphaState() {
  5937. this._isAlphaBlendDirty = false;
  5938. this._isBlendFunctionParametersDirty = false;
  5939. this._alphaBlend = false;
  5940. this._blendFunctionParameters = new Array(4);
  5941. this.reset();
  5942. }
  5943. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5944. get: function () {
  5945. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5946. },
  5947. enumerable: true,
  5948. configurable: true
  5949. });
  5950. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5951. get: function () {
  5952. return this._alphaBlend;
  5953. },
  5954. set: function (value) {
  5955. if (this._alphaBlend === value) {
  5956. return;
  5957. }
  5958. this._alphaBlend = value;
  5959. this._isAlphaBlendDirty = true;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5965. if (this._blendFunctionParameters[0] === value0 &&
  5966. this._blendFunctionParameters[1] === value1 &&
  5967. this._blendFunctionParameters[2] === value2 &&
  5968. this._blendFunctionParameters[3] === value3) {
  5969. return;
  5970. }
  5971. this._blendFunctionParameters[0] = value0;
  5972. this._blendFunctionParameters[1] = value1;
  5973. this._blendFunctionParameters[2] = value2;
  5974. this._blendFunctionParameters[3] = value3;
  5975. this._isBlendFunctionParametersDirty = true;
  5976. };
  5977. _AlphaState.prototype.reset = function () {
  5978. this._alphaBlend = false;
  5979. this._blendFunctionParameters[0] = null;
  5980. this._blendFunctionParameters[1] = null;
  5981. this._blendFunctionParameters[2] = null;
  5982. this._blendFunctionParameters[3] = null;
  5983. this._isAlphaBlendDirty = true;
  5984. this._isBlendFunctionParametersDirty = false;
  5985. };
  5986. _AlphaState.prototype.apply = function (gl) {
  5987. if (!this.isDirty) {
  5988. return;
  5989. }
  5990. // Alpha blend
  5991. if (this._isAlphaBlendDirty) {
  5992. if (this._alphaBlend) {
  5993. gl.enable(gl.BLEND);
  5994. }
  5995. else {
  5996. gl.disable(gl.BLEND);
  5997. }
  5998. this._isAlphaBlendDirty = false;
  5999. }
  6000. // Alpha function
  6001. if (this._isBlendFunctionParametersDirty) {
  6002. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6003. this._isBlendFunctionParametersDirty = false;
  6004. }
  6005. };
  6006. return _AlphaState;
  6007. }());
  6008. Internals._AlphaState = _AlphaState;
  6009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6010. })(BABYLON || (BABYLON = {}));
  6011. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6012. var BABYLON;
  6013. (function (BABYLON) {
  6014. var Internals;
  6015. (function (Internals) {
  6016. var _DepthCullingState = (function () {
  6017. /**
  6018. * Initializes the state.
  6019. */
  6020. function _DepthCullingState() {
  6021. this._isDepthTestDirty = false;
  6022. this._isDepthMaskDirty = false;
  6023. this._isDepthFuncDirty = false;
  6024. this._isCullFaceDirty = false;
  6025. this._isCullDirty = false;
  6026. this._isZOffsetDirty = false;
  6027. this.reset();
  6028. }
  6029. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6030. get: function () {
  6031. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6032. },
  6033. enumerable: true,
  6034. configurable: true
  6035. });
  6036. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6037. get: function () {
  6038. return this._zOffset;
  6039. },
  6040. set: function (value) {
  6041. if (this._zOffset === value) {
  6042. return;
  6043. }
  6044. this._zOffset = value;
  6045. this._isZOffsetDirty = true;
  6046. },
  6047. enumerable: true,
  6048. configurable: true
  6049. });
  6050. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6051. get: function () {
  6052. return this._cullFace;
  6053. },
  6054. set: function (value) {
  6055. if (this._cullFace === value) {
  6056. return;
  6057. }
  6058. this._cullFace = value;
  6059. this._isCullFaceDirty = true;
  6060. },
  6061. enumerable: true,
  6062. configurable: true
  6063. });
  6064. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6065. get: function () {
  6066. return this._cull;
  6067. },
  6068. set: function (value) {
  6069. if (this._cull === value) {
  6070. return;
  6071. }
  6072. this._cull = value;
  6073. this._isCullDirty = true;
  6074. },
  6075. enumerable: true,
  6076. configurable: true
  6077. });
  6078. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6079. get: function () {
  6080. return this._depthFunc;
  6081. },
  6082. set: function (value) {
  6083. if (this._depthFunc === value) {
  6084. return;
  6085. }
  6086. this._depthFunc = value;
  6087. this._isDepthFuncDirty = true;
  6088. },
  6089. enumerable: true,
  6090. configurable: true
  6091. });
  6092. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6093. get: function () {
  6094. return this._depthMask;
  6095. },
  6096. set: function (value) {
  6097. if (this._depthMask === value) {
  6098. return;
  6099. }
  6100. this._depthMask = value;
  6101. this._isDepthMaskDirty = true;
  6102. },
  6103. enumerable: true,
  6104. configurable: true
  6105. });
  6106. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6107. get: function () {
  6108. return this._depthTest;
  6109. },
  6110. set: function (value) {
  6111. if (this._depthTest === value) {
  6112. return;
  6113. }
  6114. this._depthTest = value;
  6115. this._isDepthTestDirty = true;
  6116. },
  6117. enumerable: true,
  6118. configurable: true
  6119. });
  6120. _DepthCullingState.prototype.reset = function () {
  6121. this._depthMask = true;
  6122. this._depthTest = true;
  6123. this._depthFunc = null;
  6124. this._cullFace = null;
  6125. this._cull = null;
  6126. this._zOffset = 0;
  6127. this._isDepthTestDirty = true;
  6128. this._isDepthMaskDirty = true;
  6129. this._isDepthFuncDirty = false;
  6130. this._isCullFaceDirty = false;
  6131. this._isCullDirty = false;
  6132. this._isZOffsetDirty = false;
  6133. };
  6134. _DepthCullingState.prototype.apply = function (gl) {
  6135. if (!this.isDirty) {
  6136. return;
  6137. }
  6138. // Cull
  6139. if (this._isCullDirty) {
  6140. if (this.cull) {
  6141. gl.enable(gl.CULL_FACE);
  6142. }
  6143. else {
  6144. gl.disable(gl.CULL_FACE);
  6145. }
  6146. this._isCullDirty = false;
  6147. }
  6148. // Cull face
  6149. if (this._isCullFaceDirty) {
  6150. gl.cullFace(this.cullFace);
  6151. this._isCullFaceDirty = false;
  6152. }
  6153. // Depth mask
  6154. if (this._isDepthMaskDirty) {
  6155. gl.depthMask(this.depthMask);
  6156. this._isDepthMaskDirty = false;
  6157. }
  6158. // Depth test
  6159. if (this._isDepthTestDirty) {
  6160. if (this.depthTest) {
  6161. gl.enable(gl.DEPTH_TEST);
  6162. }
  6163. else {
  6164. gl.disable(gl.DEPTH_TEST);
  6165. }
  6166. this._isDepthTestDirty = false;
  6167. }
  6168. // Depth func
  6169. if (this._isDepthFuncDirty) {
  6170. gl.depthFunc(this.depthFunc);
  6171. this._isDepthFuncDirty = false;
  6172. }
  6173. // zOffset
  6174. if (this._isZOffsetDirty) {
  6175. if (this.zOffset) {
  6176. gl.enable(gl.POLYGON_OFFSET_FILL);
  6177. gl.polygonOffset(this.zOffset, 0);
  6178. }
  6179. else {
  6180. gl.disable(gl.POLYGON_OFFSET_FILL);
  6181. }
  6182. this._isZOffsetDirty = false;
  6183. }
  6184. };
  6185. return _DepthCullingState;
  6186. }());
  6187. Internals._DepthCullingState = _DepthCullingState;
  6188. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6189. })(BABYLON || (BABYLON = {}));
  6190. //# sourceMappingURL=babylon.depthCullingState.js.map
  6191. var BABYLON;
  6192. (function (BABYLON) {
  6193. var Internals;
  6194. (function (Internals) {
  6195. var _StencilState = (function () {
  6196. function _StencilState() {
  6197. this._isStencilTestDirty = false;
  6198. this._isStencilMaskDirty = false;
  6199. this._isStencilFuncDirty = false;
  6200. this._isStencilOpDirty = false;
  6201. this.reset();
  6202. }
  6203. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6204. get: function () {
  6205. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6206. },
  6207. enumerable: true,
  6208. configurable: true
  6209. });
  6210. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6211. get: function () {
  6212. return this._stencilFunc;
  6213. },
  6214. set: function (value) {
  6215. if (this._stencilFunc === value) {
  6216. return;
  6217. }
  6218. this._stencilFunc = value;
  6219. this._isStencilFuncDirty = true;
  6220. },
  6221. enumerable: true,
  6222. configurable: true
  6223. });
  6224. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6225. get: function () {
  6226. return this._stencilFuncRef;
  6227. },
  6228. set: function (value) {
  6229. if (this._stencilFuncRef === value) {
  6230. return;
  6231. }
  6232. this._stencilFuncRef = value;
  6233. this._isStencilFuncDirty = true;
  6234. },
  6235. enumerable: true,
  6236. configurable: true
  6237. });
  6238. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6239. get: function () {
  6240. return this._stencilFuncMask;
  6241. },
  6242. set: function (value) {
  6243. if (this._stencilFuncMask === value) {
  6244. return;
  6245. }
  6246. this._stencilFuncMask = value;
  6247. this._isStencilFuncDirty = true;
  6248. },
  6249. enumerable: true,
  6250. configurable: true
  6251. });
  6252. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6253. get: function () {
  6254. return this._stencilOpStencilFail;
  6255. },
  6256. set: function (value) {
  6257. if (this._stencilOpStencilFail === value) {
  6258. return;
  6259. }
  6260. this._stencilOpStencilFail = value;
  6261. this._isStencilOpDirty = true;
  6262. },
  6263. enumerable: true,
  6264. configurable: true
  6265. });
  6266. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6267. get: function () {
  6268. return this._stencilOpDepthFail;
  6269. },
  6270. set: function (value) {
  6271. if (this._stencilOpDepthFail === value) {
  6272. return;
  6273. }
  6274. this._stencilOpDepthFail = value;
  6275. this._isStencilOpDirty = true;
  6276. },
  6277. enumerable: true,
  6278. configurable: true
  6279. });
  6280. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6281. get: function () {
  6282. return this._stencilOpStencilDepthPass;
  6283. },
  6284. set: function (value) {
  6285. if (this._stencilOpStencilDepthPass === value) {
  6286. return;
  6287. }
  6288. this._stencilOpStencilDepthPass = value;
  6289. this._isStencilOpDirty = true;
  6290. },
  6291. enumerable: true,
  6292. configurable: true
  6293. });
  6294. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6295. get: function () {
  6296. return this._stencilMask;
  6297. },
  6298. set: function (value) {
  6299. if (this._stencilMask === value) {
  6300. return;
  6301. }
  6302. this._stencilMask = value;
  6303. this._isStencilMaskDirty = true;
  6304. },
  6305. enumerable: true,
  6306. configurable: true
  6307. });
  6308. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6309. get: function () {
  6310. return this._stencilTest;
  6311. },
  6312. set: function (value) {
  6313. if (this._stencilTest === value) {
  6314. return;
  6315. }
  6316. this._stencilTest = value;
  6317. this._isStencilTestDirty = true;
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. _StencilState.prototype.reset = function () {
  6323. this._stencilTest = false;
  6324. this._stencilMask = 0xFF;
  6325. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6326. this._stencilFuncRef = 1;
  6327. this._stencilFuncMask = 0xFF;
  6328. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6329. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6330. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6331. this._isStencilTestDirty = true;
  6332. this._isStencilMaskDirty = true;
  6333. this._isStencilFuncDirty = true;
  6334. this._isStencilOpDirty = true;
  6335. };
  6336. _StencilState.prototype.apply = function (gl) {
  6337. if (!this.isDirty) {
  6338. return;
  6339. }
  6340. // Stencil test
  6341. if (this._isStencilTestDirty) {
  6342. if (this.stencilTest) {
  6343. gl.enable(gl.STENCIL_TEST);
  6344. }
  6345. else {
  6346. gl.disable(gl.STENCIL_TEST);
  6347. }
  6348. this._isStencilTestDirty = false;
  6349. }
  6350. // Stencil mask
  6351. if (this._isStencilMaskDirty) {
  6352. gl.stencilMask(this.stencilMask);
  6353. this._isStencilMaskDirty = false;
  6354. }
  6355. // Stencil func
  6356. if (this._isStencilFuncDirty) {
  6357. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6358. this._isStencilFuncDirty = false;
  6359. }
  6360. // Stencil op
  6361. if (this._isStencilOpDirty) {
  6362. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6363. this._isStencilOpDirty = false;
  6364. }
  6365. };
  6366. return _StencilState;
  6367. }());
  6368. Internals._StencilState = _StencilState;
  6369. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6370. })(BABYLON || (BABYLON = {}));
  6371. //# sourceMappingURL=babylon.stencilState.js.map
  6372. var BABYLON;
  6373. (function (BABYLON) {
  6374. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6375. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6376. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6377. gl.compileShader(shader);
  6378. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6379. throw new Error(gl.getShaderInfoLog(shader));
  6380. }
  6381. return shader;
  6382. };
  6383. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6384. var magFilter = gl.NEAREST;
  6385. var minFilter = gl.NEAREST;
  6386. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6387. magFilter = gl.LINEAR;
  6388. if (generateMipMaps) {
  6389. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6390. }
  6391. else {
  6392. minFilter = gl.LINEAR;
  6393. }
  6394. }
  6395. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6396. magFilter = gl.LINEAR;
  6397. if (generateMipMaps) {
  6398. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6399. }
  6400. else {
  6401. minFilter = gl.LINEAR;
  6402. }
  6403. }
  6404. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6405. magFilter = gl.NEAREST;
  6406. if (generateMipMaps) {
  6407. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6408. }
  6409. else {
  6410. minFilter = gl.NEAREST;
  6411. }
  6412. }
  6413. return {
  6414. min: minFilter,
  6415. mag: magFilter
  6416. };
  6417. };
  6418. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6420. var engine = scene.getEngine();
  6421. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6422. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6423. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6424. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6425. texture._baseWidth = width;
  6426. texture._baseHeight = height;
  6427. texture._width = potWidth;
  6428. texture._height = potHeight;
  6429. texture.isReady = true;
  6430. processFunction(potWidth, potHeight);
  6431. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6434. if (!noMipmap && !isCompressed) {
  6435. gl.generateMipmap(gl.TEXTURE_2D);
  6436. }
  6437. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6438. engine.resetTextureCache();
  6439. scene._removePendingData(texture);
  6440. texture.onLoadedCallbacks.forEach(function (callback) {
  6441. callback();
  6442. });
  6443. texture.onLoadedCallbacks = [];
  6444. };
  6445. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6446. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6447. var img;
  6448. var onload = function () {
  6449. loadedImages[index] = img;
  6450. loadedImages._internalCount++;
  6451. scene._removePendingData(img);
  6452. if (loadedImages._internalCount === 6) {
  6453. onfinish(loadedImages);
  6454. }
  6455. };
  6456. var onerror = function () {
  6457. scene._removePendingData(img);
  6458. if (onErrorCallBack) {
  6459. onErrorCallBack();
  6460. }
  6461. };
  6462. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6463. scene._addPendingData(img);
  6464. };
  6465. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6466. if (onError === void 0) { onError = null; }
  6467. var loadedImages = [];
  6468. loadedImages._internalCount = 0;
  6469. for (var index = 0; index < 6; index++) {
  6470. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6471. }
  6472. };
  6473. var InstancingAttributeInfo = (function () {
  6474. function InstancingAttributeInfo() {
  6475. }
  6476. return InstancingAttributeInfo;
  6477. }());
  6478. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6479. var EngineCapabilities = (function () {
  6480. function EngineCapabilities() {
  6481. }
  6482. return EngineCapabilities;
  6483. }());
  6484. BABYLON.EngineCapabilities = EngineCapabilities;
  6485. /**
  6486. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6487. */
  6488. var Engine = (function () {
  6489. /**
  6490. * @constructor
  6491. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6492. * @param {boolean} [antialias] - enable antialias
  6493. * @param options - further options to be sent to the getContext function
  6494. */
  6495. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6496. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6497. var _this = this;
  6498. // Public members
  6499. this.isFullscreen = false;
  6500. this.isPointerLock = false;
  6501. this.cullBackFaces = true;
  6502. this.renderEvenInBackground = true;
  6503. // To enable/disable IDB support and avoid XHR on .manifest
  6504. this.enableOfflineSupport = true;
  6505. this.scenes = new Array();
  6506. this._windowIsBackground = false;
  6507. this._webGLVersion = 1.0;
  6508. this._badOS = false;
  6509. this._drawCalls = new BABYLON.PerfCounter();
  6510. this._renderingQueueLaunched = false;
  6511. this._activeRenderLoops = [];
  6512. // FPS
  6513. this.fpsRange = 60;
  6514. this.previousFramesDuration = [];
  6515. this.fps = 60;
  6516. this.deltaTime = 0;
  6517. // States
  6518. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6519. this._stencilState = new BABYLON.Internals._StencilState();
  6520. this._alphaState = new BABYLON.Internals._AlphaState();
  6521. this._alphaMode = Engine.ALPHA_DISABLE;
  6522. // Cache
  6523. this._loadedTexturesCache = new Array();
  6524. this._maxTextureChannels = 16;
  6525. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6526. this._compiledEffects = {};
  6527. this._vertexAttribArraysEnabled = [];
  6528. this._uintIndicesCurrentlySet = false;
  6529. this._currentBoundBuffer = new Array();
  6530. this._currentBufferPointers = [];
  6531. this._currentInstanceLocations = new Array();
  6532. this._currentInstanceBuffers = new Array();
  6533. this._vaoRecordInProgress = false;
  6534. this._mustWipeVertexAttributes = false;
  6535. // Hardware supported Compressed Textures
  6536. this._texturesSupported = new Array();
  6537. this._onVRFullScreenTriggered = function () {
  6538. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6539. //get the old size before we change
  6540. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6541. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6542. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6543. //But actually, no browser follow the specs...
  6544. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6545. //get the width and height, change the render size
  6546. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6547. var width, height;
  6548. _this.setHardwareScalingLevel(1);
  6549. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6550. }
  6551. else {
  6552. //When the specs are implemented, need to uncomment this.
  6553. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6554. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6555. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6556. _this._vrDisplayEnabled = undefined;
  6557. }
  6558. };
  6559. this._renderingCanvas = canvas;
  6560. this._externalData = new BABYLON.StringDictionary();
  6561. options = options || {};
  6562. if (antialias != null) {
  6563. options.antialias = antialias;
  6564. }
  6565. if (options.preserveDrawingBuffer === undefined) {
  6566. options.preserveDrawingBuffer = false;
  6567. }
  6568. // GL
  6569. if (!options.disableWebGL2Support) {
  6570. try {
  6571. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6572. if (this._gl) {
  6573. this._webGLVersion = 2.0;
  6574. }
  6575. }
  6576. catch (e) {
  6577. }
  6578. }
  6579. if (!this._gl) {
  6580. if (!canvas) {
  6581. throw new Error("The provided canvas is null or undefined.");
  6582. }
  6583. try {
  6584. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6585. }
  6586. catch (e) {
  6587. throw new Error("WebGL not supported");
  6588. }
  6589. }
  6590. if (!this._gl) {
  6591. throw new Error("WebGL not supported");
  6592. }
  6593. this._onBlur = function () {
  6594. _this._windowIsBackground = true;
  6595. };
  6596. this._onFocus = function () {
  6597. _this._windowIsBackground = false;
  6598. };
  6599. window.addEventListener("blur", this._onBlur);
  6600. window.addEventListener("focus", this._onFocus);
  6601. // Viewport
  6602. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6603. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6604. this.resize();
  6605. // Caps
  6606. this._isStencilEnable = options.stencil;
  6607. this._caps = new EngineCapabilities();
  6608. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6609. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6610. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6611. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6612. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6613. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6614. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6615. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6616. // Infos
  6617. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6618. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6619. if (rendererInfo != null) {
  6620. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6621. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6622. }
  6623. if (!this._glVendor) {
  6624. this._glVendor = "Unknown vendor";
  6625. }
  6626. if (!this._glRenderer) {
  6627. this._glRenderer = "Unknown renderer";
  6628. }
  6629. // Extensions
  6630. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6631. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6632. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6633. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6634. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6635. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6636. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6637. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6638. 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');
  6639. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6640. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6641. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6642. this._caps.highPrecisionShaderSupported = true;
  6643. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6644. // Checks if some of the format renders first to allow the use of webgl inspector.
  6645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  6646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  6647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  6648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  6649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  6650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  6651. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  6652. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6653. // Vertex array object
  6654. if (this._webGLVersion > 1) {
  6655. this._caps.vertexArrayObject = true;
  6656. }
  6657. else {
  6658. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  6659. if (vertexArrayObjectExtension != null) {
  6660. this._caps.vertexArrayObject = true;
  6661. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  6662. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  6663. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  6664. }
  6665. else {
  6666. this._caps.vertexArrayObject = false;
  6667. }
  6668. }
  6669. // Instances count
  6670. if (this._webGLVersion > 1) {
  6671. this._caps.instancedArrays = true;
  6672. }
  6673. else {
  6674. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6675. if (instanceExtension != null) {
  6676. this._caps.instancedArrays = true;
  6677. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  6678. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  6679. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  6680. }
  6681. else {
  6682. this._caps.instancedArrays = false;
  6683. }
  6684. }
  6685. // Intelligently add supported compressed formats in order to check for.
  6686. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6687. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6688. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6689. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6690. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6691. if (this._caps.astc)
  6692. this.texturesSupported.push('-astc.ktx');
  6693. if (this._caps.s3tc)
  6694. this.texturesSupported.push('-dxt.ktx');
  6695. if (this._caps.pvrtc)
  6696. this.texturesSupported.push('-pvrtc.ktx');
  6697. if (this._caps.etc2)
  6698. this.texturesSupported.push('-etc2.ktx');
  6699. if (this._caps.atc)
  6700. this.texturesSupported.push('-atc.ktx');
  6701. if (this._caps.etc1)
  6702. this.texturesSupported.push('-etc1.ktx');
  6703. if (this._gl.getShaderPrecisionFormat) {
  6704. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6705. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6706. }
  6707. // Depth buffer
  6708. this.setDepthBuffer(true);
  6709. this.setDepthFunctionToLessOrEqual();
  6710. this.setDepthWrite(true);
  6711. // Fullscreen
  6712. this._onFullscreenChange = function () {
  6713. if (document.fullscreen !== undefined) {
  6714. _this.isFullscreen = document.fullscreen;
  6715. }
  6716. else if (document.mozFullScreen !== undefined) {
  6717. _this.isFullscreen = document.mozFullScreen;
  6718. }
  6719. else if (document.webkitIsFullScreen !== undefined) {
  6720. _this.isFullscreen = document.webkitIsFullScreen;
  6721. }
  6722. else if (document.msIsFullScreen !== undefined) {
  6723. _this.isFullscreen = document.msIsFullScreen;
  6724. }
  6725. // Pointer lock
  6726. if (_this.isFullscreen && _this._pointerLockRequested) {
  6727. canvas.requestPointerLock = canvas.requestPointerLock ||
  6728. canvas.msRequestPointerLock ||
  6729. canvas.mozRequestPointerLock ||
  6730. canvas.webkitRequestPointerLock;
  6731. if (canvas.requestPointerLock) {
  6732. canvas.requestPointerLock();
  6733. }
  6734. }
  6735. };
  6736. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6737. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6738. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6739. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6740. // Pointer lock
  6741. this._onPointerLockChange = function () {
  6742. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6743. document.webkitPointerLockElement === canvas ||
  6744. document.msPointerLockElement === canvas ||
  6745. document.pointerLockElement === canvas);
  6746. };
  6747. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6748. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6749. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6750. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6751. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6752. Engine.audioEngine = new BABYLON.AudioEngine();
  6753. }
  6754. //default loading screen
  6755. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6756. //Load WebVR Devices
  6757. if (options.autoEnableWebVR) {
  6758. this.initWebVR();
  6759. }
  6760. //Detect if we are running on a faulty buggy OS.
  6761. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6762. //ua sniffing is the tool of the devil.
  6763. this._badOS = regexp.test(navigator.userAgent);
  6764. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6765. }
  6766. Object.defineProperty(Engine, "NEVER", {
  6767. get: function () {
  6768. return Engine._NEVER;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "ALWAYS", {
  6774. get: function () {
  6775. return Engine._ALWAYS;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "LESS", {
  6781. get: function () {
  6782. return Engine._LESS;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "EQUAL", {
  6788. get: function () {
  6789. return Engine._EQUAL;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "LEQUAL", {
  6795. get: function () {
  6796. return Engine._LEQUAL;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "GREATER", {
  6802. get: function () {
  6803. return Engine._GREATER;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "GEQUAL", {
  6809. get: function () {
  6810. return Engine._GEQUAL;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "NOTEQUAL", {
  6816. get: function () {
  6817. return Engine._NOTEQUAL;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "KEEP", {
  6823. get: function () {
  6824. return Engine._KEEP;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "REPLACE", {
  6830. get: function () {
  6831. return Engine._REPLACE;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine, "INCR", {
  6837. get: function () {
  6838. return Engine._INCR;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine, "DECR", {
  6844. get: function () {
  6845. return Engine._DECR;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(Engine, "INVERT", {
  6851. get: function () {
  6852. return Engine._INVERT;
  6853. },
  6854. enumerable: true,
  6855. configurable: true
  6856. });
  6857. Object.defineProperty(Engine, "INCR_WRAP", {
  6858. get: function () {
  6859. return Engine._INCR_WRAP;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(Engine, "DECR_WRAP", {
  6865. get: function () {
  6866. return Engine._DECR_WRAP;
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6872. get: function () {
  6873. return Engine._ALPHA_DISABLE;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6879. get: function () {
  6880. return Engine._ALPHA_ONEONE;
  6881. },
  6882. enumerable: true,
  6883. configurable: true
  6884. });
  6885. Object.defineProperty(Engine, "ALPHA_ADD", {
  6886. get: function () {
  6887. return Engine._ALPHA_ADD;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6893. get: function () {
  6894. return Engine._ALPHA_COMBINE;
  6895. },
  6896. enumerable: true,
  6897. configurable: true
  6898. });
  6899. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6900. get: function () {
  6901. return Engine._ALPHA_SUBTRACT;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6907. get: function () {
  6908. return Engine._ALPHA_MULTIPLY;
  6909. },
  6910. enumerable: true,
  6911. configurable: true
  6912. });
  6913. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6914. get: function () {
  6915. return Engine._ALPHA_MAXIMIZED;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6921. get: function () {
  6922. return Engine._ALPHA_PREMULTIPLIED;
  6923. },
  6924. enumerable: true,
  6925. configurable: true
  6926. });
  6927. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6928. get: function () {
  6929. return Engine._DELAYLOADSTATE_NONE;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6935. get: function () {
  6936. return Engine._DELAYLOADSTATE_LOADED;
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6942. get: function () {
  6943. return Engine._DELAYLOADSTATE_LOADING;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6949. get: function () {
  6950. return Engine._DELAYLOADSTATE_NOTLOADED;
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6956. get: function () {
  6957. return Engine._TEXTUREFORMAT_ALPHA;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6963. get: function () {
  6964. return Engine._TEXTUREFORMAT_LUMINANCE;
  6965. },
  6966. enumerable: true,
  6967. configurable: true
  6968. });
  6969. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6970. get: function () {
  6971. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6972. },
  6973. enumerable: true,
  6974. configurable: true
  6975. });
  6976. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6977. get: function () {
  6978. return Engine._TEXTUREFORMAT_RGB;
  6979. },
  6980. enumerable: true,
  6981. configurable: true
  6982. });
  6983. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6984. get: function () {
  6985. return Engine._TEXTUREFORMAT_RGBA;
  6986. },
  6987. enumerable: true,
  6988. configurable: true
  6989. });
  6990. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6991. get: function () {
  6992. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6993. },
  6994. enumerable: true,
  6995. configurable: true
  6996. });
  6997. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6998. get: function () {
  6999. return Engine._TEXTURETYPE_FLOAT;
  7000. },
  7001. enumerable: true,
  7002. configurable: true
  7003. });
  7004. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7005. get: function () {
  7006. return Engine._TEXTURETYPE_HALF_FLOAT;
  7007. },
  7008. enumerable: true,
  7009. configurable: true
  7010. });
  7011. Object.defineProperty(Engine, "Version", {
  7012. get: function () {
  7013. return "2.6-alpha";
  7014. },
  7015. enumerable: true,
  7016. configurable: true
  7017. });
  7018. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7019. get: function () {
  7020. return this._texturesSupported;
  7021. },
  7022. enumerable: true,
  7023. configurable: true
  7024. });
  7025. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7026. get: function () {
  7027. return this._textureFormatInUse;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7033. get: function () {
  7034. return this._webGLVersion;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7040. /**
  7041. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7042. */
  7043. get: function () {
  7044. return this._isStencilEnable;
  7045. },
  7046. enumerable: true,
  7047. configurable: true
  7048. });
  7049. Engine.prototype._prepareWorkingCanvas = function () {
  7050. if (this._workingCanvas) {
  7051. return;
  7052. }
  7053. this._workingCanvas = document.createElement("canvas");
  7054. this._workingContext = this._workingCanvas.getContext("2d");
  7055. };
  7056. Engine.prototype.resetTextureCache = function () {
  7057. for (var index = 0; index < this._maxTextureChannels; index++) {
  7058. this._activeTexturesCache[index] = null;
  7059. }
  7060. };
  7061. Engine.prototype.getGlInfo = function () {
  7062. return {
  7063. vendor: this._glVendor,
  7064. renderer: this._glRenderer,
  7065. version: this._glVersion
  7066. };
  7067. };
  7068. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7069. if (useScreen === void 0) { useScreen = false; }
  7070. var viewport = camera.viewport;
  7071. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7072. };
  7073. Engine.prototype.getRenderWidth = function (useScreen) {
  7074. if (useScreen === void 0) { useScreen = false; }
  7075. if (!useScreen && this._currentRenderTarget) {
  7076. return this._currentRenderTarget._width;
  7077. }
  7078. return this._renderingCanvas.width;
  7079. };
  7080. Engine.prototype.getRenderHeight = function (useScreen) {
  7081. if (useScreen === void 0) { useScreen = false; }
  7082. if (!useScreen && this._currentRenderTarget) {
  7083. return this._currentRenderTarget._height;
  7084. }
  7085. return this._renderingCanvas.height;
  7086. };
  7087. Engine.prototype.getRenderingCanvas = function () {
  7088. return this._renderingCanvas;
  7089. };
  7090. Engine.prototype.getRenderingCanvasClientRect = function () {
  7091. return this._renderingCanvas.getBoundingClientRect();
  7092. };
  7093. Engine.prototype.setHardwareScalingLevel = function (level) {
  7094. this._hardwareScalingLevel = level;
  7095. this.resize();
  7096. };
  7097. Engine.prototype.getHardwareScalingLevel = function () {
  7098. return this._hardwareScalingLevel;
  7099. };
  7100. Engine.prototype.getLoadedTexturesCache = function () {
  7101. return this._loadedTexturesCache;
  7102. };
  7103. Engine.prototype.getCaps = function () {
  7104. return this._caps;
  7105. };
  7106. Object.defineProperty(Engine.prototype, "drawCalls", {
  7107. get: function () {
  7108. return this._drawCalls.current;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7114. get: function () {
  7115. return this._drawCalls;
  7116. },
  7117. enumerable: true,
  7118. configurable: true
  7119. });
  7120. Engine.prototype.getDepthFunction = function () {
  7121. return this._depthCullingState.depthFunc;
  7122. };
  7123. Engine.prototype.setDepthFunction = function (depthFunc) {
  7124. this._depthCullingState.depthFunc = depthFunc;
  7125. };
  7126. Engine.prototype.setDepthFunctionToGreater = function () {
  7127. this._depthCullingState.depthFunc = this._gl.GREATER;
  7128. };
  7129. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7130. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7131. };
  7132. Engine.prototype.setDepthFunctionToLess = function () {
  7133. this._depthCullingState.depthFunc = this._gl.LESS;
  7134. };
  7135. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7136. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7137. };
  7138. Engine.prototype.getStencilBuffer = function () {
  7139. return this._stencilState.stencilTest;
  7140. };
  7141. Engine.prototype.setStencilBuffer = function (enable) {
  7142. this._stencilState.stencilTest = enable;
  7143. };
  7144. Engine.prototype.getStencilMask = function () {
  7145. return this._stencilState.stencilMask;
  7146. };
  7147. Engine.prototype.setStencilMask = function (mask) {
  7148. this._stencilState.stencilMask = mask;
  7149. };
  7150. Engine.prototype.getStencilFunction = function () {
  7151. return this._stencilState.stencilFunc;
  7152. };
  7153. Engine.prototype.getStencilFunctionReference = function () {
  7154. return this._stencilState.stencilFuncRef;
  7155. };
  7156. Engine.prototype.getStencilFunctionMask = function () {
  7157. return this._stencilState.stencilFuncMask;
  7158. };
  7159. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7160. this._stencilState.stencilFunc = stencilFunc;
  7161. };
  7162. Engine.prototype.setStencilFunctionReference = function (reference) {
  7163. this._stencilState.stencilFuncRef = reference;
  7164. };
  7165. Engine.prototype.setStencilFunctionMask = function (mask) {
  7166. this._stencilState.stencilFuncMask = mask;
  7167. };
  7168. Engine.prototype.getStencilOperationFail = function () {
  7169. return this._stencilState.stencilOpStencilFail;
  7170. };
  7171. Engine.prototype.getStencilOperationDepthFail = function () {
  7172. return this._stencilState.stencilOpDepthFail;
  7173. };
  7174. Engine.prototype.getStencilOperationPass = function () {
  7175. return this._stencilState.stencilOpStencilDepthPass;
  7176. };
  7177. Engine.prototype.setStencilOperationFail = function (operation) {
  7178. this._stencilState.stencilOpStencilFail = operation;
  7179. };
  7180. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7181. this._stencilState.stencilOpDepthFail = operation;
  7182. };
  7183. Engine.prototype.setStencilOperationPass = function (operation) {
  7184. this._stencilState.stencilOpStencilDepthPass = operation;
  7185. };
  7186. /**
  7187. * stop executing a render loop function and remove it from the execution array
  7188. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7189. */
  7190. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7191. if (!renderFunction) {
  7192. this._activeRenderLoops = [];
  7193. return;
  7194. }
  7195. var index = this._activeRenderLoops.indexOf(renderFunction);
  7196. if (index >= 0) {
  7197. this._activeRenderLoops.splice(index, 1);
  7198. }
  7199. };
  7200. Engine.prototype._renderLoop = function () {
  7201. var shouldRender = true;
  7202. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7203. shouldRender = false;
  7204. }
  7205. if (shouldRender) {
  7206. // Start new frame
  7207. this.beginFrame();
  7208. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7209. var renderFunction = this._activeRenderLoops[index];
  7210. renderFunction();
  7211. }
  7212. // Present
  7213. this.endFrame();
  7214. }
  7215. if (this._activeRenderLoops.length > 0) {
  7216. // Register new frame
  7217. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7218. }
  7219. else {
  7220. this._renderingQueueLaunched = false;
  7221. }
  7222. };
  7223. /**
  7224. * Register and execute a render loop. The engine can have more than one render function.
  7225. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7226. * @example
  7227. * engine.runRenderLoop(function () {
  7228. * scene.render()
  7229. * })
  7230. */
  7231. Engine.prototype.runRenderLoop = function (renderFunction) {
  7232. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7233. return;
  7234. }
  7235. this._activeRenderLoops.push(renderFunction);
  7236. if (!this._renderingQueueLaunched) {
  7237. this._renderingQueueLaunched = true;
  7238. this._bindedRenderFunction = this._renderLoop.bind(this);
  7239. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7240. }
  7241. };
  7242. /**
  7243. * Toggle full screen mode.
  7244. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7245. * @param {any} options - an options object to be sent to the requestFullscreen function
  7246. */
  7247. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7248. if (this.isFullscreen) {
  7249. BABYLON.Tools.ExitFullscreen();
  7250. }
  7251. else {
  7252. this._pointerLockRequested = requestPointerLock;
  7253. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7254. }
  7255. };
  7256. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7257. if (stencil === void 0) { stencil = false; }
  7258. this.applyStates();
  7259. var mode = 0;
  7260. if (backBuffer && color) {
  7261. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7262. mode |= this._gl.COLOR_BUFFER_BIT;
  7263. }
  7264. if (depth) {
  7265. this._gl.clearDepth(1.0);
  7266. mode |= this._gl.DEPTH_BUFFER_BIT;
  7267. }
  7268. if (stencil) {
  7269. this._gl.clearStencil(0);
  7270. mode |= this._gl.STENCIL_BUFFER_BIT;
  7271. }
  7272. this._gl.clear(mode);
  7273. };
  7274. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7275. var gl = this._gl;
  7276. // Save state
  7277. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7278. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7279. // Change state
  7280. gl.enable(gl.SCISSOR_TEST);
  7281. gl.scissor(x, y, width, height);
  7282. // Clear
  7283. this.clear(clearColor, true, true, true);
  7284. // Restore state
  7285. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7286. if (curScissor === true) {
  7287. gl.enable(gl.SCISSOR_TEST);
  7288. }
  7289. else {
  7290. gl.disable(gl.SCISSOR_TEST);
  7291. }
  7292. };
  7293. /**
  7294. * Set the WebGL's viewport
  7295. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7296. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7297. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7298. */
  7299. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7300. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7301. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7302. var x = viewport.x || 0;
  7303. var y = viewport.y || 0;
  7304. this._cachedViewport = viewport;
  7305. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7306. };
  7307. /**
  7308. * Directly set the WebGL Viewport
  7309. * The x, y, width & height are directly passed to the WebGL call
  7310. * @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.
  7311. */
  7312. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7313. var currentViewport = this._cachedViewport;
  7314. this._cachedViewport = null;
  7315. this._gl.viewport(x, y, width, height);
  7316. return currentViewport;
  7317. };
  7318. Engine.prototype.beginFrame = function () {
  7319. this._measureFps();
  7320. };
  7321. Engine.prototype.endFrame = function () {
  7322. //force a flush in case we are using a bad OS.
  7323. if (this._badOS) {
  7324. this.flushFramebuffer();
  7325. }
  7326. //submit frame to the vr device, if enabled
  7327. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7328. this._vrDisplayEnabled.submitFrame();
  7329. }
  7330. };
  7331. /**
  7332. * resize the view according to the canvas' size.
  7333. * @example
  7334. * window.addEventListener("resize", function () {
  7335. * engine.resize();
  7336. * });
  7337. */
  7338. Engine.prototype.resize = function () {
  7339. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7340. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7341. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7342. };
  7343. /**
  7344. * force a specific size of the canvas
  7345. * @param {number} width - the new canvas' width
  7346. * @param {number} height - the new canvas' height
  7347. */
  7348. Engine.prototype.setSize = function (width, height) {
  7349. this._renderingCanvas.width = width;
  7350. this._renderingCanvas.height = height;
  7351. for (var index = 0; index < this.scenes.length; index++) {
  7352. var scene = this.scenes[index];
  7353. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7354. var cam = scene.cameras[camIndex];
  7355. cam._currentRenderId = 0;
  7356. }
  7357. }
  7358. };
  7359. //WebVR functions
  7360. Engine.prototype.initWebVR = function () {
  7361. if (!this.vrDisplaysPromise) {
  7362. this._getVRDisplays();
  7363. }
  7364. };
  7365. Engine.prototype.enableVR = function (vrDevice) {
  7366. this._vrDisplayEnabled = vrDevice;
  7367. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7368. };
  7369. Engine.prototype.disableVR = function () {
  7370. if (this._vrDisplayEnabled) {
  7371. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7372. }
  7373. };
  7374. Engine.prototype._getVRDisplays = function () {
  7375. var _this = this;
  7376. var getWebVRDevices = function (devices) {
  7377. var size = devices.length;
  7378. var i = 0;
  7379. _this._vrDisplays = devices.filter(function (device) {
  7380. return devices[i] instanceof VRDisplay;
  7381. });
  7382. return _this._vrDisplays;
  7383. };
  7384. //using a key due to typescript
  7385. if (navigator.getVRDisplays) {
  7386. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7387. }
  7388. };
  7389. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7390. this._currentRenderTarget = texture;
  7391. this.bindUnboundFramebuffer(texture._framebuffer);
  7392. var gl = this._gl;
  7393. if (texture.isCube) {
  7394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7395. }
  7396. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7397. this.wipeCaches();
  7398. };
  7399. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7400. if (this._currentFramebuffer !== framebuffer) {
  7401. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7402. this._currentFramebuffer = framebuffer;
  7403. }
  7404. };
  7405. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7406. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7407. this._currentRenderTarget = null;
  7408. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7409. var gl = this._gl;
  7410. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7411. gl.generateMipmap(gl.TEXTURE_2D);
  7412. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7413. }
  7414. this.bindUnboundFramebuffer(null);
  7415. };
  7416. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7417. if (texture.generateMipMaps) {
  7418. var gl = this._gl;
  7419. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7420. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7421. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7422. }
  7423. };
  7424. Engine.prototype.flushFramebuffer = function () {
  7425. this._gl.flush();
  7426. };
  7427. Engine.prototype.restoreDefaultFramebuffer = function () {
  7428. this._currentRenderTarget = null;
  7429. this.bindUnboundFramebuffer(null);
  7430. this.setViewport(this._cachedViewport);
  7431. this.wipeCaches();
  7432. };
  7433. // VBOs
  7434. Engine.prototype._resetVertexBufferBinding = function () {
  7435. this.bindArrayBuffer(null);
  7436. this._cachedVertexBuffers = null;
  7437. };
  7438. Engine.prototype.createVertexBuffer = function (vertices) {
  7439. var vbo = this._gl.createBuffer();
  7440. this.bindArrayBuffer(vbo);
  7441. if (vertices instanceof Float32Array) {
  7442. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7443. }
  7444. else {
  7445. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7446. }
  7447. this._resetVertexBufferBinding();
  7448. vbo.references = 1;
  7449. return vbo;
  7450. };
  7451. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7452. var vbo = this._gl.createBuffer();
  7453. this.bindArrayBuffer(vbo);
  7454. if (vertices instanceof Float32Array) {
  7455. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7456. }
  7457. else {
  7458. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7459. }
  7460. this._resetVertexBufferBinding();
  7461. vbo.references = 1;
  7462. return vbo;
  7463. };
  7464. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7465. this.bindArrayBuffer(vertexBuffer);
  7466. if (offset === undefined) {
  7467. offset = 0;
  7468. }
  7469. if (count === undefined) {
  7470. if (vertices instanceof Float32Array) {
  7471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7472. }
  7473. else {
  7474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7475. }
  7476. }
  7477. else {
  7478. if (vertices instanceof Float32Array) {
  7479. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7480. }
  7481. else {
  7482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7483. }
  7484. }
  7485. this._resetVertexBufferBinding();
  7486. };
  7487. Engine.prototype._resetIndexBufferBinding = function () {
  7488. this.bindIndexBuffer(null);
  7489. this._cachedIndexBuffer = null;
  7490. };
  7491. Engine.prototype.createIndexBuffer = function (indices) {
  7492. var vbo = this._gl.createBuffer();
  7493. this.bindIndexBuffer(vbo);
  7494. // Check for 32 bits indices
  7495. var arrayBuffer;
  7496. var need32Bits = false;
  7497. if (indices instanceof Uint16Array) {
  7498. arrayBuffer = indices;
  7499. }
  7500. else {
  7501. //check 32 bit support
  7502. if (this._caps.uintIndices) {
  7503. if (indices instanceof Uint32Array) {
  7504. arrayBuffer = indices;
  7505. need32Bits = true;
  7506. }
  7507. else {
  7508. //number[] or Int32Array, check if 32 bit is necessary
  7509. for (var index = 0; index < indices.length; index++) {
  7510. if (indices[index] > 65535) {
  7511. need32Bits = true;
  7512. break;
  7513. }
  7514. }
  7515. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7516. }
  7517. }
  7518. else {
  7519. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  7520. arrayBuffer = new Uint16Array(indices);
  7521. }
  7522. }
  7523. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7524. this._resetIndexBufferBinding();
  7525. vbo.references = 1;
  7526. vbo.is32Bits = need32Bits;
  7527. return vbo;
  7528. };
  7529. Engine.prototype.bindArrayBuffer = function (buffer) {
  7530. if (!this._vaoRecordInProgress) {
  7531. this._unBindVertexArrayObject();
  7532. }
  7533. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7534. };
  7535. Engine.prototype.bindIndexBuffer = function (buffer) {
  7536. if (!this._vaoRecordInProgress) {
  7537. this._unBindVertexArrayObject();
  7538. }
  7539. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7540. };
  7541. Engine.prototype.bindBuffer = function (buffer, target) {
  7542. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  7543. this._gl.bindBuffer(target, buffer);
  7544. this._currentBoundBuffer[target] = buffer;
  7545. }
  7546. };
  7547. Engine.prototype.updateArrayBuffer = function (data) {
  7548. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7549. };
  7550. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7551. var pointer = this._currentBufferPointers[indx];
  7552. var changed = false;
  7553. if (!pointer) {
  7554. changed = true;
  7555. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7556. }
  7557. else {
  7558. if (pointer.buffer !== buffer) {
  7559. pointer.buffer = buffer;
  7560. changed = true;
  7561. }
  7562. if (pointer.size !== size) {
  7563. pointer.size = size;
  7564. changed = true;
  7565. }
  7566. if (pointer.type !== type) {
  7567. pointer.type = type;
  7568. changed = true;
  7569. }
  7570. if (pointer.normalized !== normalized) {
  7571. pointer.normalized = normalized;
  7572. changed = true;
  7573. }
  7574. if (pointer.stride !== stride) {
  7575. pointer.stride = stride;
  7576. changed = true;
  7577. }
  7578. if (pointer.offset !== offset) {
  7579. pointer.offset = offset;
  7580. changed = true;
  7581. }
  7582. }
  7583. if (changed || this._vaoRecordInProgress) {
  7584. this.bindArrayBuffer(buffer);
  7585. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7586. }
  7587. };
  7588. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  7589. if (indexBuffer == null) {
  7590. return;
  7591. }
  7592. if (this._cachedIndexBuffer !== indexBuffer) {
  7593. this._cachedIndexBuffer = indexBuffer;
  7594. this.bindIndexBuffer(indexBuffer);
  7595. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7596. }
  7597. };
  7598. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  7599. var attributes = effect.getAttributesNames();
  7600. if (!this._vaoRecordInProgress) {
  7601. this._unBindVertexArrayObject();
  7602. }
  7603. this.unbindAllAttributes();
  7604. for (var index = 0; index < attributes.length; index++) {
  7605. var order = effect.getAttributeLocation(index);
  7606. if (order >= 0) {
  7607. var vertexBuffer = vertexBuffers[attributes[index]];
  7608. if (!vertexBuffer) {
  7609. continue;
  7610. }
  7611. this._gl.enableVertexAttribArray(order);
  7612. if (!this._vaoRecordInProgress) {
  7613. this._vertexAttribArraysEnabled[order] = true;
  7614. }
  7615. var buffer = vertexBuffer.getBuffer();
  7616. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7617. if (vertexBuffer.getIsInstanced()) {
  7618. this._gl.vertexAttribDivisor(order, 1);
  7619. if (!this._vaoRecordInProgress) {
  7620. this._currentInstanceLocations.push(order);
  7621. this._currentInstanceBuffers.push(buffer);
  7622. }
  7623. }
  7624. }
  7625. }
  7626. };
  7627. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  7628. var vao = this._gl.createVertexArray();
  7629. this._vaoRecordInProgress = true;
  7630. this._gl.bindVertexArray(vao);
  7631. this._mustWipeVertexAttributes = true;
  7632. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7633. this.bindIndexBuffer(indexBuffer);
  7634. this._vaoRecordInProgress = false;
  7635. this._gl.bindVertexArray(null);
  7636. return vao;
  7637. };
  7638. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  7639. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  7640. this._cachedVertexArrayObject = vertexArrayObject;
  7641. this._gl.bindVertexArray(vertexArrayObject);
  7642. this._cachedVertexBuffers = null;
  7643. this._cachedIndexBuffer = null;
  7644. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  7645. this._mustWipeVertexAttributes = true;
  7646. }
  7647. };
  7648. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7649. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7650. this._cachedVertexBuffers = vertexBuffer;
  7651. this._cachedEffectForVertexBuffers = effect;
  7652. var attributesCount = effect.getAttributesCount();
  7653. this._unBindVertexArrayObject();
  7654. this.unbindAllAttributes();
  7655. var offset = 0;
  7656. for (var index = 0; index < attributesCount; index++) {
  7657. if (index < vertexDeclaration.length) {
  7658. var order = effect.getAttributeLocation(index);
  7659. if (order >= 0) {
  7660. this._gl.enableVertexAttribArray(order);
  7661. this._vertexAttribArraysEnabled[order] = true;
  7662. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7663. }
  7664. offset += vertexDeclaration[index] * 4;
  7665. }
  7666. }
  7667. }
  7668. this._bindIndexBufferWithCache(indexBuffer);
  7669. };
  7670. Engine.prototype._unBindVertexArrayObject = function () {
  7671. if (!this._cachedVertexArrayObject) {
  7672. return;
  7673. }
  7674. this._cachedVertexArrayObject = null;
  7675. this._gl.bindVertexArray(null);
  7676. };
  7677. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7678. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7679. this._cachedVertexBuffers = vertexBuffers;
  7680. this._cachedEffectForVertexBuffers = effect;
  7681. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7682. }
  7683. this._bindIndexBufferWithCache(indexBuffer);
  7684. };
  7685. Engine.prototype.unbindInstanceAttributes = function () {
  7686. var boundBuffer;
  7687. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7688. var instancesBuffer = this._currentInstanceBuffers[i];
  7689. if (boundBuffer != instancesBuffer) {
  7690. boundBuffer = instancesBuffer;
  7691. this.bindArrayBuffer(instancesBuffer);
  7692. }
  7693. var offsetLocation = this._currentInstanceLocations[i];
  7694. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7695. }
  7696. this._currentInstanceBuffers.length = 0;
  7697. this._currentInstanceLocations.length = 0;
  7698. };
  7699. Engine.prototype.releaseVertexArrayObject = function (vao) {
  7700. this._gl.deleteVertexArray(vao);
  7701. };
  7702. Engine.prototype._releaseBuffer = function (buffer) {
  7703. buffer.references--;
  7704. if (buffer.references === 0) {
  7705. this._gl.deleteBuffer(buffer);
  7706. return true;
  7707. }
  7708. return false;
  7709. };
  7710. Engine.prototype.createInstancesBuffer = function (capacity) {
  7711. var buffer = this._gl.createBuffer();
  7712. buffer.capacity = capacity;
  7713. this.bindArrayBuffer(buffer);
  7714. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7715. return buffer;
  7716. };
  7717. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7718. this._gl.deleteBuffer(buffer);
  7719. };
  7720. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7721. this.bindArrayBuffer(instancesBuffer);
  7722. if (data) {
  7723. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7724. }
  7725. if (offsetLocations[0].index !== undefined) {
  7726. var stride = 0;
  7727. for (var i = 0; i < offsetLocations.length; i++) {
  7728. var ai = offsetLocations[i];
  7729. stride += ai.attributeSize * 4;
  7730. }
  7731. for (var i = 0; i < offsetLocations.length; i++) {
  7732. var ai = offsetLocations[i];
  7733. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7734. this._gl.enableVertexAttribArray(ai.index);
  7735. this._vertexAttribArraysEnabled[ai.index] = true;
  7736. }
  7737. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7738. this._gl.vertexAttribDivisor(ai.index, 1);
  7739. this._currentInstanceLocations.push(ai.index);
  7740. this._currentInstanceBuffers.push(instancesBuffer);
  7741. }
  7742. }
  7743. else {
  7744. for (var index = 0; index < 4; index++) {
  7745. var offsetLocation = offsetLocations[index];
  7746. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7747. this._gl.enableVertexAttribArray(offsetLocation);
  7748. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7749. }
  7750. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7751. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7752. this._currentInstanceLocations.push(offsetLocation);
  7753. this._currentInstanceBuffers.push(instancesBuffer);
  7754. }
  7755. }
  7756. };
  7757. Engine.prototype.applyStates = function () {
  7758. this._depthCullingState.apply(this._gl);
  7759. this._stencilState.apply(this._gl);
  7760. this._alphaState.apply(this._gl);
  7761. };
  7762. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7763. // Apply states
  7764. this.applyStates();
  7765. this._drawCalls.addCount(1, false);
  7766. // Render
  7767. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7768. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7769. if (instancesCount) {
  7770. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7771. return;
  7772. }
  7773. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7774. };
  7775. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7776. // Apply states
  7777. this.applyStates();
  7778. this._drawCalls.addCount(1, false);
  7779. if (instancesCount) {
  7780. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7781. return;
  7782. }
  7783. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7784. };
  7785. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7786. // Apply states
  7787. this.applyStates();
  7788. this._drawCalls.addCount(1, false);
  7789. if (instancesCount) {
  7790. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7791. return;
  7792. }
  7793. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7794. };
  7795. // Shaders
  7796. Engine.prototype._releaseEffect = function (effect) {
  7797. if (this._compiledEffects[effect._key]) {
  7798. delete this._compiledEffects[effect._key];
  7799. if (effect.getProgram()) {
  7800. this._gl.deleteProgram(effect.getProgram());
  7801. }
  7802. }
  7803. };
  7804. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7805. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7806. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7807. var name = vertex + "+" + fragment + "@" + defines;
  7808. if (this._compiledEffects[name]) {
  7809. return this._compiledEffects[name];
  7810. }
  7811. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7812. effect._key = name;
  7813. this._compiledEffects[name] = effect;
  7814. return effect;
  7815. };
  7816. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7817. if (uniformsNames === void 0) { uniformsNames = []; }
  7818. if (samplers === void 0) { samplers = []; }
  7819. if (defines === void 0) { defines = ""; }
  7820. return this.createEffect({
  7821. vertex: "particles",
  7822. fragmentElement: fragmentName
  7823. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7824. };
  7825. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7826. context = context || this._gl;
  7827. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7828. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7829. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7830. var shaderProgram = context.createProgram();
  7831. context.attachShader(shaderProgram, vertexShader);
  7832. context.attachShader(shaderProgram, fragmentShader);
  7833. context.linkProgram(shaderProgram);
  7834. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7835. if (!linked) {
  7836. var error = context.getProgramInfoLog(shaderProgram);
  7837. if (error) {
  7838. throw new Error(error);
  7839. }
  7840. }
  7841. context.deleteShader(vertexShader);
  7842. context.deleteShader(fragmentShader);
  7843. return shaderProgram;
  7844. };
  7845. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7846. var results = [];
  7847. for (var index = 0; index < uniformsNames.length; index++) {
  7848. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7849. }
  7850. return results;
  7851. };
  7852. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7853. var results = [];
  7854. for (var index = 0; index < attributesNames.length; index++) {
  7855. try {
  7856. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7857. }
  7858. catch (e) {
  7859. results.push(-1);
  7860. }
  7861. }
  7862. return results;
  7863. };
  7864. Engine.prototype.enableEffect = function (effect) {
  7865. // Use program
  7866. this.setProgram(effect.getProgram());
  7867. this._currentEffect = effect;
  7868. if (effect.onBind) {
  7869. effect.onBind(effect);
  7870. }
  7871. };
  7872. Engine.prototype.setIntArray = function (uniform, array) {
  7873. if (!uniform)
  7874. return;
  7875. this._gl.uniform1iv(uniform, array);
  7876. };
  7877. Engine.prototype.setIntArray2 = function (uniform, array) {
  7878. if (!uniform || array.length % 2 !== 0)
  7879. return;
  7880. this._gl.uniform2iv(uniform, array);
  7881. };
  7882. Engine.prototype.setIntArray3 = function (uniform, array) {
  7883. if (!uniform || array.length % 3 !== 0)
  7884. return;
  7885. this._gl.uniform3iv(uniform, array);
  7886. };
  7887. Engine.prototype.setIntArray4 = function (uniform, array) {
  7888. if (!uniform || array.length % 4 !== 0)
  7889. return;
  7890. this._gl.uniform4iv(uniform, array);
  7891. };
  7892. Engine.prototype.setFloatArray = function (uniform, array) {
  7893. if (!uniform)
  7894. return;
  7895. this._gl.uniform1fv(uniform, array);
  7896. };
  7897. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7898. if (!uniform || array.length % 2 !== 0)
  7899. return;
  7900. this._gl.uniform2fv(uniform, array);
  7901. };
  7902. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7903. if (!uniform || array.length % 3 !== 0)
  7904. return;
  7905. this._gl.uniform3fv(uniform, array);
  7906. };
  7907. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7908. if (!uniform || array.length % 4 !== 0)
  7909. return;
  7910. this._gl.uniform4fv(uniform, array);
  7911. };
  7912. Engine.prototype.setArray = function (uniform, array) {
  7913. if (!uniform)
  7914. return;
  7915. this._gl.uniform1fv(uniform, array);
  7916. };
  7917. Engine.prototype.setArray2 = function (uniform, array) {
  7918. if (!uniform || array.length % 2 !== 0)
  7919. return;
  7920. this._gl.uniform2fv(uniform, array);
  7921. };
  7922. Engine.prototype.setArray3 = function (uniform, array) {
  7923. if (!uniform || array.length % 3 !== 0)
  7924. return;
  7925. this._gl.uniform3fv(uniform, array);
  7926. };
  7927. Engine.prototype.setArray4 = function (uniform, array) {
  7928. if (!uniform || array.length % 4 !== 0)
  7929. return;
  7930. this._gl.uniform4fv(uniform, array);
  7931. };
  7932. Engine.prototype.setMatrices = function (uniform, matrices) {
  7933. if (!uniform)
  7934. return;
  7935. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7936. };
  7937. Engine.prototype.setMatrix = function (uniform, matrix) {
  7938. if (!uniform)
  7939. return;
  7940. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7941. };
  7942. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7943. if (!uniform)
  7944. return;
  7945. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7946. };
  7947. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7948. if (!uniform)
  7949. return;
  7950. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7951. };
  7952. Engine.prototype.setFloat = function (uniform, value) {
  7953. if (!uniform)
  7954. return;
  7955. this._gl.uniform1f(uniform, value);
  7956. };
  7957. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7958. if (!uniform)
  7959. return;
  7960. this._gl.uniform2f(uniform, x, y);
  7961. };
  7962. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7963. if (!uniform)
  7964. return;
  7965. this._gl.uniform3f(uniform, x, y, z);
  7966. };
  7967. Engine.prototype.setBool = function (uniform, bool) {
  7968. if (!uniform)
  7969. return;
  7970. this._gl.uniform1i(uniform, bool);
  7971. };
  7972. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7973. if (!uniform)
  7974. return;
  7975. this._gl.uniform4f(uniform, x, y, z, w);
  7976. };
  7977. Engine.prototype.setColor3 = function (uniform, color3) {
  7978. if (!uniform)
  7979. return;
  7980. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7981. };
  7982. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7983. if (!uniform)
  7984. return;
  7985. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7986. };
  7987. // States
  7988. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7989. if (zOffset === void 0) { zOffset = 0; }
  7990. if (reverseSide === void 0) { reverseSide = false; }
  7991. // Culling
  7992. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7993. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7994. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7995. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7996. if (culling) {
  7997. this._depthCullingState.cullFace = cullFace;
  7998. this._depthCullingState.cull = true;
  7999. }
  8000. else {
  8001. this._depthCullingState.cull = false;
  8002. }
  8003. }
  8004. // Z offset
  8005. this._depthCullingState.zOffset = zOffset;
  8006. };
  8007. Engine.prototype.setDepthBuffer = function (enable) {
  8008. this._depthCullingState.depthTest = enable;
  8009. };
  8010. Engine.prototype.getDepthWrite = function () {
  8011. return this._depthCullingState.depthMask;
  8012. };
  8013. Engine.prototype.setDepthWrite = function (enable) {
  8014. this._depthCullingState.depthMask = enable;
  8015. };
  8016. Engine.prototype.setColorWrite = function (enable) {
  8017. this._gl.colorMask(enable, enable, enable, enable);
  8018. };
  8019. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8020. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8021. if (this._alphaMode === mode) {
  8022. return;
  8023. }
  8024. switch (mode) {
  8025. case Engine.ALPHA_DISABLE:
  8026. this._alphaState.alphaBlend = false;
  8027. break;
  8028. case Engine.ALPHA_PREMULTIPLIED:
  8029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8030. this._alphaState.alphaBlend = true;
  8031. break;
  8032. case Engine.ALPHA_COMBINE:
  8033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8034. this._alphaState.alphaBlend = true;
  8035. break;
  8036. case Engine.ALPHA_ONEONE:
  8037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8038. this._alphaState.alphaBlend = true;
  8039. break;
  8040. case Engine.ALPHA_ADD:
  8041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8042. this._alphaState.alphaBlend = true;
  8043. break;
  8044. case Engine.ALPHA_SUBTRACT:
  8045. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8046. this._alphaState.alphaBlend = true;
  8047. break;
  8048. case Engine.ALPHA_MULTIPLY:
  8049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8050. this._alphaState.alphaBlend = true;
  8051. break;
  8052. case Engine.ALPHA_MAXIMIZED:
  8053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8054. this._alphaState.alphaBlend = true;
  8055. break;
  8056. }
  8057. if (!noDepthWriteChange) {
  8058. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8059. }
  8060. this._alphaMode = mode;
  8061. };
  8062. Engine.prototype.getAlphaMode = function () {
  8063. return this._alphaMode;
  8064. };
  8065. Engine.prototype.setAlphaTesting = function (enable) {
  8066. this._alphaTest = enable;
  8067. };
  8068. Engine.prototype.getAlphaTesting = function () {
  8069. return this._alphaTest;
  8070. };
  8071. // Textures
  8072. Engine.prototype.wipeCaches = function () {
  8073. this.resetTextureCache();
  8074. this._currentEffect = null;
  8075. this._stencilState.reset();
  8076. this._depthCullingState.reset();
  8077. this.setDepthFunctionToLessOrEqual();
  8078. this._alphaState.reset();
  8079. this._cachedVertexBuffers = null;
  8080. this._cachedIndexBuffer = null;
  8081. this._cachedEffectForVertexBuffers = null;
  8082. this._unBindVertexArrayObject();
  8083. this.bindIndexBuffer(null);
  8084. this.bindArrayBuffer(null);
  8085. };
  8086. /**
  8087. * Set the compressed texture format to use, based on the formats you have, and the formats
  8088. * supported by the hardware / browser.
  8089. *
  8090. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8091. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8092. * to API arguments needed to compressed textures. This puts the burden on the container
  8093. * generator to house the arcane code for determining these for current & future formats.
  8094. *
  8095. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8096. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8097. *
  8098. * Note: The result of this call is not taken into account when a texture is base64.
  8099. *
  8100. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8101. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8102. *
  8103. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8104. * @returns The extension selected.
  8105. */
  8106. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8107. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8108. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8109. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8110. return this._textureFormatInUse = this._texturesSupported[i];
  8111. }
  8112. }
  8113. }
  8114. // actively set format to nothing, to allow this to be called more than once
  8115. // and possibly fail the 2nd time
  8116. return this._textureFormatInUse = null;
  8117. };
  8118. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack) {
  8119. var _this = this;
  8120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8121. if (onLoad === void 0) { onLoad = null; }
  8122. if (onError === void 0) { onError = null; }
  8123. if (buffer === void 0) { buffer = null; }
  8124. var texture = fallBack ? fallBack : this._gl.createTexture();
  8125. var extension;
  8126. var isKTX = false;
  8127. var fromData = false;
  8128. var url = String(urlArg);
  8129. if (url.substr(0, 5) === "data:") {
  8130. fromData = true;
  8131. }
  8132. if (!fromData) {
  8133. var lastDot = url.lastIndexOf('.');
  8134. extension = url.substring(lastDot).toLowerCase();
  8135. if (this._textureFormatInUse && !fromData && !fallBack) {
  8136. extension = this._textureFormatInUse;
  8137. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8138. isKTX = true;
  8139. }
  8140. }
  8141. else {
  8142. var oldUrl = url;
  8143. fromData = oldUrl.split(':');
  8144. url = oldUrl;
  8145. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8146. }
  8147. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8148. var isTGA = (extension === ".tga");
  8149. scene._addPendingData(texture);
  8150. texture.url = url;
  8151. texture.noMipmap = noMipmap;
  8152. texture.references = 1;
  8153. texture.samplingMode = samplingMode;
  8154. texture.onLoadedCallbacks = [];
  8155. if (onLoad) {
  8156. texture.onLoadedCallbacks.push(onLoad);
  8157. }
  8158. if (!fallBack)
  8159. this._loadedTexturesCache.push(texture);
  8160. var onerror = function () {
  8161. scene._removePendingData(texture);
  8162. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8163. if (isKTX) {
  8164. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  8165. }
  8166. else if (onError) {
  8167. onError();
  8168. }
  8169. };
  8170. var callback;
  8171. if (isKTX || isTGA || isDDS) {
  8172. if (isKTX) {
  8173. callback = function (data) {
  8174. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8175. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8176. ktx.uploadLevels(_this._gl, !noMipmap);
  8177. }, samplingMode);
  8178. };
  8179. }
  8180. else if (isTGA) {
  8181. callback = function (arrayBuffer) {
  8182. var data = new Uint8Array(arrayBuffer);
  8183. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8184. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8185. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8186. }, samplingMode);
  8187. };
  8188. }
  8189. else if (isDDS) {
  8190. callback = function (data) {
  8191. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8192. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8193. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8194. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8195. }, samplingMode);
  8196. };
  8197. }
  8198. if (!(fromData instanceof Array))
  8199. BABYLON.Tools.LoadFile(url, function (data) {
  8200. callback(data);
  8201. }, null, scene.database, true, onerror);
  8202. else
  8203. callback(buffer);
  8204. }
  8205. else {
  8206. var onload = function (img) {
  8207. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8208. var isPot = (img.width === potWidth && img.height === potHeight);
  8209. if (!isPot) {
  8210. _this._prepareWorkingCanvas();
  8211. _this._workingCanvas.width = potWidth;
  8212. _this._workingCanvas.height = potHeight;
  8213. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8214. _this._workingContext.imageSmoothingEnabled = false;
  8215. _this._workingContext.mozImageSmoothingEnabled = false;
  8216. _this._workingContext.oImageSmoothingEnabled = false;
  8217. _this._workingContext.webkitImageSmoothingEnabled = false;
  8218. _this._workingContext.msImageSmoothingEnabled = false;
  8219. }
  8220. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8221. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8222. _this._workingContext.imageSmoothingEnabled = true;
  8223. _this._workingContext.mozImageSmoothingEnabled = true;
  8224. _this._workingContext.oImageSmoothingEnabled = true;
  8225. _this._workingContext.webkitImageSmoothingEnabled = true;
  8226. _this._workingContext.msImageSmoothingEnabled = true;
  8227. }
  8228. }
  8229. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8230. }, samplingMode);
  8231. };
  8232. if (!(fromData instanceof Array))
  8233. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8234. else
  8235. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8236. }
  8237. return texture;
  8238. };
  8239. Engine.prototype._getInternalFormat = function (format) {
  8240. var internalFormat = this._gl.RGBA;
  8241. switch (format) {
  8242. case Engine.TEXTUREFORMAT_ALPHA:
  8243. internalFormat = this._gl.ALPHA;
  8244. break;
  8245. case Engine.TEXTUREFORMAT_LUMINANCE:
  8246. internalFormat = this._gl.LUMINANCE;
  8247. break;
  8248. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8249. internalFormat = this._gl.LUMINANCE_ALPHA;
  8250. break;
  8251. case Engine.TEXTUREFORMAT_RGB:
  8252. internalFormat = this._gl.RGB;
  8253. break;
  8254. case Engine.TEXTUREFORMAT_RGBA:
  8255. internalFormat = this._gl.RGBA;
  8256. break;
  8257. }
  8258. return internalFormat;
  8259. };
  8260. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8261. if (compression === void 0) { compression = null; }
  8262. var internalFormat = this._getInternalFormat(format);
  8263. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8264. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8265. if (texture._width % 4 !== 0) {
  8266. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8267. }
  8268. if (compression) {
  8269. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8270. }
  8271. else {
  8272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8273. }
  8274. if (texture.generateMipMaps) {
  8275. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8276. }
  8277. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8278. this.resetTextureCache();
  8279. texture.isReady = true;
  8280. };
  8281. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8282. if (compression === void 0) { compression = null; }
  8283. var texture = this._gl.createTexture();
  8284. texture._baseWidth = width;
  8285. texture._baseHeight = height;
  8286. texture._width = width;
  8287. texture._height = height;
  8288. texture.references = 1;
  8289. this.updateRawTexture(texture, data, format, invertY, compression);
  8290. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8291. // Filters
  8292. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8293. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8295. if (generateMipMaps) {
  8296. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8297. }
  8298. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8299. texture.samplingMode = samplingMode;
  8300. this._loadedTexturesCache.push(texture);
  8301. return texture;
  8302. };
  8303. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8304. var texture = this._gl.createTexture();
  8305. texture._baseWidth = width;
  8306. texture._baseHeight = height;
  8307. if (generateMipMaps) {
  8308. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8309. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8310. }
  8311. this.resetTextureCache();
  8312. texture._width = width;
  8313. texture._height = height;
  8314. texture.isReady = false;
  8315. texture.generateMipMaps = generateMipMaps;
  8316. texture.references = 1;
  8317. texture.samplingMode = samplingMode;
  8318. this.updateTextureSamplingMode(samplingMode, texture);
  8319. this._loadedTexturesCache.push(texture);
  8320. return texture;
  8321. };
  8322. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8323. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8324. if (texture.isCube) {
  8325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8326. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8327. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8329. }
  8330. else {
  8331. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8333. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8334. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8335. }
  8336. texture.samplingMode = samplingMode;
  8337. };
  8338. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8339. if (premulAlpha === void 0) { premulAlpha = false; }
  8340. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8341. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8342. if (premulAlpha) {
  8343. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8344. }
  8345. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8346. if (texture.generateMipMaps) {
  8347. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8348. }
  8349. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8350. if (premulAlpha) {
  8351. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8352. }
  8353. this.resetTextureCache();
  8354. texture.isReady = true;
  8355. };
  8356. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8357. if (texture._isDisabled) {
  8358. return;
  8359. }
  8360. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8361. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8362. try {
  8363. // Testing video texture support
  8364. if (this._videoTextureSupported === undefined) {
  8365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8366. if (this._gl.getError() !== 0) {
  8367. this._videoTextureSupported = false;
  8368. }
  8369. else {
  8370. this._videoTextureSupported = true;
  8371. }
  8372. }
  8373. // Copy video through the current working canvas if video texture is not supported
  8374. if (!this._videoTextureSupported) {
  8375. if (!texture._workingCanvas) {
  8376. texture._workingCanvas = document.createElement("canvas");
  8377. texture._workingContext = texture._workingCanvas.getContext("2d");
  8378. texture._workingCanvas.width = texture._width;
  8379. texture._workingCanvas.height = texture._height;
  8380. }
  8381. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8382. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8383. }
  8384. else {
  8385. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8386. }
  8387. if (texture.generateMipMaps) {
  8388. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8389. }
  8390. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8391. this.resetTextureCache();
  8392. texture.isReady = true;
  8393. }
  8394. catch (ex) {
  8395. // Something unexpected
  8396. // Let's disable the texture
  8397. texture._isDisabled = true;
  8398. }
  8399. };
  8400. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8401. // old version had a "generateMipMaps" arg instead of options.
  8402. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8403. // in the same way, generateDepthBuffer is defaulted to true
  8404. var generateMipMaps = false;
  8405. var generateDepthBuffer = true;
  8406. var generateStencilBuffer = false;
  8407. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8409. if (options !== undefined) {
  8410. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8412. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8413. type = options.type === undefined ? type : options.type;
  8414. if (options.samplingMode !== undefined) {
  8415. samplingMode = options.samplingMode;
  8416. }
  8417. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8418. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8419. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8420. }
  8421. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8422. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8423. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8424. }
  8425. }
  8426. var gl = this._gl;
  8427. var texture = gl.createTexture();
  8428. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8429. var width = size.width || size;
  8430. var height = size.height || size;
  8431. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8432. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8433. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8434. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8435. }
  8436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8440. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  8441. var depthStencilBuffer;
  8442. // Create the depth/stencil buffer
  8443. if (generateStencilBuffer) {
  8444. depthStencilBuffer = gl.createRenderbuffer();
  8445. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8446. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8447. }
  8448. else if (generateDepthBuffer) {
  8449. depthStencilBuffer = gl.createRenderbuffer();
  8450. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8451. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8452. }
  8453. // Create the framebuffer
  8454. var framebuffer = gl.createFramebuffer();
  8455. this.bindUnboundFramebuffer(framebuffer);
  8456. // Manage attachments
  8457. if (generateStencilBuffer) {
  8458. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8459. }
  8460. else if (generateDepthBuffer) {
  8461. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8462. }
  8463. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8464. if (generateMipMaps) {
  8465. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8466. }
  8467. // Unbind
  8468. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8469. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8470. this.bindUnboundFramebuffer(null);
  8471. texture._framebuffer = framebuffer;
  8472. if (generateDepthBuffer) {
  8473. texture._depthBuffer = depthStencilBuffer;
  8474. }
  8475. texture._baseWidth = width;
  8476. texture._baseHeight = height;
  8477. texture._width = width;
  8478. texture._height = height;
  8479. texture.isReady = true;
  8480. texture.generateMipMaps = generateMipMaps;
  8481. texture.references = 1;
  8482. texture.samplingMode = samplingMode;
  8483. texture.type = type;
  8484. this.resetTextureCache();
  8485. this._loadedTexturesCache.push(texture);
  8486. return texture;
  8487. };
  8488. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8489. var gl = this._gl;
  8490. var texture = gl.createTexture();
  8491. var generateMipMaps = true;
  8492. var generateDepthBuffer = true;
  8493. var generateStencilBuffer = false;
  8494. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8495. if (options !== undefined) {
  8496. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8497. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8498. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8499. if (options.samplingMode !== undefined) {
  8500. samplingMode = options.samplingMode;
  8501. }
  8502. }
  8503. texture.isCube = true;
  8504. texture.references = 1;
  8505. texture.generateMipMaps = generateMipMaps;
  8506. texture.references = 1;
  8507. texture.samplingMode = samplingMode;
  8508. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8510. for (var face = 0; face < 6; face++) {
  8511. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8512. }
  8513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8517. // Create the depth buffer
  8518. var depthStencilBuffer;
  8519. // Create the depth/stencil buffer
  8520. if (generateStencilBuffer) {
  8521. depthStencilBuffer = gl.createRenderbuffer();
  8522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8523. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8524. }
  8525. else if (generateDepthBuffer) {
  8526. depthStencilBuffer = gl.createRenderbuffer();
  8527. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8528. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8529. }
  8530. // Create the framebuffer
  8531. var framebuffer = gl.createFramebuffer();
  8532. this.bindUnboundFramebuffer(framebuffer);
  8533. // Manage attachments
  8534. if (generateStencilBuffer) {
  8535. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8536. }
  8537. else if (generateDepthBuffer) {
  8538. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8539. }
  8540. // Mipmaps
  8541. if (texture.generateMipMaps) {
  8542. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8543. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8544. }
  8545. // Unbind
  8546. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8547. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8548. this.bindUnboundFramebuffer(null);
  8549. texture._framebuffer = framebuffer;
  8550. if (generateDepthBuffer) {
  8551. texture._depthBuffer = depthStencilBuffer;
  8552. }
  8553. texture._width = size;
  8554. texture._height = size;
  8555. texture.isReady = true;
  8556. this.resetTextureCache();
  8557. this._loadedTexturesCache.push(texture);
  8558. return texture;
  8559. };
  8560. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8561. var _this = this;
  8562. if (onLoad === void 0) { onLoad = null; }
  8563. if (onError === void 0) { onError = null; }
  8564. var gl = this._gl;
  8565. var texture = gl.createTexture();
  8566. texture.isCube = true;
  8567. texture.url = rootUrl;
  8568. texture.references = 1;
  8569. texture.onLoadedCallbacks = [];
  8570. var isKTX = false;
  8571. var lastDot = rootUrl.lastIndexOf('.');
  8572. var extension = rootUrl.substring(lastDot).toLowerCase();
  8573. if (this._textureFormatInUse) {
  8574. extension = this._textureFormatInUse;
  8575. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8576. isKTX = true;
  8577. }
  8578. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8579. if (isKTX) {
  8580. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8581. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8582. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8584. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8585. ktx.uploadLevels(_this._gl, !noMipmap);
  8586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8591. _this.resetTextureCache();
  8592. texture._width = ktx.pixelWidth;
  8593. texture._height = ktx.pixelHeight;
  8594. texture.isReady = true;
  8595. }, null, null, true, onError);
  8596. }
  8597. else if (isDDS) {
  8598. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8599. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8600. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8601. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8602. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8603. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8604. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8605. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8606. }
  8607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8612. _this.resetTextureCache();
  8613. texture._width = info.width;
  8614. texture._height = info.height;
  8615. texture.isReady = true;
  8616. }, null, null, true, onError);
  8617. }
  8618. else {
  8619. cascadeLoad(rootUrl, scene, function (imgs) {
  8620. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8621. var height = width;
  8622. _this._prepareWorkingCanvas();
  8623. _this._workingCanvas.width = width;
  8624. _this._workingCanvas.height = height;
  8625. var faces = [
  8626. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8627. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8628. ];
  8629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8631. for (var index = 0; index < faces.length; index++) {
  8632. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8633. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8634. }
  8635. if (!noMipmap) {
  8636. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8637. }
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8642. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8643. _this.resetTextureCache();
  8644. texture._width = width;
  8645. texture._height = height;
  8646. texture.isReady = true;
  8647. texture.onLoadedCallbacks.forEach(function (callback) {
  8648. callback();
  8649. });
  8650. if (onLoad) {
  8651. onLoad();
  8652. }
  8653. }, files, onError);
  8654. }
  8655. this._loadedTexturesCache.push(texture);
  8656. return texture;
  8657. };
  8658. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8659. texture._width = width;
  8660. texture._height = height;
  8661. texture._size = width * height;
  8662. texture._baseWidth = width;
  8663. texture._baseHeight = height;
  8664. };
  8665. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8666. var _this = this;
  8667. var gl = this._gl;
  8668. var texture = gl.createTexture();
  8669. scene._addPendingData(texture);
  8670. texture.isCube = true;
  8671. texture.references = 1;
  8672. texture.url = url;
  8673. var textureType = gl.UNSIGNED_BYTE;
  8674. if (type === Engine.TEXTURETYPE_FLOAT) {
  8675. textureType = gl.FLOAT;
  8676. }
  8677. var internalFormat = this._getInternalFormat(format);
  8678. var needConversion = false;
  8679. if (internalFormat === gl.RGB) {
  8680. internalFormat = gl.RGBA;
  8681. needConversion = true;
  8682. }
  8683. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  8684. var width = size;
  8685. var height = width;
  8686. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8687. texture._width = width;
  8688. texture._height = height;
  8689. var onerror = function () {
  8690. scene._removePendingData(texture);
  8691. };
  8692. var internalCallback = function (data) {
  8693. var rgbeDataArrays = callback(data);
  8694. var facesIndex = [
  8695. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8696. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8697. ];
  8698. width = texture._width;
  8699. height = texture._height;
  8700. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8701. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8702. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8703. if (mipmmapGenerator) {
  8704. var arrayTemp = [];
  8705. // Data are known to be in +X +Y +Z -X -Y -Z
  8706. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8707. arrayTemp.push(rgbeDataArrays[0]); // +X
  8708. arrayTemp.push(rgbeDataArrays[3]); // -X
  8709. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8710. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8711. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8712. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8713. var mipData = mipmmapGenerator(arrayTemp);
  8714. // mipData is order in +X -X +Y -Y +Z -Z
  8715. var mipFaces = [0, 2, 4, 1, 3, 5];
  8716. for (var level = 0; level < mipData.length; level++) {
  8717. var mipSize = width >> level;
  8718. for (var mipIndex in mipFaces) {
  8719. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  8720. if (needConversion) {
  8721. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  8722. }
  8723. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  8724. }
  8725. }
  8726. }
  8727. else {
  8728. // Data are known to be in +X +Y +Z -X -Y -Z
  8729. for (var index = 0; index < facesIndex.length; index++) {
  8730. var faceData = rgbeDataArrays[index];
  8731. if (needConversion) {
  8732. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  8733. }
  8734. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  8735. }
  8736. if (!noMipmap && isPot) {
  8737. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8738. }
  8739. else {
  8740. noMipmap = true;
  8741. }
  8742. }
  8743. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8746. }
  8747. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8750. }
  8751. else {
  8752. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8753. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8754. }
  8755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8757. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8758. texture.isReady = true;
  8759. _this.resetTextureCache();
  8760. scene._removePendingData(texture);
  8761. };
  8762. BABYLON.Tools.LoadFile(url, function (data) {
  8763. internalCallback(data);
  8764. }, onerror, scene.database, true);
  8765. return texture;
  8766. };
  8767. ;
  8768. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  8769. // Create new RGBA data container.
  8770. var rgbaData;
  8771. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  8772. rgbaData = new Float32Array(width * height * 4);
  8773. }
  8774. else {
  8775. rgbaData = new Uint32Array(width * height * 4);
  8776. }
  8777. // Convert each pixel.
  8778. for (var x = 0; x < width; x++) {
  8779. for (var y = 0; y < height; y++) {
  8780. var index = (y * width + x) * 3;
  8781. var newIndex = (y * width + x) * 4;
  8782. // Map Old Value to new value.
  8783. rgbaData[newIndex + 0] = rgbData[index + 0];
  8784. rgbaData[newIndex + 1] = rgbData[index + 1];
  8785. rgbaData[newIndex + 2] = rgbData[index + 2];
  8786. // Add fully opaque alpha channel.
  8787. rgbaData[newIndex + 3] = 1;
  8788. }
  8789. }
  8790. return rgbaData;
  8791. };
  8792. Engine.prototype._releaseTexture = function (texture) {
  8793. var gl = this._gl;
  8794. if (texture._framebuffer) {
  8795. gl.deleteFramebuffer(texture._framebuffer);
  8796. }
  8797. if (texture._depthBuffer) {
  8798. gl.deleteRenderbuffer(texture._depthBuffer);
  8799. }
  8800. gl.deleteTexture(texture);
  8801. // Unbind channels
  8802. this.unbindAllTextures();
  8803. var index = this._loadedTexturesCache.indexOf(texture);
  8804. if (index !== -1) {
  8805. this._loadedTexturesCache.splice(index, 1);
  8806. }
  8807. };
  8808. Engine.prototype.setProgram = function (program) {
  8809. if (this._currentProgram !== program) {
  8810. this._gl.useProgram(program);
  8811. this._currentProgram = program;
  8812. }
  8813. };
  8814. Engine.prototype.bindSamplers = function (effect) {
  8815. this.setProgram(effect.getProgram());
  8816. var samplers = effect.getSamplers();
  8817. for (var index = 0; index < samplers.length; index++) {
  8818. var uniform = effect.getUniform(samplers[index]);
  8819. this._gl.uniform1i(uniform, index);
  8820. }
  8821. this._currentEffect = null;
  8822. };
  8823. Engine.prototype.activateTexture = function (texture) {
  8824. if (this._activeTexture !== texture) {
  8825. this._gl.activeTexture(texture);
  8826. this._activeTexture = texture;
  8827. }
  8828. };
  8829. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8830. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8831. this._gl.bindTexture(target, texture);
  8832. this._activeTexturesCache[this._activeTexture] = texture;
  8833. }
  8834. };
  8835. Engine.prototype._bindTexture = function (channel, texture) {
  8836. if (channel < 0) {
  8837. return;
  8838. }
  8839. this.activateTexture(this._gl.TEXTURE0 + channel);
  8840. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8841. };
  8842. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8843. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8844. };
  8845. Engine.prototype.unbindAllTextures = function () {
  8846. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8847. this.activateTexture(this._gl["TEXTURE" + channel]);
  8848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8850. }
  8851. };
  8852. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8853. if (channel < 0) {
  8854. return;
  8855. }
  8856. this._gl.uniform1i(uniform, channel);
  8857. this._setTexture(channel, texture);
  8858. };
  8859. Engine.prototype._setTexture = function (channel, texture) {
  8860. // Not ready?
  8861. if (!texture || !texture.isReady()) {
  8862. if (this._activeTexturesCache[channel] != null) {
  8863. this.activateTexture(this._gl["TEXTURE" + channel]);
  8864. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8865. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8866. }
  8867. return;
  8868. }
  8869. // Video
  8870. var alreadyActivated = false;
  8871. if (texture instanceof BABYLON.VideoTexture) {
  8872. this.activateTexture(this._gl["TEXTURE" + channel]);
  8873. alreadyActivated = true;
  8874. texture.update();
  8875. }
  8876. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8877. texture.delayLoad();
  8878. return;
  8879. }
  8880. var internalTexture = texture.getInternalTexture();
  8881. if (this._activeTexturesCache[channel] === internalTexture) {
  8882. return;
  8883. }
  8884. if (!alreadyActivated) {
  8885. this.activateTexture(this._gl["TEXTURE" + channel]);
  8886. }
  8887. if (internalTexture.isCube) {
  8888. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8889. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8890. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8891. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8892. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8894. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8895. }
  8896. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8897. }
  8898. else {
  8899. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8900. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8901. internalTexture._cachedWrapU = texture.wrapU;
  8902. switch (texture.wrapU) {
  8903. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8905. break;
  8906. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8908. break;
  8909. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8911. break;
  8912. }
  8913. }
  8914. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8915. internalTexture._cachedWrapV = texture.wrapV;
  8916. switch (texture.wrapV) {
  8917. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8919. break;
  8920. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8922. break;
  8923. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8925. break;
  8926. }
  8927. }
  8928. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8929. }
  8930. };
  8931. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8932. if (channel < 0) {
  8933. return;
  8934. }
  8935. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8936. this._textureUnits = new Int32Array(textures.length);
  8937. }
  8938. for (var i = 0; i < textures.length; i++) {
  8939. this._textureUnits[i] = channel + i;
  8940. }
  8941. this._gl.uniform1iv(uniform, this._textureUnits);
  8942. for (var index = 0; index < textures.length; index++) {
  8943. this._setTexture(channel + index, textures[index]);
  8944. }
  8945. };
  8946. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8947. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8948. var value = texture.anisotropicFilteringLevel;
  8949. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8950. value = 1;
  8951. }
  8952. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8953. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8954. texture._cachedAnisotropicFilteringLevel = value;
  8955. }
  8956. };
  8957. Engine.prototype.readPixels = function (x, y, width, height) {
  8958. var data = new Uint8Array(height * width * 4);
  8959. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8960. return data;
  8961. };
  8962. /**
  8963. * Add an externaly attached data from its key.
  8964. * This method call will fail and return false, if such key already exists.
  8965. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8966. * @param key the unique key that identifies the data
  8967. * @param data the data object to associate to the key for this Engine instance
  8968. * @return true if no such key were already present and the data was added successfully, false otherwise
  8969. */
  8970. Engine.prototype.addExternalData = function (key, data) {
  8971. return this._externalData.add(key, data);
  8972. };
  8973. /**
  8974. * Get an externaly attached data from its key
  8975. * @param key the unique key that identifies the data
  8976. * @return the associated data, if present (can be null), or undefined if not present
  8977. */
  8978. Engine.prototype.getExternalData = function (key) {
  8979. return this._externalData.get(key);
  8980. };
  8981. /**
  8982. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8983. * @param key the unique key that identifies the data
  8984. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8985. * @return the associated data, can be null if the factory returned null.
  8986. */
  8987. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8988. return this._externalData.getOrAddWithFactory(key, factory);
  8989. };
  8990. /**
  8991. * Remove an externaly attached data from the Engine instance
  8992. * @param key the unique key that identifies the data
  8993. * @return true if the data was successfully removed, false if it doesn't exist
  8994. */
  8995. Engine.prototype.removeExternalData = function (key) {
  8996. return this._externalData.remove(key);
  8997. };
  8998. Engine.prototype.releaseInternalTexture = function (texture) {
  8999. if (!texture) {
  9000. return;
  9001. }
  9002. texture.references--;
  9003. // Final reference ?
  9004. if (texture.references === 0) {
  9005. var texturesCache = this.getLoadedTexturesCache();
  9006. var index = texturesCache.indexOf(texture);
  9007. if (index > -1) {
  9008. texturesCache.splice(index, 1);
  9009. }
  9010. this._releaseTexture(texture);
  9011. }
  9012. };
  9013. Engine.prototype.unbindAllAttributes = function () {
  9014. if (this._mustWipeVertexAttributes) {
  9015. this._mustWipeVertexAttributes = false;
  9016. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9017. this._gl.disableVertexAttribArray(i);
  9018. this._vertexAttribArraysEnabled[i] = false;
  9019. this._currentBufferPointers[i] = null;
  9020. }
  9021. return;
  9022. }
  9023. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9024. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9025. continue;
  9026. }
  9027. this._gl.disableVertexAttribArray(i);
  9028. this._vertexAttribArraysEnabled[i] = false;
  9029. this._currentBufferPointers[i] = null;
  9030. }
  9031. };
  9032. // Dispose
  9033. Engine.prototype.dispose = function () {
  9034. this.hideLoadingUI();
  9035. this.stopRenderLoop();
  9036. // Release scenes
  9037. while (this.scenes.length) {
  9038. this.scenes[0].dispose();
  9039. }
  9040. // Release audio engine
  9041. Engine.audioEngine.dispose();
  9042. // Release effects
  9043. for (var name in this._compiledEffects) {
  9044. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9045. }
  9046. // Unbind
  9047. this.unbindAllAttributes();
  9048. this._gl = null;
  9049. //WebVR
  9050. this.disableVR();
  9051. // Events
  9052. window.removeEventListener("blur", this._onBlur);
  9053. window.removeEventListener("focus", this._onFocus);
  9054. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9055. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9056. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9057. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9058. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9059. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9060. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9061. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9062. };
  9063. // Loading screen
  9064. Engine.prototype.displayLoadingUI = function () {
  9065. this._loadingScreen.displayLoadingUI();
  9066. };
  9067. Engine.prototype.hideLoadingUI = function () {
  9068. this._loadingScreen.hideLoadingUI();
  9069. };
  9070. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9071. get: function () {
  9072. return this._loadingScreen;
  9073. },
  9074. set: function (loadingScreen) {
  9075. this._loadingScreen = loadingScreen;
  9076. },
  9077. enumerable: true,
  9078. configurable: true
  9079. });
  9080. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9081. set: function (text) {
  9082. this._loadingScreen.loadingUIText = text;
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9088. set: function (color) {
  9089. this._loadingScreen.loadingUIBackgroundColor = color;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Engine.prototype.attachContextLostEvent = function (callback) {
  9095. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9096. };
  9097. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9098. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9099. };
  9100. Engine.prototype.getVertexShaderSource = function (program) {
  9101. var shaders = this._gl.getAttachedShaders(program);
  9102. return this._gl.getShaderSource(shaders[0]);
  9103. };
  9104. Engine.prototype.getFragmentShaderSource = function (program) {
  9105. var shaders = this._gl.getAttachedShaders(program);
  9106. return this._gl.getShaderSource(shaders[1]);
  9107. };
  9108. // FPS
  9109. Engine.prototype.getFps = function () {
  9110. return this.fps;
  9111. };
  9112. Engine.prototype.getDeltaTime = function () {
  9113. return this.deltaTime;
  9114. };
  9115. Engine.prototype._measureFps = function () {
  9116. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9117. var length = this.previousFramesDuration.length;
  9118. if (length >= 2) {
  9119. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9120. }
  9121. if (length >= this.fpsRange) {
  9122. if (length > this.fpsRange) {
  9123. this.previousFramesDuration.splice(0, 1);
  9124. length = this.previousFramesDuration.length;
  9125. }
  9126. var sum = 0;
  9127. for (var id = 0; id < length - 1; id++) {
  9128. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9129. }
  9130. this.fps = 1000.0 / (sum / (length - 1));
  9131. }
  9132. };
  9133. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9134. if (this._webGLVersion > 1) {
  9135. return this._caps.colorBufferFloat;
  9136. }
  9137. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9138. };
  9139. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9140. if (this._webGLVersion > 1) {
  9141. return this._caps.colorBufferFloat;
  9142. }
  9143. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9144. };
  9145. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9146. Engine.prototype._canRenderToFramebuffer = function (type) {
  9147. var gl = this._gl;
  9148. //clear existing errors
  9149. while (gl.getError() !== gl.NO_ERROR) { }
  9150. var successful = true;
  9151. var texture = gl.createTexture();
  9152. gl.bindTexture(gl.TEXTURE_2D, texture);
  9153. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9156. var fb = gl.createFramebuffer();
  9157. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9158. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9159. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9160. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9161. successful = successful && (gl.getError() === gl.NO_ERROR);
  9162. //try render by clearing frame buffer's color buffer
  9163. if (successful) {
  9164. gl.clear(gl.COLOR_BUFFER_BIT);
  9165. successful = successful && (gl.getError() === gl.NO_ERROR);
  9166. }
  9167. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9168. if (successful) {
  9169. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9170. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9171. var readFormat = gl.RGBA;
  9172. var readType = gl.UNSIGNED_BYTE;
  9173. var buffer = new Uint8Array(4);
  9174. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9175. successful = successful && (gl.getError() === gl.NO_ERROR);
  9176. }
  9177. //clean up
  9178. gl.deleteTexture(texture);
  9179. gl.deleteFramebuffer(fb);
  9180. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9181. //clear accumulated errors
  9182. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9183. return successful;
  9184. };
  9185. Engine.prototype._getWebGLTextureType = function (type) {
  9186. if (type === Engine.TEXTURETYPE_FLOAT) {
  9187. return this._gl.FLOAT;
  9188. }
  9189. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9190. // Add Half Float Constant.
  9191. return Engine.HALF_FLOAT_OES;
  9192. }
  9193. return this._gl.UNSIGNED_BYTE;
  9194. };
  9195. ;
  9196. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9197. if (this._webGLVersion === 1) {
  9198. return this._gl.RGBA;
  9199. }
  9200. if (type === Engine.TEXTURETYPE_FLOAT) {
  9201. return Engine.RGBA32F;
  9202. }
  9203. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9204. return Engine.RGBA16F;
  9205. }
  9206. return this._gl.RGBA;
  9207. };
  9208. ;
  9209. // Statics
  9210. Engine.isSupported = function () {
  9211. try {
  9212. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9213. if (navigator.isCocoonJS) {
  9214. return true;
  9215. }
  9216. var tempcanvas = document.createElement("canvas");
  9217. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9218. return gl != null && !!window.WebGLRenderingContext;
  9219. }
  9220. catch (e) {
  9221. return false;
  9222. }
  9223. };
  9224. return Engine;
  9225. }());
  9226. // Const statics
  9227. Engine._ALPHA_DISABLE = 0;
  9228. Engine._ALPHA_ADD = 1;
  9229. Engine._ALPHA_COMBINE = 2;
  9230. Engine._ALPHA_SUBTRACT = 3;
  9231. Engine._ALPHA_MULTIPLY = 4;
  9232. Engine._ALPHA_MAXIMIZED = 5;
  9233. Engine._ALPHA_ONEONE = 6;
  9234. Engine._ALPHA_PREMULTIPLIED = 7;
  9235. Engine._DELAYLOADSTATE_NONE = 0;
  9236. Engine._DELAYLOADSTATE_LOADED = 1;
  9237. Engine._DELAYLOADSTATE_LOADING = 2;
  9238. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9239. Engine._TEXTUREFORMAT_ALPHA = 0;
  9240. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9241. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9242. Engine._TEXTUREFORMAT_RGB = 4;
  9243. Engine._TEXTUREFORMAT_RGBA = 5;
  9244. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9245. Engine._TEXTURETYPE_FLOAT = 1;
  9246. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9247. // Depht or Stencil test Constants.
  9248. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9249. 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.
  9250. 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.
  9251. 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.
  9252. 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.
  9253. 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.
  9254. 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.
  9255. 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.
  9256. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9257. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9258. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9259. // Stencil Actions Constants.
  9260. Engine._KEEP = 0x1E00;
  9261. Engine._REPLACE = 0x1E01;
  9262. Engine._INCR = 0x1E02;
  9263. Engine._DECR = 0x1E03;
  9264. Engine._INVERT = 0x150A;
  9265. Engine._INCR_WRAP = 0x8507;
  9266. Engine._DECR_WRAP = 0x8508;
  9267. // Updatable statics so stick with vars here
  9268. Engine.CollisionsEpsilon = 0.001;
  9269. Engine.CodeRepository = "src/";
  9270. Engine.ShadersRepository = "src/Shaders/";
  9271. BABYLON.Engine = Engine;
  9272. })(BABYLON || (BABYLON = {}));
  9273. //# sourceMappingURL=babylon.engine.js.map
  9274. var BABYLON;
  9275. (function (BABYLON) {
  9276. /**
  9277. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9278. */
  9279. var Node = (function () {
  9280. /**
  9281. * @constructor
  9282. * @param {string} name - the name and id to be given to this node
  9283. * @param {BABYLON.Scene} the scene this node will be added to
  9284. */
  9285. function Node(name, scene) {
  9286. this.state = "";
  9287. this.metadata = null;
  9288. this.doNotSerialize = false;
  9289. this.animations = new Array();
  9290. this._ranges = {};
  9291. this._childrenFlag = -1;
  9292. this._isEnabled = true;
  9293. this._isReady = true;
  9294. this._currentRenderId = -1;
  9295. this._parentRenderId = -1;
  9296. /**
  9297. * An event triggered when the mesh is disposed.
  9298. * @type {BABYLON.Observable}
  9299. */
  9300. this.onDisposeObservable = new BABYLON.Observable();
  9301. this.name = name;
  9302. this.id = name;
  9303. this._scene = scene;
  9304. this._initCache();
  9305. }
  9306. Object.defineProperty(Node.prototype, "parent", {
  9307. get: function () {
  9308. return this._parentNode;
  9309. },
  9310. set: function (parent) {
  9311. if (this._parentNode === parent) {
  9312. return;
  9313. }
  9314. if (this._parentNode) {
  9315. var index = this._parentNode._children.indexOf(this);
  9316. if (index !== -1) {
  9317. this._parentNode._children.splice(index, 1);
  9318. }
  9319. }
  9320. this._parentNode = parent;
  9321. if (this._parentNode) {
  9322. if (!this._parentNode._children) {
  9323. this._parentNode._children = new Array();
  9324. }
  9325. this._parentNode._children.push(this);
  9326. }
  9327. },
  9328. enumerable: true,
  9329. configurable: true
  9330. });
  9331. Node.prototype.getClassName = function () {
  9332. return "Node";
  9333. };
  9334. Object.defineProperty(Node.prototype, "onDispose", {
  9335. set: function (callback) {
  9336. if (this._onDisposeObserver) {
  9337. this.onDisposeObservable.remove(this._onDisposeObserver);
  9338. }
  9339. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9340. },
  9341. enumerable: true,
  9342. configurable: true
  9343. });
  9344. Node.prototype.getScene = function () {
  9345. return this._scene;
  9346. };
  9347. Node.prototype.getEngine = function () {
  9348. return this._scene.getEngine();
  9349. };
  9350. // override it in derived class
  9351. Node.prototype.getWorldMatrix = function () {
  9352. return BABYLON.Matrix.Identity();
  9353. };
  9354. // override it in derived class if you add new variables to the cache
  9355. // and call the parent class method
  9356. Node.prototype._initCache = function () {
  9357. this._cache = {};
  9358. this._cache.parent = undefined;
  9359. };
  9360. Node.prototype.updateCache = function (force) {
  9361. if (!force && this.isSynchronized())
  9362. return;
  9363. this._cache.parent = this.parent;
  9364. this._updateCache();
  9365. };
  9366. // override it in derived class if you add new variables to the cache
  9367. // and call the parent class method if !ignoreParentClass
  9368. Node.prototype._updateCache = function (ignoreParentClass) {
  9369. };
  9370. // override it in derived class if you add new variables to the cache
  9371. Node.prototype._isSynchronized = function () {
  9372. return true;
  9373. };
  9374. Node.prototype._markSyncedWithParent = function () {
  9375. this._parentRenderId = this.parent._currentRenderId;
  9376. };
  9377. Node.prototype.isSynchronizedWithParent = function () {
  9378. if (!this.parent) {
  9379. return true;
  9380. }
  9381. if (this._parentRenderId !== this.parent._currentRenderId) {
  9382. return false;
  9383. }
  9384. return this.parent.isSynchronized();
  9385. };
  9386. Node.prototype.isSynchronized = function (updateCache) {
  9387. var check = this.hasNewParent();
  9388. check = check || !this.isSynchronizedWithParent();
  9389. check = check || !this._isSynchronized();
  9390. if (updateCache)
  9391. this.updateCache(true);
  9392. return !check;
  9393. };
  9394. Node.prototype.hasNewParent = function (update) {
  9395. if (this._cache.parent === this.parent)
  9396. return false;
  9397. if (update)
  9398. this._cache.parent = this.parent;
  9399. return true;
  9400. };
  9401. /**
  9402. * Is this node ready to be used/rendered
  9403. * @return {boolean} is it ready
  9404. */
  9405. Node.prototype.isReady = function () {
  9406. return this._isReady;
  9407. };
  9408. /**
  9409. * Is this node enabled.
  9410. * If the node has a parent and is enabled, the parent will be inspected as well.
  9411. * @return {boolean} whether this node (and its parent) is enabled.
  9412. * @see setEnabled
  9413. */
  9414. Node.prototype.isEnabled = function () {
  9415. if (!this._isEnabled) {
  9416. return false;
  9417. }
  9418. if (this.parent) {
  9419. return this.parent.isEnabled();
  9420. }
  9421. return true;
  9422. };
  9423. /**
  9424. * Set the enabled state of this node.
  9425. * @param {boolean} value - the new enabled state
  9426. * @see isEnabled
  9427. */
  9428. Node.prototype.setEnabled = function (value) {
  9429. this._isEnabled = value;
  9430. };
  9431. /**
  9432. * Is this node a descendant of the given node.
  9433. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9434. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9435. * @see parent
  9436. */
  9437. Node.prototype.isDescendantOf = function (ancestor) {
  9438. if (this.parent) {
  9439. if (this.parent === ancestor) {
  9440. return true;
  9441. }
  9442. return this.parent.isDescendantOf(ancestor);
  9443. }
  9444. return false;
  9445. };
  9446. /**
  9447. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9448. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9449. * @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.
  9450. * @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.
  9451. */
  9452. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9453. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9454. if (!this._children) {
  9455. return;
  9456. }
  9457. for (var index = 0; index < this._children.length; index++) {
  9458. var item = this._children[index];
  9459. if (!predicate || predicate(item)) {
  9460. results.push(item);
  9461. }
  9462. if (!directDescendantsOnly) {
  9463. item._getDescendants(results, false, predicate);
  9464. }
  9465. }
  9466. };
  9467. /**
  9468. * Will return all nodes that have this node as ascendant.
  9469. * @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.
  9470. * @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.
  9471. * @return {BABYLON.Node[]} all children nodes of all types.
  9472. */
  9473. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9474. var results = [];
  9475. this._getDescendants(results, directDescendantsOnly, predicate);
  9476. return results;
  9477. };
  9478. /**
  9479. * @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.
  9480. * @Deprecated, legacy support.
  9481. * use getDecendants instead.
  9482. */
  9483. Node.prototype.getChildren = function (predicate) {
  9484. return this.getDescendants(true, predicate);
  9485. };
  9486. /**
  9487. * Get all child-meshes of this node.
  9488. */
  9489. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9490. var results = [];
  9491. this._getDescendants(results, directDecendantsOnly, function (node) {
  9492. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9493. });
  9494. return results;
  9495. };
  9496. Node.prototype._setReady = function (state) {
  9497. if (state === this._isReady) {
  9498. return;
  9499. }
  9500. if (!state) {
  9501. this._isReady = false;
  9502. return;
  9503. }
  9504. this._isReady = true;
  9505. if (this.onReady) {
  9506. this.onReady(this);
  9507. }
  9508. };
  9509. Node.prototype.getAnimationByName = function (name) {
  9510. for (var i = 0; i < this.animations.length; i++) {
  9511. var animation = this.animations[i];
  9512. if (animation.name === name) {
  9513. return animation;
  9514. }
  9515. }
  9516. return null;
  9517. };
  9518. Node.prototype.createAnimationRange = function (name, from, to) {
  9519. // check name not already in use
  9520. if (!this._ranges[name]) {
  9521. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9522. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9523. if (this.animations[i]) {
  9524. this.animations[i].createRange(name, from, to);
  9525. }
  9526. }
  9527. }
  9528. };
  9529. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9530. if (deleteFrames === void 0) { deleteFrames = true; }
  9531. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9532. if (this.animations[i]) {
  9533. this.animations[i].deleteRange(name, deleteFrames);
  9534. }
  9535. }
  9536. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9537. };
  9538. Node.prototype.getAnimationRange = function (name) {
  9539. return this._ranges[name];
  9540. };
  9541. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9542. var range = this.getAnimationRange(name);
  9543. if (!range) {
  9544. return null;
  9545. }
  9546. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9547. };
  9548. Node.prototype.serializeAnimationRanges = function () {
  9549. var serializationRanges = [];
  9550. for (var name in this._ranges) {
  9551. var range = {};
  9552. range.name = name;
  9553. range.from = this._ranges[name].from;
  9554. range.to = this._ranges[name].to;
  9555. serializationRanges.push(range);
  9556. }
  9557. return serializationRanges;
  9558. };
  9559. Node.prototype.dispose = function () {
  9560. this.parent = null;
  9561. // Callback
  9562. this.onDisposeObservable.notifyObservers(this);
  9563. this.onDisposeObservable.clear();
  9564. };
  9565. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9566. if (parsedNode.ranges) {
  9567. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9568. var data = parsedNode.ranges[index];
  9569. node.createAnimationRange(data.name, data.from, data.to);
  9570. }
  9571. }
  9572. };
  9573. return Node;
  9574. }());
  9575. __decorate([
  9576. BABYLON.serialize()
  9577. ], Node.prototype, "name", void 0);
  9578. __decorate([
  9579. BABYLON.serialize()
  9580. ], Node.prototype, "id", void 0);
  9581. __decorate([
  9582. BABYLON.serialize()
  9583. ], Node.prototype, "uniqueId", void 0);
  9584. __decorate([
  9585. BABYLON.serialize()
  9586. ], Node.prototype, "state", void 0);
  9587. __decorate([
  9588. BABYLON.serialize()
  9589. ], Node.prototype, "metadata", void 0);
  9590. BABYLON.Node = Node;
  9591. })(BABYLON || (BABYLON = {}));
  9592. //# sourceMappingURL=babylon.node.js.map
  9593. var BABYLON;
  9594. (function (BABYLON) {
  9595. var FilesInput = (function () {
  9596. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9597. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9598. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9599. this._engine = p_engine;
  9600. this._canvas = p_canvas;
  9601. this._currentScene = p_scene;
  9602. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9603. this._progressCallback = p_progressCallback;
  9604. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9605. this._textureLoadingCallback = p_textureLoadingCallback;
  9606. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9607. }
  9608. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9609. var _this = this;
  9610. if (p_elementToMonitor) {
  9611. this._elementToMonitor = p_elementToMonitor;
  9612. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9613. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9614. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9615. }
  9616. };
  9617. FilesInput.prototype.renderFunction = function () {
  9618. if (this._additionnalRenderLoopLogicCallback) {
  9619. this._additionnalRenderLoopLogicCallback();
  9620. }
  9621. if (this._currentScene) {
  9622. if (this._textureLoadingCallback) {
  9623. var remaining = this._currentScene.getWaitingItemsCount();
  9624. if (remaining > 0) {
  9625. this._textureLoadingCallback(remaining);
  9626. }
  9627. }
  9628. this._currentScene.render();
  9629. }
  9630. };
  9631. FilesInput.prototype.drag = function (e) {
  9632. e.stopPropagation();
  9633. e.preventDefault();
  9634. };
  9635. FilesInput.prototype.drop = function (eventDrop) {
  9636. eventDrop.stopPropagation();
  9637. eventDrop.preventDefault();
  9638. this.loadFiles(eventDrop);
  9639. };
  9640. FilesInput.prototype.loadFiles = function (event) {
  9641. if (this._startingProcessingFilesCallback)
  9642. this._startingProcessingFilesCallback();
  9643. // Handling data transfer via drag'n'drop
  9644. if (event && event.dataTransfer && event.dataTransfer.files) {
  9645. this._filesToLoad = event.dataTransfer.files;
  9646. }
  9647. // Handling files from input files
  9648. if (event && event.target && event.target.files) {
  9649. this._filesToLoad = event.target.files;
  9650. }
  9651. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9652. for (var i = 0; i < this._filesToLoad.length; i++) {
  9653. var name_1 = this._filesToLoad[i].name.toLowerCase();
  9654. var extension = name_1.split('.').pop();
  9655. var type = this._filesToLoad[i].type;
  9656. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  9657. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  9658. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  9659. }
  9660. else {
  9661. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  9662. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  9663. this._sceneFileToLoad = this._filesToLoad[i];
  9664. }
  9665. else {
  9666. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  9667. }
  9668. }
  9669. }
  9670. this.reload();
  9671. }
  9672. };
  9673. FilesInput.prototype.reload = function () {
  9674. var _this = this;
  9675. var that = this;
  9676. // If a ".babylon" file has been provided
  9677. if (this._sceneFileToLoad) {
  9678. if (this._currentScene) {
  9679. if (BABYLON.Tools.errorsCount > 0) {
  9680. BABYLON.Tools.ClearLogCache();
  9681. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9682. }
  9683. this._engine.stopRenderLoop();
  9684. this._currentScene.dispose();
  9685. }
  9686. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9687. that._currentScene = newScene;
  9688. // Wait for textures and shaders to be ready
  9689. that._currentScene.executeWhenReady(function () {
  9690. // Attach camera to canvas inputs
  9691. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9692. that._currentScene.createDefaultCameraOrLight();
  9693. }
  9694. that._currentScene.activeCamera.attachControl(that._canvas);
  9695. if (that._sceneLoadedCallback) {
  9696. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9697. }
  9698. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9699. });
  9700. }, function (progress) {
  9701. if (_this._progressCallback) {
  9702. _this._progressCallback(progress);
  9703. }
  9704. });
  9705. }
  9706. else {
  9707. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9708. }
  9709. };
  9710. return FilesInput;
  9711. }());
  9712. FilesInput.FilesTextures = new Array();
  9713. FilesInput.FilesToLoad = new Array();
  9714. BABYLON.FilesInput = FilesInput;
  9715. })(BABYLON || (BABYLON = {}));
  9716. //# sourceMappingURL=babylon.filesInput.js.map
  9717. var BABYLON;
  9718. (function (BABYLON) {
  9719. var IntersectionInfo = (function () {
  9720. function IntersectionInfo(bu, bv, distance) {
  9721. this.bu = bu;
  9722. this.bv = bv;
  9723. this.distance = distance;
  9724. this.faceId = 0;
  9725. this.subMeshId = 0;
  9726. }
  9727. return IntersectionInfo;
  9728. }());
  9729. BABYLON.IntersectionInfo = IntersectionInfo;
  9730. var PickingInfo = (function () {
  9731. function PickingInfo() {
  9732. this.hit = false;
  9733. this.distance = 0;
  9734. this.pickedPoint = null;
  9735. this.pickedMesh = null;
  9736. this.bu = 0;
  9737. this.bv = 0;
  9738. this.faceId = -1;
  9739. this.subMeshId = 0;
  9740. this.pickedSprite = null;
  9741. }
  9742. // Methods
  9743. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9744. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9745. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9746. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9747. return null;
  9748. }
  9749. var indices = this.pickedMesh.getIndices();
  9750. var result;
  9751. if (useVerticesNormals) {
  9752. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9753. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9754. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9755. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9756. normal0 = normal0.scale(this.bu);
  9757. normal1 = normal1.scale(this.bv);
  9758. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9759. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9760. }
  9761. else {
  9762. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9763. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9764. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9765. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9766. var p1p2 = vertex1.subtract(vertex2);
  9767. var p3p2 = vertex3.subtract(vertex2);
  9768. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9769. }
  9770. if (useWorldCoordinates) {
  9771. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9772. }
  9773. return BABYLON.Vector3.Normalize(result);
  9774. };
  9775. PickingInfo.prototype.getTextureCoordinates = function () {
  9776. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9777. return null;
  9778. }
  9779. var indices = this.pickedMesh.getIndices();
  9780. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9781. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9782. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9783. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9784. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9785. uv1 = uv1.scale(this.bu);
  9786. uv2 = uv2.scale(this.bv);
  9787. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9788. };
  9789. return PickingInfo;
  9790. }());
  9791. BABYLON.PickingInfo = PickingInfo;
  9792. })(BABYLON || (BABYLON = {}));
  9793. //# sourceMappingURL=babylon.pickingInfo.js.map
  9794. var BABYLON;
  9795. (function (BABYLON) {
  9796. var BoundingSphere = (function () {
  9797. function BoundingSphere(minimum, maximum) {
  9798. this.minimum = minimum;
  9799. this.maximum = maximum;
  9800. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9801. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9802. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9803. this.radius = distance * 0.5;
  9804. this.centerWorld = BABYLON.Vector3.Zero();
  9805. this._update(BABYLON.Matrix.Identity());
  9806. }
  9807. // Methods
  9808. BoundingSphere.prototype._update = function (world) {
  9809. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9810. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9811. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9812. };
  9813. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9814. for (var i = 0; i < 6; i++) {
  9815. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9816. return false;
  9817. }
  9818. return true;
  9819. };
  9820. BoundingSphere.prototype.intersectsPoint = function (point) {
  9821. var x = this.centerWorld.x - point.x;
  9822. var y = this.centerWorld.y - point.y;
  9823. var z = this.centerWorld.z - point.z;
  9824. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9825. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9826. return false;
  9827. return true;
  9828. };
  9829. // Statics
  9830. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9831. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9832. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9833. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9834. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9835. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9836. return false;
  9837. return true;
  9838. };
  9839. return BoundingSphere;
  9840. }());
  9841. BABYLON.BoundingSphere = BoundingSphere;
  9842. })(BABYLON || (BABYLON = {}));
  9843. //# sourceMappingURL=babylon.boundingSphere.js.map
  9844. var BABYLON;
  9845. (function (BABYLON) {
  9846. var BoundingBox = (function () {
  9847. function BoundingBox(minimum, maximum) {
  9848. this.minimum = minimum;
  9849. this.maximum = maximum;
  9850. this.vectors = new Array();
  9851. this.vectorsWorld = new Array();
  9852. // Bounding vectors
  9853. this.vectors.push(this.minimum.clone());
  9854. this.vectors.push(this.maximum.clone());
  9855. this.vectors.push(this.minimum.clone());
  9856. this.vectors[2].x = this.maximum.x;
  9857. this.vectors.push(this.minimum.clone());
  9858. this.vectors[3].y = this.maximum.y;
  9859. this.vectors.push(this.minimum.clone());
  9860. this.vectors[4].z = this.maximum.z;
  9861. this.vectors.push(this.maximum.clone());
  9862. this.vectors[5].z = this.minimum.z;
  9863. this.vectors.push(this.maximum.clone());
  9864. this.vectors[6].x = this.minimum.x;
  9865. this.vectors.push(this.maximum.clone());
  9866. this.vectors[7].y = this.minimum.y;
  9867. // OBB
  9868. this.center = this.maximum.add(this.minimum).scale(0.5);
  9869. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9870. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9871. // World
  9872. for (var index = 0; index < this.vectors.length; index++) {
  9873. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9874. }
  9875. this.minimumWorld = BABYLON.Vector3.Zero();
  9876. this.maximumWorld = BABYLON.Vector3.Zero();
  9877. this._update(BABYLON.Matrix.Identity());
  9878. }
  9879. // Methods
  9880. BoundingBox.prototype.getWorldMatrix = function () {
  9881. return this._worldMatrix;
  9882. };
  9883. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9884. this._worldMatrix.copyFrom(matrix);
  9885. return this;
  9886. };
  9887. BoundingBox.prototype._update = function (world) {
  9888. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9889. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9890. for (var index = 0; index < this.vectors.length; index++) {
  9891. var v = this.vectorsWorld[index];
  9892. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9893. if (v.x < this.minimumWorld.x)
  9894. this.minimumWorld.x = v.x;
  9895. if (v.y < this.minimumWorld.y)
  9896. this.minimumWorld.y = v.y;
  9897. if (v.z < this.minimumWorld.z)
  9898. this.minimumWorld.z = v.z;
  9899. if (v.x > this.maximumWorld.x)
  9900. this.maximumWorld.x = v.x;
  9901. if (v.y > this.maximumWorld.y)
  9902. this.maximumWorld.y = v.y;
  9903. if (v.z > this.maximumWorld.z)
  9904. this.maximumWorld.z = v.z;
  9905. }
  9906. // OBB
  9907. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9908. this.center.scaleInPlace(0.5);
  9909. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9910. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9911. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9912. this._worldMatrix = world;
  9913. };
  9914. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9915. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9916. };
  9917. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9918. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9919. };
  9920. BoundingBox.prototype.intersectsPoint = function (point) {
  9921. var delta = -BABYLON.Epsilon;
  9922. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9923. return false;
  9924. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9925. return false;
  9926. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9927. return false;
  9928. return true;
  9929. };
  9930. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9931. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9932. };
  9933. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9934. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9935. return false;
  9936. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9937. return false;
  9938. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9939. return false;
  9940. return true;
  9941. };
  9942. // Statics
  9943. BoundingBox.Intersects = function (box0, box1) {
  9944. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9945. return false;
  9946. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9947. return false;
  9948. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9949. return false;
  9950. return true;
  9951. };
  9952. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9953. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9954. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9955. return (num <= (sphereRadius * sphereRadius));
  9956. };
  9957. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9958. for (var p = 0; p < 6; p++) {
  9959. for (var i = 0; i < 8; i++) {
  9960. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9961. return false;
  9962. }
  9963. }
  9964. }
  9965. return true;
  9966. };
  9967. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9968. for (var p = 0; p < 6; p++) {
  9969. var inCount = 8;
  9970. for (var i = 0; i < 8; i++) {
  9971. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9972. --inCount;
  9973. }
  9974. else {
  9975. break;
  9976. }
  9977. }
  9978. if (inCount === 0)
  9979. return false;
  9980. }
  9981. return true;
  9982. };
  9983. return BoundingBox;
  9984. }());
  9985. BABYLON.BoundingBox = BoundingBox;
  9986. })(BABYLON || (BABYLON = {}));
  9987. //# sourceMappingURL=babylon.boundingBox.js.map
  9988. var BABYLON;
  9989. (function (BABYLON) {
  9990. var computeBoxExtents = function (axis, box) {
  9991. var p = BABYLON.Vector3.Dot(box.center, axis);
  9992. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9993. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9994. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9995. var r = r0 + r1 + r2;
  9996. return {
  9997. min: p - r,
  9998. max: p + r
  9999. };
  10000. };
  10001. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10002. var axisOverlap = function (axis, box0, box1) {
  10003. var result0 = computeBoxExtents(axis, box0);
  10004. var result1 = computeBoxExtents(axis, box1);
  10005. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10006. };
  10007. var BoundingInfo = (function () {
  10008. function BoundingInfo(minimum, maximum) {
  10009. this.minimum = minimum;
  10010. this.maximum = maximum;
  10011. this._isLocked = false;
  10012. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10013. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10014. }
  10015. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10016. get: function () {
  10017. return this._isLocked;
  10018. },
  10019. set: function (value) {
  10020. this._isLocked = value;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. // Methods
  10026. BoundingInfo.prototype.update = function (world) {
  10027. if (this._isLocked) {
  10028. return;
  10029. }
  10030. this.boundingBox._update(world);
  10031. this.boundingSphere._update(world);
  10032. };
  10033. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10034. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10035. return false;
  10036. return this.boundingBox.isInFrustum(frustumPlanes);
  10037. };
  10038. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10039. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10040. };
  10041. BoundingInfo.prototype._checkCollision = function (collider) {
  10042. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10043. };
  10044. BoundingInfo.prototype.intersectsPoint = function (point) {
  10045. if (!this.boundingSphere.centerWorld) {
  10046. return false;
  10047. }
  10048. if (!this.boundingSphere.intersectsPoint(point)) {
  10049. return false;
  10050. }
  10051. if (!this.boundingBox.intersectsPoint(point)) {
  10052. return false;
  10053. }
  10054. return true;
  10055. };
  10056. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10057. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10058. return false;
  10059. }
  10060. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10061. return false;
  10062. }
  10063. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10064. return false;
  10065. }
  10066. if (!precise) {
  10067. return true;
  10068. }
  10069. var box0 = this.boundingBox;
  10070. var box1 = boundingInfo.boundingBox;
  10071. if (!axisOverlap(box0.directions[0], box0, box1))
  10072. return false;
  10073. if (!axisOverlap(box0.directions[1], box0, box1))
  10074. return false;
  10075. if (!axisOverlap(box0.directions[2], box0, box1))
  10076. return false;
  10077. if (!axisOverlap(box1.directions[0], box0, box1))
  10078. return false;
  10079. if (!axisOverlap(box1.directions[1], box0, box1))
  10080. return false;
  10081. if (!axisOverlap(box1.directions[2], box0, box1))
  10082. return false;
  10083. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10084. return false;
  10085. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10086. return false;
  10087. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10088. return false;
  10089. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10090. return false;
  10091. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10092. return false;
  10093. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10094. return false;
  10095. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10096. return false;
  10097. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10098. return false;
  10099. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10100. return false;
  10101. return true;
  10102. };
  10103. return BoundingInfo;
  10104. }());
  10105. BABYLON.BoundingInfo = BoundingInfo;
  10106. })(BABYLON || (BABYLON = {}));
  10107. //# sourceMappingURL=babylon.boundingInfo.js.map
  10108. var BABYLON;
  10109. (function (BABYLON) {
  10110. var Ray = (function () {
  10111. function Ray(origin, direction, length) {
  10112. if (length === void 0) { length = Number.MAX_VALUE; }
  10113. this.origin = origin;
  10114. this.direction = direction;
  10115. this.length = length;
  10116. }
  10117. // Methods
  10118. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10119. var d = 0.0;
  10120. var maxValue = Number.MAX_VALUE;
  10121. var inv;
  10122. var min;
  10123. var max;
  10124. var temp;
  10125. if (Math.abs(this.direction.x) < 0.0000001) {
  10126. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10127. return false;
  10128. }
  10129. }
  10130. else {
  10131. inv = 1.0 / this.direction.x;
  10132. min = (minimum.x - this.origin.x) * inv;
  10133. max = (maximum.x - this.origin.x) * inv;
  10134. if (max === -Infinity) {
  10135. max = Infinity;
  10136. }
  10137. if (min > max) {
  10138. temp = min;
  10139. min = max;
  10140. max = temp;
  10141. }
  10142. d = Math.max(min, d);
  10143. maxValue = Math.min(max, maxValue);
  10144. if (d > maxValue) {
  10145. return false;
  10146. }
  10147. }
  10148. if (Math.abs(this.direction.y) < 0.0000001) {
  10149. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10150. return false;
  10151. }
  10152. }
  10153. else {
  10154. inv = 1.0 / this.direction.y;
  10155. min = (minimum.y - this.origin.y) * inv;
  10156. max = (maximum.y - this.origin.y) * inv;
  10157. if (max === -Infinity) {
  10158. max = Infinity;
  10159. }
  10160. if (min > max) {
  10161. temp = min;
  10162. min = max;
  10163. max = temp;
  10164. }
  10165. d = Math.max(min, d);
  10166. maxValue = Math.min(max, maxValue);
  10167. if (d > maxValue) {
  10168. return false;
  10169. }
  10170. }
  10171. if (Math.abs(this.direction.z) < 0.0000001) {
  10172. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10173. return false;
  10174. }
  10175. }
  10176. else {
  10177. inv = 1.0 / this.direction.z;
  10178. min = (minimum.z - this.origin.z) * inv;
  10179. max = (maximum.z - this.origin.z) * inv;
  10180. if (max === -Infinity) {
  10181. max = Infinity;
  10182. }
  10183. if (min > max) {
  10184. temp = min;
  10185. min = max;
  10186. max = temp;
  10187. }
  10188. d = Math.max(min, d);
  10189. maxValue = Math.min(max, maxValue);
  10190. if (d > maxValue) {
  10191. return false;
  10192. }
  10193. }
  10194. return true;
  10195. };
  10196. Ray.prototype.intersectsBox = function (box) {
  10197. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10198. };
  10199. Ray.prototype.intersectsSphere = function (sphere) {
  10200. var x = sphere.center.x - this.origin.x;
  10201. var y = sphere.center.y - this.origin.y;
  10202. var z = sphere.center.z - this.origin.z;
  10203. var pyth = (x * x) + (y * y) + (z * z);
  10204. var rr = sphere.radius * sphere.radius;
  10205. if (pyth <= rr) {
  10206. return true;
  10207. }
  10208. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10209. if (dot < 0.0) {
  10210. return false;
  10211. }
  10212. var temp = pyth - (dot * dot);
  10213. return temp <= rr;
  10214. };
  10215. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10216. if (!this._edge1) {
  10217. this._edge1 = BABYLON.Vector3.Zero();
  10218. this._edge2 = BABYLON.Vector3.Zero();
  10219. this._pvec = BABYLON.Vector3.Zero();
  10220. this._tvec = BABYLON.Vector3.Zero();
  10221. this._qvec = BABYLON.Vector3.Zero();
  10222. }
  10223. vertex1.subtractToRef(vertex0, this._edge1);
  10224. vertex2.subtractToRef(vertex0, this._edge2);
  10225. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10226. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10227. if (det === 0) {
  10228. return null;
  10229. }
  10230. var invdet = 1 / det;
  10231. this.origin.subtractToRef(vertex0, this._tvec);
  10232. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10233. if (bu < 0 || bu > 1.0) {
  10234. return null;
  10235. }
  10236. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10237. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10238. if (bv < 0 || bu + bv > 1.0) {
  10239. return null;
  10240. }
  10241. //check if the distance is longer than the predefined length.
  10242. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10243. if (distance > this.length) {
  10244. return null;
  10245. }
  10246. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10247. };
  10248. Ray.prototype.intersectsPlane = function (plane) {
  10249. var distance;
  10250. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10251. if (Math.abs(result1) < 9.99999997475243E-07) {
  10252. return null;
  10253. }
  10254. else {
  10255. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10256. distance = (-plane.d - result2) / result1;
  10257. if (distance < 0.0) {
  10258. if (distance < -9.99999997475243E-07) {
  10259. return null;
  10260. }
  10261. else {
  10262. return 0;
  10263. }
  10264. }
  10265. return distance;
  10266. }
  10267. };
  10268. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10269. var tm = BABYLON.Tmp.Matrix[0];
  10270. mesh.getWorldMatrix().invertToRef(tm);
  10271. if (this._tmpRay) {
  10272. Ray.TransformToRef(this, tm, this._tmpRay);
  10273. }
  10274. else {
  10275. this._tmpRay = Ray.Transform(this, tm);
  10276. }
  10277. return mesh.intersects(this._tmpRay, fastCheck);
  10278. };
  10279. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  10280. if (results) {
  10281. results.length = 0;
  10282. }
  10283. else {
  10284. results = [];
  10285. }
  10286. for (var i = 0; i < meshes.length; i++) {
  10287. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  10288. if (pickInfo.hit) {
  10289. results.push(pickInfo);
  10290. }
  10291. }
  10292. results.sort(this._comparePickingInfo);
  10293. return results;
  10294. };
  10295. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  10296. if (pickingInfoA.distance < pickingInfoB.distance) {
  10297. return -1;
  10298. }
  10299. else if (pickingInfoA.distance > pickingInfoB.distance) {
  10300. return 1;
  10301. }
  10302. else {
  10303. return 0;
  10304. }
  10305. };
  10306. /**
  10307. * @Deprecated. Use new RayHelper.show() instead.
  10308. * */
  10309. Ray.prototype.show = function (scene, color) {
  10310. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  10311. if (!this._rayHelper) {
  10312. this._rayHelper = new BABYLON.RayHelper(this);
  10313. }
  10314. this._rayHelper.show(scene, color);
  10315. };
  10316. /**
  10317. * @Deprecated. Use new RayHelper.hide() instead.
  10318. * */
  10319. Ray.prototype.hide = function () {
  10320. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  10321. if (this._rayHelper) {
  10322. this._rayHelper.hide();
  10323. this._rayHelper = null;
  10324. }
  10325. };
  10326. /**
  10327. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10328. * @param sega the first point of the segment to test the intersection against
  10329. * @param segb the second point of the segment to test the intersection against
  10330. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10331. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10332. */
  10333. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10334. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10335. var u = segb.subtract(sega);
  10336. var v = rsegb.subtract(this.origin);
  10337. var w = sega.subtract(this.origin);
  10338. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10339. var b = BABYLON.Vector3.Dot(u, v);
  10340. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10341. var d = BABYLON.Vector3.Dot(u, w);
  10342. var e = BABYLON.Vector3.Dot(v, w);
  10343. var D = a * c - b * b; // always >= 0
  10344. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10345. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10346. // compute the line parameters of the two closest points
  10347. if (D < Ray.smallnum) {
  10348. sN = 0.0; // force using point P0 on segment S1
  10349. sD = 1.0; // to prevent possible division by 0.0 later
  10350. tN = e;
  10351. tD = c;
  10352. }
  10353. else {
  10354. sN = (b * e - c * d);
  10355. tN = (a * e - b * d);
  10356. if (sN < 0.0) {
  10357. sN = 0.0;
  10358. tN = e;
  10359. tD = c;
  10360. }
  10361. else if (sN > sD) {
  10362. sN = sD;
  10363. tN = e + b;
  10364. tD = c;
  10365. }
  10366. }
  10367. if (tN < 0.0) {
  10368. tN = 0.0;
  10369. // recompute sc for this edge
  10370. if (-d < 0.0) {
  10371. sN = 0.0;
  10372. }
  10373. else if (-d > a)
  10374. sN = sD;
  10375. else {
  10376. sN = -d;
  10377. sD = a;
  10378. }
  10379. }
  10380. else if (tN > tD) {
  10381. tN = tD;
  10382. // recompute sc for this edge
  10383. if ((-d + b) < 0.0) {
  10384. sN = 0;
  10385. }
  10386. else if ((-d + b) > a) {
  10387. sN = sD;
  10388. }
  10389. else {
  10390. sN = (-d + b);
  10391. sD = a;
  10392. }
  10393. }
  10394. // finally do the division to get sc and tc
  10395. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10396. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10397. // get the difference of the two closest points
  10398. var qtc = v.multiplyByFloats(tc, tc, tc);
  10399. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10400. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10401. if (isIntersected) {
  10402. return qtc.length();
  10403. }
  10404. return -1;
  10405. };
  10406. // Statics
  10407. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10408. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10409. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10410. var direction = end.subtract(start);
  10411. direction.normalize();
  10412. return new Ray(start, direction);
  10413. };
  10414. /**
  10415. * 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
  10416. * transformed to the given world matrix.
  10417. * @param origin The origin point
  10418. * @param end The end point
  10419. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10420. */
  10421. Ray.CreateNewFromTo = function (origin, end, world) {
  10422. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10423. var direction = end.subtract(origin);
  10424. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10425. direction.normalize();
  10426. return Ray.Transform(new Ray(origin, direction, length), world);
  10427. };
  10428. Ray.Transform = function (ray, matrix) {
  10429. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10430. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10431. newDirection.normalize();
  10432. return new Ray(newOrigin, newDirection, ray.length);
  10433. };
  10434. Ray.TransformToRef = function (ray, matrix, result) {
  10435. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10436. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10437. ray.direction.normalize();
  10438. };
  10439. return Ray;
  10440. }());
  10441. Ray.smallnum = 0.00000001;
  10442. Ray.rayl = 10e8;
  10443. BABYLON.Ray = Ray;
  10444. })(BABYLON || (BABYLON = {}));
  10445. //# sourceMappingURL=babylon.ray.js.map
  10446. var BABYLON;
  10447. (function (BABYLON) {
  10448. var RayHelper = (function () {
  10449. function RayHelper(ray) {
  10450. this.ray = ray;
  10451. }
  10452. RayHelper.prototype.show = function (scene, color) {
  10453. if (!this._renderFunction) {
  10454. var ray = this.ray;
  10455. this._renderFunction = this._render.bind(this);
  10456. this._scene = scene;
  10457. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  10458. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10459. this._scene.registerBeforeRender(this._renderFunction);
  10460. }
  10461. if (color) {
  10462. this._renderLine.color.copyFrom(color);
  10463. }
  10464. };
  10465. RayHelper.prototype.hide = function () {
  10466. if (this._renderFunction) {
  10467. this._scene.unregisterBeforeRender(this._renderFunction);
  10468. this._scene = null;
  10469. this._renderFunction = null;
  10470. this._renderLine.dispose();
  10471. this._renderLine = null;
  10472. this._renderPoints = null;
  10473. }
  10474. };
  10475. RayHelper.prototype._render = function () {
  10476. var ray = this.ray;
  10477. var point = this._renderPoints[1];
  10478. var len = Math.min(ray.length, 1000000);
  10479. point.copyFrom(ray.direction);
  10480. point.scaleInPlace(len);
  10481. point.addInPlace(ray.origin);
  10482. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10483. };
  10484. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  10485. this._attachedToMesh = mesh;
  10486. var ray = this.ray;
  10487. if (!ray.direction) {
  10488. ray.direction = BABYLON.Vector3.Zero();
  10489. }
  10490. if (!ray.origin) {
  10491. ray.origin = BABYLON.Vector3.Zero();
  10492. }
  10493. if (length) {
  10494. ray.length = length;
  10495. }
  10496. if (!meshSpaceOrigin) {
  10497. meshSpaceOrigin = BABYLON.Vector3.Zero();
  10498. }
  10499. if (!meshSpaceDirection) {
  10500. // -1 so that this will work with Mesh.lookAt
  10501. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  10502. }
  10503. if (!this._meshSpaceDirection) {
  10504. this._meshSpaceDirection = meshSpaceDirection.clone();
  10505. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  10506. }
  10507. else {
  10508. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  10509. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  10510. }
  10511. if (!this._updateToMeshFunction) {
  10512. this._updateToMeshFunction = this._updateToMesh.bind(this);
  10513. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  10514. }
  10515. this._updateToMesh();
  10516. };
  10517. RayHelper.prototype.detachFromMesh = function () {
  10518. if (this._attachedToMesh) {
  10519. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  10520. this._attachedToMesh = null;
  10521. this._updateToMeshFunction = null;
  10522. }
  10523. };
  10524. RayHelper.prototype._updateToMesh = function () {
  10525. var ray = this.ray;
  10526. if (this._attachedToMesh._isDisposed) {
  10527. this.detachFromMesh();
  10528. return;
  10529. }
  10530. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  10531. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  10532. };
  10533. RayHelper.prototype.dispose = function () {
  10534. this.hide();
  10535. this.detachFromMesh();
  10536. this.ray = null;
  10537. };
  10538. return RayHelper;
  10539. }());
  10540. BABYLON.RayHelper = RayHelper;
  10541. })(BABYLON || (BABYLON = {}));
  10542. //# sourceMappingURL=babylon.rayHelper.js.map
  10543. var BABYLON;
  10544. (function (BABYLON) {
  10545. var AbstractMesh = (function (_super) {
  10546. __extends(AbstractMesh, _super);
  10547. // Constructor
  10548. function AbstractMesh(name, scene) {
  10549. var _this = _super.call(this, name, scene) || this;
  10550. _this._facetNb = 0; // facet number
  10551. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10552. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10553. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10554. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10555. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10556. _this._subDiv = {
  10557. max: 1,
  10558. X: 1,
  10559. Y: 1,
  10560. Z: 1
  10561. };
  10562. // Events
  10563. /**
  10564. * An event triggered when this mesh collides with another one
  10565. * @type {BABYLON.Observable}
  10566. */
  10567. _this.onCollideObservable = new BABYLON.Observable();
  10568. /**
  10569. * An event triggered when the collision's position changes
  10570. * @type {BABYLON.Observable}
  10571. */
  10572. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10573. /**
  10574. * An event triggered after the world matrix is updated
  10575. * @type {BABYLON.Observable}
  10576. */
  10577. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10578. // Properties
  10579. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10580. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10581. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10582. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10583. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10584. _this.visibility = 1.0;
  10585. _this.alphaIndex = Number.MAX_VALUE;
  10586. _this.infiniteDistance = false;
  10587. _this.isVisible = true;
  10588. _this.isPickable = true;
  10589. _this.showBoundingBox = false;
  10590. _this.showSubMeshesBoundingBox = false;
  10591. _this.isBlocker = false;
  10592. _this.renderingGroupId = 0;
  10593. _this.receiveShadows = false;
  10594. _this.renderOutline = false;
  10595. _this.outlineColor = BABYLON.Color3.Red();
  10596. _this.outlineWidth = 0.02;
  10597. _this.renderOverlay = false;
  10598. _this.overlayColor = BABYLON.Color3.Red();
  10599. _this.overlayAlpha = 0.5;
  10600. _this.hasVertexAlpha = false;
  10601. _this.useVertexColors = true;
  10602. _this.applyFog = true;
  10603. _this.computeBonesUsingShaders = true;
  10604. _this.scalingDeterminant = 1;
  10605. _this.numBoneInfluencers = 4;
  10606. _this.useOctreeForRenderingSelection = true;
  10607. _this.useOctreeForPicking = true;
  10608. _this.useOctreeForCollisions = true;
  10609. _this.layerMask = 0x0FFFFFFF;
  10610. /**
  10611. * True if the mesh must be rendered in any case.
  10612. */
  10613. _this.alwaysSelectAsActiveMesh = false;
  10614. // Collisions
  10615. _this._checkCollisions = false;
  10616. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10617. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10618. _this._collider = new BABYLON.Collider();
  10619. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10620. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10621. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10622. // Edges
  10623. _this.edgesWidth = 1;
  10624. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10625. // Cache
  10626. _this._localWorld = BABYLON.Matrix.Zero();
  10627. _this._worldMatrix = BABYLON.Matrix.Zero();
  10628. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10629. _this._absolutePosition = BABYLON.Vector3.Zero();
  10630. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10631. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10632. _this._isDirty = false;
  10633. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10634. _this._isDisposed = false;
  10635. _this._renderId = 0;
  10636. _this._intersectionsInProgress = new Array();
  10637. _this._isWorldMatrixFrozen = false;
  10638. _this._unIndexed = false;
  10639. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10640. if (collidedMesh === void 0) { collidedMesh = null; }
  10641. //TODO move this to the collision coordinator!
  10642. if (_this.getScene().workerCollisions)
  10643. newPosition.multiplyInPlace(_this._collider.radius);
  10644. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10645. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10646. _this.position.addInPlace(_this._diffPositionForCollisions);
  10647. }
  10648. if (collidedMesh) {
  10649. _this.onCollideObservable.notifyObservers(collidedMesh);
  10650. }
  10651. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10652. };
  10653. scene.addMesh(_this);
  10654. return _this;
  10655. }
  10656. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10657. get: function () {
  10658. return AbstractMesh._BILLBOARDMODE_NONE;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10664. get: function () {
  10665. return AbstractMesh._BILLBOARDMODE_X;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10671. get: function () {
  10672. return AbstractMesh._BILLBOARDMODE_Y;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10678. get: function () {
  10679. return AbstractMesh._BILLBOARDMODE_Z;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10685. get: function () {
  10686. return AbstractMesh._BILLBOARDMODE_ALL;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10692. /**
  10693. * Read-only : the number of facets in the mesh
  10694. */
  10695. get: function () {
  10696. return this._facetNb;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10702. /**
  10703. * The number of subdivisions per axis in the partioning space
  10704. */
  10705. get: function () {
  10706. return this._partitioningSubdivisions;
  10707. },
  10708. set: function (nb) {
  10709. this._partitioningSubdivisions = nb;
  10710. },
  10711. enumerable: true,
  10712. configurable: true
  10713. });
  10714. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10715. /**
  10716. * The ratio to apply to the bouding box size to set to the partioning space.
  10717. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10718. */
  10719. get: function () {
  10720. return this._partitioningBBoxRatio;
  10721. },
  10722. set: function (ratio) {
  10723. this._partitioningBBoxRatio = ratio;
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10729. /**
  10730. * Read-only : is the feature facetData enabled ?
  10731. */
  10732. get: function () {
  10733. return this._facetDataEnabled;
  10734. },
  10735. enumerable: true,
  10736. configurable: true
  10737. });
  10738. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10739. set: function (callback) {
  10740. if (this._onCollideObserver) {
  10741. this.onCollideObservable.remove(this._onCollideObserver);
  10742. }
  10743. this._onCollideObserver = this.onCollideObservable.add(callback);
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10749. set: function (callback) {
  10750. if (this._onCollisionPositionChangeObserver) {
  10751. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10752. }
  10753. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10754. },
  10755. enumerable: true,
  10756. configurable: true
  10757. });
  10758. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10759. get: function () {
  10760. return this._skeleton;
  10761. },
  10762. set: function (value) {
  10763. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10764. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10765. }
  10766. if (value && value.needInitialSkinMatrix) {
  10767. value._registerMeshWithPoseMatrix(this);
  10768. }
  10769. this._skeleton = value;
  10770. if (!this._skeleton) {
  10771. this._bonesTransformMatrices = null;
  10772. }
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. /**
  10778. * Returns the string "AbstractMesh"
  10779. */
  10780. AbstractMesh.prototype.getClassName = function () {
  10781. return "AbstractMesh";
  10782. };
  10783. /**
  10784. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10785. */
  10786. AbstractMesh.prototype.toString = function (fullDetails) {
  10787. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10788. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10789. if (this._skeleton) {
  10790. ret += ", skeleton: " + this._skeleton.name;
  10791. }
  10792. if (fullDetails) {
  10793. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10794. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10795. }
  10796. return ret;
  10797. };
  10798. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10799. /**
  10800. * Ratation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  10801. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  10802. * Default : (0.0, 0.0, 0.0)
  10803. */
  10804. get: function () {
  10805. return this._rotation;
  10806. },
  10807. set: function (newRotation) {
  10808. this._rotation = newRotation;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10814. /**
  10815. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  10816. * Default : (1.0, 1.0, 1.0)
  10817. */
  10818. get: function () {
  10819. return this._scaling;
  10820. },
  10821. set: function (newScaling) {
  10822. this._scaling = newScaling;
  10823. if (this.physicsImpostor) {
  10824. this.physicsImpostor.forceUpdate();
  10825. }
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10831. /**
  10832. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  10833. * It's null by default.
  10834. * 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)
  10835. */
  10836. get: function () {
  10837. return this._rotationQuaternion;
  10838. },
  10839. set: function (quaternion) {
  10840. this._rotationQuaternion = quaternion;
  10841. //reset the rotation vector.
  10842. if (quaternion && this.rotation.length()) {
  10843. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  10844. }
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. // Methods
  10850. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10851. this._poseMatrix.copyFrom(matrix);
  10852. };
  10853. AbstractMesh.prototype.getPoseMatrix = function () {
  10854. return this._poseMatrix;
  10855. };
  10856. AbstractMesh.prototype.disableEdgesRendering = function () {
  10857. if (this._edgesRenderer !== undefined) {
  10858. this._edgesRenderer.dispose();
  10859. this._edgesRenderer = undefined;
  10860. }
  10861. };
  10862. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10863. if (epsilon === void 0) { epsilon = 0.95; }
  10864. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10865. this.disableEdgesRendering();
  10866. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10867. };
  10868. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10869. get: function () {
  10870. return false;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. /**
  10876. * Returns this by default, used by the class Mesh.
  10877. * Returned type : AbstractMesh
  10878. */
  10879. AbstractMesh.prototype.getLOD = function (camera) {
  10880. return this;
  10881. };
  10882. /**
  10883. * Returns 0 by default, used by the class Mesh.
  10884. * Returns an integer.
  10885. */
  10886. AbstractMesh.prototype.getTotalVertices = function () {
  10887. return 0;
  10888. };
  10889. /**
  10890. * Returns null by default, used by the class Mesh.
  10891. * Returned type : integer array
  10892. */
  10893. AbstractMesh.prototype.getIndices = function () {
  10894. return null;
  10895. };
  10896. /**
  10897. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  10898. * Returned type : float array or Float32Array
  10899. */
  10900. AbstractMesh.prototype.getVerticesData = function (kind) {
  10901. return null;
  10902. };
  10903. /** Returns false by default, used by the class Mesh.
  10904. * Returns a boolean
  10905. */
  10906. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10907. return false;
  10908. };
  10909. /**
  10910. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  10911. * Returns a BoundingInfo
  10912. */
  10913. AbstractMesh.prototype.getBoundingInfo = function () {
  10914. if (this._masterMesh) {
  10915. return this._masterMesh.getBoundingInfo();
  10916. }
  10917. if (!this._boundingInfo) {
  10918. this._updateBoundingInfo();
  10919. }
  10920. return this._boundingInfo;
  10921. };
  10922. /**
  10923. * Sets a mesh new object BoundingInfo.
  10924. * Returns nothing.
  10925. */
  10926. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10927. this._boundingInfo = boundingInfo;
  10928. };
  10929. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10930. get: function () {
  10931. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. AbstractMesh.prototype._preActivate = function () {
  10937. };
  10938. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10939. };
  10940. AbstractMesh.prototype._activate = function (renderId) {
  10941. this._renderId = renderId;
  10942. };
  10943. /**
  10944. * Returns the last update of the World matrix
  10945. * Returns a Matrix.
  10946. */
  10947. AbstractMesh.prototype.getWorldMatrix = function () {
  10948. if (this._masterMesh) {
  10949. return this._masterMesh.getWorldMatrix();
  10950. }
  10951. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10952. this.computeWorldMatrix();
  10953. }
  10954. return this._worldMatrix;
  10955. };
  10956. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10957. /**
  10958. * Returns directly the last state of the mesh World matrix.
  10959. * A Matrix is returned.
  10960. */
  10961. get: function () {
  10962. return this._worldMatrix;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10968. /**
  10969. * Returns the current mesh absolute position.
  10970. * Retuns a Vector3
  10971. */
  10972. get: function () {
  10973. return this._absolutePosition;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. /**
  10979. * Prevents the World matrix to be computed any longer.
  10980. * Returns nothing.
  10981. */
  10982. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10983. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10984. this.computeWorldMatrix(true);
  10985. this._isWorldMatrixFrozen = true;
  10986. };
  10987. /**
  10988. * Allows back the World matrix computation.
  10989. * Returns nothing.
  10990. */
  10991. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10992. this._isWorldMatrixFrozen = false;
  10993. this.computeWorldMatrix(true);
  10994. };
  10995. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10996. /**
  10997. * True if the World matrix has been frozen.
  10998. * Returns a boolean.
  10999. */
  11000. get: function () {
  11001. return this._isWorldMatrixFrozen;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. /**
  11007. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11008. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD
  11009. */
  11010. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11011. axis.normalize();
  11012. if (!this.rotationQuaternion) {
  11013. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11014. this.rotation = BABYLON.Vector3.Zero();
  11015. }
  11016. var rotationQuaternion;
  11017. if (!space || space === BABYLON.Space.LOCAL) {
  11018. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11019. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11020. }
  11021. else {
  11022. if (this.parent) {
  11023. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11024. invertParentWorldMatrix.invert();
  11025. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11026. }
  11027. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11028. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11029. }
  11030. };
  11031. /**
  11032. * Translates the mesh along the axis vector for the passed distance in the given space.
  11033. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD
  11034. */
  11035. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11036. var displacementVector = axis.scale(distance);
  11037. if (!space || space === BABYLON.Space.LOCAL) {
  11038. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11039. this.setPositionWithLocalVector(tempV3);
  11040. }
  11041. else {
  11042. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11043. }
  11044. };
  11045. /**
  11046. * Adds a rotation step to the mesh current rotation.
  11047. * x, y, z are Euler angles expressed in radians.
  11048. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11049. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11050. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11051. * ```javascript
  11052. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11053. * ```
  11054. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11055. * 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.
  11056. */
  11057. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11058. var rotationQuaternion;
  11059. if (this.rotationQuaternion) {
  11060. rotationQuaternion = this.rotationQuaternion;
  11061. }
  11062. else {
  11063. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11064. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11065. }
  11066. var accumulation = BABYLON.Tmp.Quaternion[0];
  11067. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11068. rotationQuaternion.multiplyInPlace(accumulation);
  11069. if (!this.rotationQuaternion) {
  11070. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11071. }
  11072. return this;
  11073. };
  11074. AbstractMesh.prototype.getAbsolutePosition = function () {
  11075. this.computeWorldMatrix();
  11076. return this._absolutePosition;
  11077. };
  11078. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11079. if (!absolutePosition) {
  11080. return;
  11081. }
  11082. var absolutePositionX;
  11083. var absolutePositionY;
  11084. var absolutePositionZ;
  11085. if (absolutePosition.x === undefined) {
  11086. if (arguments.length < 3) {
  11087. return;
  11088. }
  11089. absolutePositionX = arguments[0];
  11090. absolutePositionY = arguments[1];
  11091. absolutePositionZ = arguments[2];
  11092. }
  11093. else {
  11094. absolutePositionX = absolutePosition.x;
  11095. absolutePositionY = absolutePosition.y;
  11096. absolutePositionZ = absolutePosition.z;
  11097. }
  11098. if (this.parent) {
  11099. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11100. invertParentWorldMatrix.invert();
  11101. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11102. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11103. }
  11104. else {
  11105. this.position.x = absolutePositionX;
  11106. this.position.y = absolutePositionY;
  11107. this.position.z = absolutePositionZ;
  11108. }
  11109. };
  11110. // ================================== Point of View Movement =================================
  11111. /**
  11112. * Perform relative position change from the point of view of behind the front of the mesh.
  11113. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11114. * Supports definition of mesh facing forward or backward.
  11115. * @param {number} amountRight
  11116. * @param {number} amountUp
  11117. * @param {number} amountForward
  11118. */
  11119. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11120. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11121. };
  11122. /**
  11123. * Calculate relative position change from the point of view of behind the front of the mesh.
  11124. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11125. * Supports definition of mesh facing forward or backward.
  11126. * @param {number} amountRight
  11127. * @param {number} amountUp
  11128. * @param {number} amountForward
  11129. */
  11130. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11131. var rotMatrix = new BABYLON.Matrix();
  11132. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11133. rotQuaternion.toRotationMatrix(rotMatrix);
  11134. var translationDelta = BABYLON.Vector3.Zero();
  11135. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11137. return translationDelta;
  11138. };
  11139. // ================================== Point of View Rotation =================================
  11140. /**
  11141. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11142. * Supports definition of mesh facing forward or backward.
  11143. * @param {number} flipBack
  11144. * @param {number} twirlClockwise
  11145. * @param {number} tiltRight
  11146. */
  11147. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11148. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11149. };
  11150. /**
  11151. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11152. * Supports definition of mesh facing forward or backward.
  11153. * @param {number} flipBack
  11154. * @param {number} twirlClockwise
  11155. * @param {number} tiltRight
  11156. */
  11157. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11158. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11159. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11160. };
  11161. /**
  11162. * Sets a new pivot matrix to the mesh.
  11163. * Returns nothing.
  11164. */
  11165. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11166. this._pivotMatrix = matrix;
  11167. this._cache.pivotMatrixUpdated = true;
  11168. };
  11169. /**
  11170. * Returns the mesh pivot matrix.
  11171. * Default : Identity.
  11172. * A Matrix is returned.
  11173. */
  11174. AbstractMesh.prototype.getPivotMatrix = function () {
  11175. return this._pivotMatrix;
  11176. };
  11177. AbstractMesh.prototype._isSynchronized = function () {
  11178. if (this._isDirty) {
  11179. return false;
  11180. }
  11181. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11182. return false;
  11183. if (this._cache.pivotMatrixUpdated) {
  11184. return false;
  11185. }
  11186. if (this.infiniteDistance) {
  11187. return false;
  11188. }
  11189. if (!this._cache.position.equals(this.position))
  11190. return false;
  11191. if (this.rotationQuaternion) {
  11192. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11193. return false;
  11194. }
  11195. if (!this._cache.rotation.equals(this.rotation))
  11196. return false;
  11197. if (!this._cache.scaling.equals(this.scaling))
  11198. return false;
  11199. return true;
  11200. };
  11201. AbstractMesh.prototype._initCache = function () {
  11202. _super.prototype._initCache.call(this);
  11203. this._cache.localMatrixUpdated = false;
  11204. this._cache.position = BABYLON.Vector3.Zero();
  11205. this._cache.scaling = BABYLON.Vector3.Zero();
  11206. this._cache.rotation = BABYLON.Vector3.Zero();
  11207. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11208. this._cache.billboardMode = -1;
  11209. };
  11210. AbstractMesh.prototype.markAsDirty = function (property) {
  11211. if (property === "rotation") {
  11212. this.rotationQuaternion = null;
  11213. }
  11214. this._currentRenderId = Number.MAX_VALUE;
  11215. this._isDirty = true;
  11216. };
  11217. AbstractMesh.prototype._updateBoundingInfo = function () {
  11218. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11219. this._boundingInfo.update(this.worldMatrixFromCache);
  11220. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11221. };
  11222. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11223. if (!this.subMeshes) {
  11224. return;
  11225. }
  11226. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11227. var subMesh = this.subMeshes[subIndex];
  11228. if (!subMesh.IsGlobal) {
  11229. subMesh.updateBoundingInfo(matrix);
  11230. }
  11231. }
  11232. };
  11233. /**
  11234. * Computes the mesh World matrix and returns it.
  11235. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11236. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11237. * If the parameter `force`is set to `true`, the actual computation is done.
  11238. * Returns the mesh World Matrix.
  11239. */
  11240. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11241. if (this._isWorldMatrixFrozen) {
  11242. return this._worldMatrix;
  11243. }
  11244. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  11245. this._currentRenderId = this.getScene().getRenderId();
  11246. return this._worldMatrix;
  11247. }
  11248. this._cache.position.copyFrom(this.position);
  11249. this._cache.scaling.copyFrom(this.scaling);
  11250. this._cache.pivotMatrixUpdated = false;
  11251. this._cache.billboardMode = this.billboardMode;
  11252. this._currentRenderId = this.getScene().getRenderId();
  11253. this._isDirty = false;
  11254. // Scaling
  11255. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11256. // Rotation
  11257. //rotate, if quaternion is set and rotation was used
  11258. if (this.rotationQuaternion) {
  11259. var len = this.rotation.length();
  11260. if (len) {
  11261. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11262. this.rotation.copyFromFloats(0, 0, 0);
  11263. }
  11264. }
  11265. if (this.rotationQuaternion) {
  11266. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11267. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11268. }
  11269. else {
  11270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11271. this._cache.rotation.copyFrom(this.rotation);
  11272. }
  11273. // Translation
  11274. if (this.infiniteDistance && !this.parent) {
  11275. var camera = this.getScene().activeCamera;
  11276. if (camera) {
  11277. var cameraWorldMatrix = camera.getWorldMatrix();
  11278. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11279. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11280. }
  11281. }
  11282. else {
  11283. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11284. }
  11285. // Composing transformations
  11286. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11287. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11288. // Billboarding
  11289. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11290. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  11291. var localPosition = BABYLON.Tmp.Vector3[0];
  11292. if (this.parent && this.parent.getWorldMatrix) {
  11293. this._markSyncedWithParent();
  11294. var parentMatrix;
  11295. if (this._meshToBoneReferal) {
  11296. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11297. parentMatrix = BABYLON.Tmp.Matrix[6];
  11298. }
  11299. else {
  11300. parentMatrix = this.parent.getWorldMatrix();
  11301. }
  11302. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  11303. localPosition = BABYLON.Tmp.Vector3[1];
  11304. }
  11305. var zero = this.getScene().activeCamera.globalPosition.clone();
  11306. if (this.parent && this.parent.position) {
  11307. localPosition.addInPlace(this.parent.position);
  11308. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  11309. }
  11310. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11311. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  11312. zero.x = localPosition.x + BABYLON.Epsilon;
  11313. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  11314. zero.y = localPosition.y + BABYLON.Epsilon;
  11315. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  11316. zero.z = localPosition.z + BABYLON.Epsilon;
  11317. }
  11318. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  11319. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  11320. BABYLON.Tmp.Matrix[3].invert();
  11321. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  11322. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  11323. }
  11324. // Local world
  11325. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11326. // Parent
  11327. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  11328. this._markSyncedWithParent();
  11329. if (this._meshToBoneReferal) {
  11330. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11331. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11332. }
  11333. else {
  11334. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11335. }
  11336. }
  11337. else {
  11338. this._worldMatrix.copyFrom(this._localWorld);
  11339. }
  11340. // Bounding info
  11341. this._updateBoundingInfo();
  11342. // Absolute position
  11343. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11344. // Callbacks
  11345. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11346. if (!this._poseMatrix) {
  11347. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11348. }
  11349. return this._worldMatrix;
  11350. };
  11351. /**
  11352. * If you'd like to be called back after the mesh position, rotation or scaling has been updated
  11353. * @param func: callback function to add
  11354. */
  11355. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11356. this.onAfterWorldMatrixUpdateObservable.add(func);
  11357. };
  11358. /**
  11359. * Removes a registered callback function
  11360. */
  11361. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11362. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11363. };
  11364. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11365. this.computeWorldMatrix();
  11366. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11367. };
  11368. /**
  11369. * Returns the mesh position in the local space from the current World matrix values.
  11370. * Returns a new Vector3.
  11371. */
  11372. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11373. this.computeWorldMatrix();
  11374. var invLocalWorldMatrix = this._localWorld.clone();
  11375. invLocalWorldMatrix.invert();
  11376. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11377. };
  11378. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11379. this.computeWorldMatrix(true);
  11380. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11381. };
  11382. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11383. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11384. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11385. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11386. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11387. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11388. /// <returns>Mesh oriented towards targetMesh</returns>
  11389. if (yawCor === void 0) { yawCor = 0; }
  11390. if (pitchCor === void 0) { pitchCor = 0; }
  11391. if (rollCor === void 0) { rollCor = 0; }
  11392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11393. var dv = AbstractMesh._lookAtVectorCache;
  11394. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11395. targetPoint.subtractToRef(pos, dv);
  11396. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11397. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11398. var pitch = Math.atan2(dv.y, len);
  11399. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11400. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11401. };
  11402. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11403. this._meshToBoneReferal = affectedMesh;
  11404. this.parent = bone;
  11405. if (bone.getWorldMatrix().determinant() < 0) {
  11406. this.scalingDeterminant *= -1;
  11407. }
  11408. };
  11409. AbstractMesh.prototype.detachFromBone = function () {
  11410. if (this.parent.getWorldMatrix().determinant() < 0) {
  11411. this.scalingDeterminant *= -1;
  11412. }
  11413. this._meshToBoneReferal = null;
  11414. this.parent = null;
  11415. };
  11416. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11417. return this._boundingInfo.isInFrustum(frustumPlanes);
  11418. };
  11419. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11420. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11421. ;
  11422. };
  11423. /**
  11424. * True if the mesh intersects another mesh or a SolidParticle object.
  11425. * 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)
  11426. * Returns a boolean.
  11427. */
  11428. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11429. if (!this._boundingInfo || !mesh._boundingInfo) {
  11430. return false;
  11431. }
  11432. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11433. };
  11434. /**
  11435. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11436. * Returns a boolean.
  11437. */
  11438. AbstractMesh.prototype.intersectsPoint = function (point) {
  11439. if (!this._boundingInfo) {
  11440. return false;
  11441. }
  11442. return this._boundingInfo.intersectsPoint(point);
  11443. };
  11444. // Physics
  11445. /**
  11446. * @Deprecated. Use new PhysicsImpostor instead.
  11447. * */
  11448. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11449. //legacy support
  11450. if (impostor.impostor) {
  11451. options = impostor;
  11452. impostor = impostor.impostor;
  11453. }
  11454. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11455. return this.physicsImpostor.physicsBody;
  11456. };
  11457. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11458. return this.physicsImpostor;
  11459. };
  11460. /**
  11461. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11462. */
  11463. AbstractMesh.prototype.getPhysicsMass = function () {
  11464. return this.physicsImpostor.getParam("mass");
  11465. };
  11466. /**
  11467. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11468. */
  11469. AbstractMesh.prototype.getPhysicsFriction = function () {
  11470. return this.physicsImpostor.getParam("friction");
  11471. };
  11472. /**
  11473. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11474. */
  11475. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11476. return this.physicsImpostor.getParam("restitution");
  11477. };
  11478. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11479. if (!camera) {
  11480. camera = this.getScene().activeCamera;
  11481. }
  11482. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11483. };
  11484. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11485. if (!camera) {
  11486. camera = this.getScene().activeCamera;
  11487. }
  11488. return this.absolutePosition.subtract(camera.position).length();
  11489. };
  11490. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11491. if (!this.physicsImpostor) {
  11492. return;
  11493. }
  11494. this.physicsImpostor.applyImpulse(force, contactPoint);
  11495. };
  11496. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11497. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11498. return;
  11499. }
  11500. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11501. mainPivot: pivot1,
  11502. connectedPivot: pivot2,
  11503. nativeParams: options
  11504. });
  11505. };
  11506. /**
  11507. * @Deprecated
  11508. */
  11509. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11510. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11511. this.updatePhysicsBody();
  11512. };
  11513. /**
  11514. * @Deprecated
  11515. * Calling this function is not needed anymore.
  11516. * The physics engine takes care of transofmration automatically.
  11517. */
  11518. AbstractMesh.prototype.updatePhysicsBody = function () {
  11519. //Unneeded
  11520. };
  11521. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11522. // Collisions
  11523. get: function () {
  11524. return this._checkCollisions;
  11525. },
  11526. set: function (collisionEnabled) {
  11527. this._checkCollisions = collisionEnabled;
  11528. if (this.getScene().workerCollisions) {
  11529. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11530. }
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11536. var globalPosition = this.getAbsolutePosition();
  11537. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11538. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11539. this._collider.radius = this.ellipsoid;
  11540. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11541. };
  11542. // Submeshes octree
  11543. /**
  11544. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11545. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11546. */
  11547. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11548. if (maxCapacity === void 0) { maxCapacity = 64; }
  11549. if (maxDepth === void 0) { maxDepth = 2; }
  11550. if (!this._submeshesOctree) {
  11551. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11552. }
  11553. this.computeWorldMatrix(true);
  11554. // Update octree
  11555. var bbox = this.getBoundingInfo().boundingBox;
  11556. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11557. return this._submeshesOctree;
  11558. };
  11559. // Collisions
  11560. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11561. this._generatePointsArray();
  11562. // Transformation
  11563. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11564. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11565. subMesh._lastColliderWorldVertices = [];
  11566. subMesh._trianglePlanes = [];
  11567. var start = subMesh.verticesStart;
  11568. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11569. for (var i = start; i < end; i++) {
  11570. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11571. }
  11572. }
  11573. // Collide
  11574. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11575. if (collider.collisionFound) {
  11576. collider.collidedMesh = this;
  11577. }
  11578. };
  11579. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11580. var subMeshes;
  11581. var len;
  11582. // Octrees
  11583. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11584. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11585. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11586. len = intersections.length;
  11587. subMeshes = intersections.data;
  11588. }
  11589. else {
  11590. subMeshes = this.subMeshes;
  11591. len = subMeshes.length;
  11592. }
  11593. for (var index = 0; index < len; index++) {
  11594. var subMesh = subMeshes[index];
  11595. // Bounding test
  11596. if (len > 1 && !subMesh._checkCollision(collider))
  11597. continue;
  11598. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11599. }
  11600. };
  11601. AbstractMesh.prototype._checkCollision = function (collider) {
  11602. // Bounding box test
  11603. if (!this._boundingInfo._checkCollision(collider))
  11604. return;
  11605. // Transformation matrix
  11606. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11607. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11608. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11609. };
  11610. // Picking
  11611. AbstractMesh.prototype._generatePointsArray = function () {
  11612. return false;
  11613. };
  11614. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11615. var pickingInfo = new BABYLON.PickingInfo();
  11616. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11617. return pickingInfo;
  11618. }
  11619. if (!this._generatePointsArray()) {
  11620. return pickingInfo;
  11621. }
  11622. var intersectInfo = null;
  11623. // Octrees
  11624. var subMeshes;
  11625. var len;
  11626. if (this._submeshesOctree && this.useOctreeForPicking) {
  11627. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11628. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11629. len = intersections.length;
  11630. subMeshes = intersections.data;
  11631. }
  11632. else {
  11633. subMeshes = this.subMeshes;
  11634. len = subMeshes.length;
  11635. }
  11636. for (var index = 0; index < len; index++) {
  11637. var subMesh = subMeshes[index];
  11638. // Bounding test
  11639. if (len > 1 && !subMesh.canIntersects(ray))
  11640. continue;
  11641. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11642. if (currentIntersectInfo) {
  11643. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11644. intersectInfo = currentIntersectInfo;
  11645. intersectInfo.subMeshId = index;
  11646. if (fastCheck) {
  11647. break;
  11648. }
  11649. }
  11650. }
  11651. }
  11652. if (intersectInfo) {
  11653. // Get picked point
  11654. var world = this.getWorldMatrix();
  11655. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11656. var direction = ray.direction.clone();
  11657. direction = direction.scale(intersectInfo.distance);
  11658. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11659. var pickedPoint = worldOrigin.add(worldDirection);
  11660. // Return result
  11661. pickingInfo.hit = true;
  11662. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11663. pickingInfo.pickedPoint = pickedPoint;
  11664. pickingInfo.pickedMesh = this;
  11665. pickingInfo.bu = intersectInfo.bu;
  11666. pickingInfo.bv = intersectInfo.bv;
  11667. pickingInfo.faceId = intersectInfo.faceId;
  11668. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11669. return pickingInfo;
  11670. }
  11671. return pickingInfo;
  11672. };
  11673. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11674. return null;
  11675. };
  11676. AbstractMesh.prototype.releaseSubMeshes = function () {
  11677. if (this.subMeshes) {
  11678. while (this.subMeshes.length) {
  11679. this.subMeshes[0].dispose();
  11680. }
  11681. }
  11682. else {
  11683. this.subMeshes = new Array();
  11684. }
  11685. };
  11686. /**
  11687. * Disposes the AbstractMesh.
  11688. * Some internal references are kept for further use.
  11689. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  11690. * Returns nothing.
  11691. */
  11692. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11693. var _this = this;
  11694. var index;
  11695. // Action manager
  11696. if (this.actionManager) {
  11697. this.actionManager.dispose();
  11698. this.actionManager = null;
  11699. }
  11700. // Skeleton
  11701. this.skeleton = null;
  11702. // Animations
  11703. this.getScene().stopAnimation(this);
  11704. // Physics
  11705. if (this.physicsImpostor) {
  11706. this.physicsImpostor.dispose();
  11707. }
  11708. // Intersections in progress
  11709. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11710. var other = this._intersectionsInProgress[index];
  11711. var pos = other._intersectionsInProgress.indexOf(this);
  11712. other._intersectionsInProgress.splice(pos, 1);
  11713. }
  11714. this._intersectionsInProgress = [];
  11715. // Lights
  11716. var lights = this.getScene().lights;
  11717. lights.forEach(function (light) {
  11718. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11719. if (meshIndex !== -1) {
  11720. light.includedOnlyMeshes.splice(meshIndex, 1);
  11721. }
  11722. meshIndex = light.excludedMeshes.indexOf(_this);
  11723. if (meshIndex !== -1) {
  11724. light.excludedMeshes.splice(meshIndex, 1);
  11725. }
  11726. // Shadow generators
  11727. var generator = light.getShadowGenerator();
  11728. if (generator) {
  11729. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11730. if (meshIndex !== -1) {
  11731. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11732. }
  11733. }
  11734. });
  11735. // Edges
  11736. if (this._edgesRenderer) {
  11737. this._edgesRenderer.dispose();
  11738. this._edgesRenderer = null;
  11739. }
  11740. // SubMeshes
  11741. if (this.getClassName() !== "InstancedMesh") {
  11742. this.releaseSubMeshes();
  11743. }
  11744. // Engine
  11745. this.getScene().getEngine().wipeCaches();
  11746. // Remove from scene
  11747. this.getScene().removeMesh(this);
  11748. if (!doNotRecurse) {
  11749. // Particles
  11750. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11751. if (this.getScene().particleSystems[index].emitter === this) {
  11752. this.getScene().particleSystems[index].dispose();
  11753. index--;
  11754. }
  11755. }
  11756. // Children
  11757. var objects = this.getDescendants(true);
  11758. for (index = 0; index < objects.length; index++) {
  11759. objects[index].dispose();
  11760. }
  11761. }
  11762. else {
  11763. var childMeshes = this.getChildMeshes(true);
  11764. for (index = 0; index < childMeshes.length; index++) {
  11765. var child = childMeshes[index];
  11766. child.parent = null;
  11767. child.computeWorldMatrix(true);
  11768. }
  11769. }
  11770. // facet data
  11771. if (this._facetDataEnabled) {
  11772. this.disableFacetData();
  11773. }
  11774. this.onAfterWorldMatrixUpdateObservable.clear();
  11775. this.onCollideObservable.clear();
  11776. this.onCollisionPositionChangeObservable.clear();
  11777. this._isDisposed = true;
  11778. _super.prototype.dispose.call(this);
  11779. };
  11780. AbstractMesh.prototype.getDirection = function (localAxis) {
  11781. var result = BABYLON.Vector3.Zero();
  11782. this.getDirectionToRef(localAxis, result);
  11783. return result;
  11784. };
  11785. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11786. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11787. };
  11788. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11789. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11790. if (this.getScene().getRenderId() == 0) {
  11791. this.computeWorldMatrix(true);
  11792. }
  11793. var wm = this.getWorldMatrix();
  11794. if (space == BABYLON.Space.WORLD) {
  11795. var tmat = BABYLON.Tmp.Matrix[0];
  11796. wm.invertToRef(tmat);
  11797. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11798. }
  11799. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11800. this._pivotMatrix.m[12] = -point.x;
  11801. this._pivotMatrix.m[13] = -point.y;
  11802. this._pivotMatrix.m[14] = -point.z;
  11803. this._cache.pivotMatrixUpdated = true;
  11804. };
  11805. AbstractMesh.prototype.getPivotPoint = function () {
  11806. var point = BABYLON.Vector3.Zero();
  11807. this.getPivotPointToRef(point);
  11808. return point;
  11809. };
  11810. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11811. result.x = -this._pivotMatrix.m[12];
  11812. result.y = -this._pivotMatrix.m[13];
  11813. result.z = -this._pivotMatrix.m[14];
  11814. };
  11815. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11816. var point = BABYLON.Vector3.Zero();
  11817. this.getAbsolutePivotPointToRef(point);
  11818. return point;
  11819. };
  11820. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  11821. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11822. var child = this;
  11823. var parent = mesh;
  11824. if (mesh == null) {
  11825. if (child.parent && keepWorldPositionRotation) {
  11826. var rotation = BABYLON.Tmp.Quaternion[0];
  11827. var position = BABYLON.Tmp.Vector3[0];
  11828. var scale = BABYLON.Tmp.Vector3[1];
  11829. child.getWorldMatrix().decompose(scale, rotation, position);
  11830. if (child.rotationQuaternion) {
  11831. child.rotationQuaternion.copyFrom(rotation);
  11832. }
  11833. else {
  11834. rotation.toEulerAnglesToRef(child.rotation);
  11835. }
  11836. child.position.x = position.x;
  11837. child.position.y = position.y;
  11838. child.position.z = position.z;
  11839. }
  11840. }
  11841. else {
  11842. if (keepWorldPositionRotation) {
  11843. var rotation = BABYLON.Tmp.Quaternion[0];
  11844. var position = BABYLON.Tmp.Vector3[0];
  11845. var scale = BABYLON.Tmp.Vector3[1];
  11846. var m1 = BABYLON.Tmp.Matrix[0];
  11847. var m2 = BABYLON.Tmp.Matrix[1];
  11848. parent.getWorldMatrix().decompose(scale, rotation, position);
  11849. rotation.toRotationMatrix(m1);
  11850. m2.setTranslation(position);
  11851. m2.multiplyToRef(m1, m1);
  11852. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  11853. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11854. m.decompose(scale, rotation, position);
  11855. if (child.rotationQuaternion) {
  11856. child.rotationQuaternion.copyFrom(rotation);
  11857. }
  11858. else {
  11859. rotation.toEulerAnglesToRef(child.rotation);
  11860. }
  11861. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  11862. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11863. m.decompose(scale, rotation, position);
  11864. child.position.x = position.x;
  11865. child.position.y = position.y;
  11866. child.position.z = position.z;
  11867. }
  11868. }
  11869. child.parent = parent;
  11870. };
  11871. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  11872. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11873. mesh.setParent(this, keepWorldPositionRotation);
  11874. };
  11875. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  11876. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11877. mesh.setParent(null, keepWorldPositionRotation);
  11878. };
  11879. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11880. result.x = this._pivotMatrix.m[12];
  11881. result.y = this._pivotMatrix.m[13];
  11882. result.z = this._pivotMatrix.m[14];
  11883. this.getPivotPointToRef(result);
  11884. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11885. };
  11886. // Facet data
  11887. /**
  11888. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  11889. */
  11890. AbstractMesh.prototype._initFacetData = function () {
  11891. if (!this._facetNormals) {
  11892. this._facetNormals = new Array();
  11893. }
  11894. if (!this._facetPositions) {
  11895. this._facetPositions = new Array();
  11896. }
  11897. if (!this._facetPartitioning) {
  11898. this._facetPartitioning = new Array();
  11899. }
  11900. this._facetNb = this.getIndices().length / 3;
  11901. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  11902. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  11903. for (var f = 0; f < this._facetNb; f++) {
  11904. this._facetNormals[f] = BABYLON.Vector3.Zero();
  11905. this._facetPositions[f] = BABYLON.Vector3.Zero();
  11906. }
  11907. this._facetDataEnabled = true;
  11908. return this;
  11909. };
  11910. /**
  11911. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  11912. * This method can be called within the render loop.
  11913. * 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.
  11914. */
  11915. AbstractMesh.prototype.updateFacetData = function () {
  11916. if (!this._facetDataEnabled) {
  11917. this._initFacetData();
  11918. }
  11919. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11920. var indices = this.getIndices();
  11921. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11922. var bInfo = this.getBoundingInfo();
  11923. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  11924. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  11925. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  11926. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  11927. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  11928. this._subDiv.max = this._partitioningSubdivisions;
  11929. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  11930. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  11931. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  11932. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  11933. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  11934. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  11935. // set the parameters for ComputeNormals()
  11936. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  11937. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  11938. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  11939. this._facetParameters.bInfo = bInfo;
  11940. this._facetParameters.bbSize = this._bbSize;
  11941. this._facetParameters.subDiv = this._subDiv;
  11942. this._facetParameters.ratio = this.partitioningBBoxRatio;
  11943. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  11944. return this;
  11945. };
  11946. /**
  11947. * Returns the facetLocalNormals array.
  11948. * The normals are expressed in the mesh local space.
  11949. */
  11950. AbstractMesh.prototype.getFacetLocalNormals = function () {
  11951. if (!this._facetNormals) {
  11952. this.updateFacetData();
  11953. }
  11954. return this._facetNormals;
  11955. };
  11956. /**
  11957. * Returns the facetLocalPositions array.
  11958. * The facet positions are expressed in the mesh local space.
  11959. */
  11960. AbstractMesh.prototype.getFacetLocalPositions = function () {
  11961. if (!this._facetPositions) {
  11962. this.updateFacetData();
  11963. }
  11964. return this._facetPositions;
  11965. };
  11966. /**
  11967. * Returns the facetLocalPartioning array
  11968. */
  11969. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  11970. if (!this._facetPartitioning) {
  11971. this.updateFacetData();
  11972. }
  11973. return this._facetPartitioning;
  11974. };
  11975. /**
  11976. * Returns the i-th facet position in the world system.
  11977. * This method allocates a new Vector3 per call.
  11978. */
  11979. AbstractMesh.prototype.getFacetPosition = function (i) {
  11980. var pos = BABYLON.Vector3.Zero();
  11981. this.getFacetPositionToRef(i, pos);
  11982. return pos;
  11983. };
  11984. /**
  11985. * Sets the reference Vector3 with the i-th facet position in the world system.
  11986. * Returns the mesh.
  11987. */
  11988. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  11989. var localPos = (this.getFacetLocalPositions())[i];
  11990. var world = this.getWorldMatrix();
  11991. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  11992. return this;
  11993. };
  11994. /**
  11995. * Returns the i-th facet normal in the world system.
  11996. * This method allocates a new Vector3 per call.
  11997. */
  11998. AbstractMesh.prototype.getFacetNormal = function (i) {
  11999. var norm = BABYLON.Vector3.Zero();
  12000. this.getFacetNormalToRef(i, norm);
  12001. return norm;
  12002. };
  12003. /**
  12004. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12005. * Returns the mesh.
  12006. */
  12007. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12008. var localNorm = (this.getFacetLocalNormals())[i];
  12009. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12010. return this;
  12011. };
  12012. /**
  12013. * 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).
  12014. */
  12015. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12016. var bInfo = this.getBoundingInfo();
  12017. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12018. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12019. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12020. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12021. return null;
  12022. }
  12023. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12024. };
  12025. /**
  12026. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12027. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12028. * 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.
  12029. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12030. * 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.
  12031. */
  12032. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12033. if (checkFace === void 0) { checkFace = false; }
  12034. if (facing === void 0) { facing = true; }
  12035. var world = this.getWorldMatrix();
  12036. var invMat = BABYLON.Tmp.Matrix[5];
  12037. world.invertToRef(invMat);
  12038. var invVect = BABYLON.Tmp.Vector3[8];
  12039. var closest = null;
  12040. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12041. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12042. if (projected) {
  12043. // tranform the local computed projected vector to world coordinates
  12044. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12045. }
  12046. return closest;
  12047. };
  12048. /**
  12049. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12050. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12051. * 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.
  12052. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12053. * 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.
  12054. */
  12055. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12056. if (checkFace === void 0) { checkFace = false; }
  12057. if (facing === void 0) { facing = true; }
  12058. var closest = null;
  12059. var tmpx = 0.0;
  12060. var tmpy = 0.0;
  12061. var tmpz = 0.0;
  12062. var d = 0.0; // tmp dot facet normal * facet position
  12063. var t0 = 0.0;
  12064. var projx = 0.0;
  12065. var projy = 0.0;
  12066. var projz = 0.0;
  12067. // Get all the facets in the same partitioning block than (x, y, z)
  12068. var facetPositions = this.getFacetLocalPositions();
  12069. var facetNormals = this.getFacetLocalNormals();
  12070. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12071. if (!facetsInBlock) {
  12072. return null;
  12073. }
  12074. // Get the closest facet to (x, y, z)
  12075. var shortest = Number.MAX_VALUE; // init distance vars
  12076. var tmpDistance = shortest;
  12077. var fib; // current facet in the block
  12078. var norm; // current facet normal
  12079. var p0; // current facet barycenter position
  12080. // loop on all the facets in the current partitioning block
  12081. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12082. fib = facetsInBlock[idx];
  12083. norm = facetNormals[fib];
  12084. p0 = facetPositions[fib];
  12085. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12086. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12087. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12088. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12089. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12090. projx = x + norm.x * t0;
  12091. projy = y + norm.y * t0;
  12092. projz = z + norm.z * t0;
  12093. tmpx = projx - x;
  12094. tmpy = projy - y;
  12095. tmpz = projz - z;
  12096. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12097. if (tmpDistance < shortest) {
  12098. shortest = tmpDistance;
  12099. closest = fib;
  12100. if (projected) {
  12101. projected.x = projx;
  12102. projected.y = projy;
  12103. projected.z = projz;
  12104. }
  12105. }
  12106. }
  12107. }
  12108. return closest;
  12109. };
  12110. /**
  12111. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12112. */
  12113. AbstractMesh.prototype.getFacetDataParameters = function () {
  12114. return this._facetParameters;
  12115. };
  12116. /**
  12117. * Disables the feature FacetData and frees the related memory.
  12118. * Returns the mesh.
  12119. */
  12120. AbstractMesh.prototype.disableFacetData = function () {
  12121. if (this._facetDataEnabled) {
  12122. this._facetDataEnabled = false;
  12123. this._facetPositions = null;
  12124. this._facetNormals = null;
  12125. this._facetPartitioning = null;
  12126. this._facetParameters = null;
  12127. }
  12128. return this;
  12129. };
  12130. return AbstractMesh;
  12131. }(BABYLON.Node));
  12132. // Statics
  12133. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12134. AbstractMesh._BILLBOARDMODE_X = 1;
  12135. AbstractMesh._BILLBOARDMODE_Y = 2;
  12136. AbstractMesh._BILLBOARDMODE_Z = 4;
  12137. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12138. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12139. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12140. BABYLON.AbstractMesh = AbstractMesh;
  12141. })(BABYLON || (BABYLON = {}));
  12142. //# sourceMappingURL=babylon.abstractMesh.js.map
  12143. var BABYLON;
  12144. (function (BABYLON) {
  12145. var Light = (function (_super) {
  12146. __extends(Light, _super);
  12147. function Light(name, scene) {
  12148. var _this = _super.call(this, name, scene) || this;
  12149. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12150. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12151. _this.intensity = 1.0;
  12152. _this.range = Number.MAX_VALUE;
  12153. _this.includeOnlyWithLayerMask = 0;
  12154. _this.includedOnlyMeshes = new Array();
  12155. _this.excludedMeshes = new Array();
  12156. _this.excludeWithLayerMask = 0;
  12157. _this.lightmapMode = 0;
  12158. // PBR Properties.
  12159. _this.radius = 0.00001;
  12160. _this._excludedMeshesIds = new Array();
  12161. _this._includedOnlyMeshesIds = new Array();
  12162. scene.addLight(_this);
  12163. return _this;
  12164. }
  12165. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12166. /**
  12167. * If every light affecting the material is in this lightmapMode,
  12168. * material.lightmapTexture adds or multiplies
  12169. * (depends on material.useLightmapAsShadowmap)
  12170. * after every other light calculations.
  12171. */
  12172. get: function () {
  12173. return Light._LIGHTMAP_DEFAULT;
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12179. /**
  12180. * material.lightmapTexture as only diffuse lighting from this light
  12181. * adds pnly specular lighting from this light
  12182. * adds dynamic shadows
  12183. */
  12184. get: function () {
  12185. return Light._LIGHTMAP_SPECULAR;
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12191. /**
  12192. * material.lightmapTexture as only lighting
  12193. * no light calculation from this light
  12194. * only adds dynamic shadows from this light
  12195. */
  12196. get: function () {
  12197. return Light._LIGHTMAP_SHADOWSONLY;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Light.prototype.getClassName = function () {
  12203. return "Light";
  12204. };
  12205. /**
  12206. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12207. */
  12208. Light.prototype.toString = function (fullDetails) {
  12209. var ret = "Name: " + this.name;
  12210. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12211. if (this.animations) {
  12212. for (var i = 0; i < this.animations.length; i++) {
  12213. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12214. }
  12215. }
  12216. if (fullDetails) {
  12217. }
  12218. return ret;
  12219. };
  12220. Light.prototype.getShadowGenerator = function () {
  12221. return this._shadowGenerator;
  12222. };
  12223. Light.prototype.getAbsolutePosition = function () {
  12224. return BABYLON.Vector3.Zero();
  12225. };
  12226. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12227. };
  12228. Light.prototype._getWorldMatrix = function () {
  12229. return BABYLON.Matrix.Identity();
  12230. };
  12231. Light.prototype.canAffectMesh = function (mesh) {
  12232. if (!mesh) {
  12233. return true;
  12234. }
  12235. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12236. return false;
  12237. }
  12238. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12239. return false;
  12240. }
  12241. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12242. return false;
  12243. }
  12244. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12245. return false;
  12246. }
  12247. return true;
  12248. };
  12249. Light.prototype.getWorldMatrix = function () {
  12250. this._currentRenderId = this.getScene().getRenderId();
  12251. var worldMatrix = this._getWorldMatrix();
  12252. if (this.parent && this.parent.getWorldMatrix) {
  12253. if (!this._parentedWorldMatrix) {
  12254. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12255. }
  12256. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12257. this._markSyncedWithParent();
  12258. return this._parentedWorldMatrix;
  12259. }
  12260. return worldMatrix;
  12261. };
  12262. Light.prototype.dispose = function () {
  12263. if (this._shadowGenerator) {
  12264. this._shadowGenerator.dispose();
  12265. this._shadowGenerator = null;
  12266. }
  12267. // Animations
  12268. this.getScene().stopAnimation(this);
  12269. // Remove from scene
  12270. this.getScene().removeLight(this);
  12271. _super.prototype.dispose.call(this);
  12272. };
  12273. Light.prototype.getTypeID = function () {
  12274. return 0;
  12275. };
  12276. Light.prototype.clone = function (name) {
  12277. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12278. };
  12279. Light.prototype.serialize = function () {
  12280. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12281. // Type
  12282. serializationObject.type = this.getTypeID();
  12283. // Parent
  12284. if (this.parent) {
  12285. serializationObject.parentId = this.parent.id;
  12286. }
  12287. // Inclusion / exclusions
  12288. if (this.excludedMeshes.length > 0) {
  12289. serializationObject.excludedMeshesIds = [];
  12290. this.excludedMeshes.forEach(function (mesh) {
  12291. serializationObject.excludedMeshesIds.push(mesh.id);
  12292. });
  12293. }
  12294. if (this.includedOnlyMeshes.length > 0) {
  12295. serializationObject.includedOnlyMeshesIds = [];
  12296. this.includedOnlyMeshes.forEach(function (mesh) {
  12297. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12298. });
  12299. }
  12300. // Animations
  12301. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12302. serializationObject.ranges = this.serializeAnimationRanges();
  12303. return serializationObject;
  12304. };
  12305. Light.GetConstructorFromName = function (type, name, scene) {
  12306. switch (type) {
  12307. case 0:
  12308. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12309. case 1:
  12310. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12311. case 2:
  12312. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12313. case 3:
  12314. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12315. }
  12316. };
  12317. Light.Parse = function (parsedLight, scene) {
  12318. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12319. // Inclusion / exclusions
  12320. if (parsedLight.excludedMeshesIds) {
  12321. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12322. }
  12323. if (parsedLight.includedOnlyMeshesIds) {
  12324. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12325. }
  12326. // Parent
  12327. if (parsedLight.parentId) {
  12328. light._waitingParentId = parsedLight.parentId;
  12329. }
  12330. // Animations
  12331. if (parsedLight.animations) {
  12332. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12333. var parsedAnimation = parsedLight.animations[animationIndex];
  12334. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12335. }
  12336. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12337. }
  12338. if (parsedLight.autoAnimate) {
  12339. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12340. }
  12341. return light;
  12342. };
  12343. return Light;
  12344. }(BABYLON.Node));
  12345. //lightmapMode Consts
  12346. Light._LIGHTMAP_DEFAULT = 0;
  12347. Light._LIGHTMAP_SPECULAR = 1;
  12348. Light._LIGHTMAP_SHADOWSONLY = 2;
  12349. __decorate([
  12350. BABYLON.serializeAsColor3()
  12351. ], Light.prototype, "diffuse", void 0);
  12352. __decorate([
  12353. BABYLON.serializeAsColor3()
  12354. ], Light.prototype, "specular", void 0);
  12355. __decorate([
  12356. BABYLON.serialize()
  12357. ], Light.prototype, "intensity", void 0);
  12358. __decorate([
  12359. BABYLON.serialize()
  12360. ], Light.prototype, "range", void 0);
  12361. __decorate([
  12362. BABYLON.serialize()
  12363. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  12364. __decorate([
  12365. BABYLON.serialize()
  12366. ], Light.prototype, "excludeWithLayerMask", void 0);
  12367. __decorate([
  12368. BABYLON.serialize()
  12369. ], Light.prototype, "lightmapMode", void 0);
  12370. __decorate([
  12371. BABYLON.serialize()
  12372. ], Light.prototype, "radius", void 0);
  12373. BABYLON.Light = Light;
  12374. })(BABYLON || (BABYLON = {}));
  12375. //# sourceMappingURL=babylon.light.js.map
  12376. var BABYLON;
  12377. (function (BABYLON) {
  12378. var PointLight = (function (_super) {
  12379. __extends(PointLight, _super);
  12380. function PointLight(name, position, scene) {
  12381. var _this = _super.call(this, name, scene) || this;
  12382. _this.position = position;
  12383. return _this;
  12384. }
  12385. PointLight.prototype.getClassName = function () {
  12386. return "PointLight";
  12387. };
  12388. PointLight.prototype.getAbsolutePosition = function () {
  12389. return this.transformedPosition ? this.transformedPosition : this.position;
  12390. };
  12391. PointLight.prototype.computeTransformedPosition = function () {
  12392. if (this.parent && this.parent.getWorldMatrix) {
  12393. if (!this.transformedPosition) {
  12394. this.transformedPosition = BABYLON.Vector3.Zero();
  12395. }
  12396. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12397. return true;
  12398. }
  12399. return false;
  12400. };
  12401. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  12402. if (this.parent && this.parent.getWorldMatrix) {
  12403. this.computeTransformedPosition();
  12404. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  12405. return;
  12406. }
  12407. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  12408. };
  12409. PointLight.prototype.needCube = function () {
  12410. return true;
  12411. };
  12412. PointLight.prototype.supportsVSM = function () {
  12413. return false;
  12414. };
  12415. PointLight.prototype.needRefreshPerFrame = function () {
  12416. return false;
  12417. };
  12418. PointLight.prototype.getShadowDirection = function (faceIndex) {
  12419. switch (faceIndex) {
  12420. case 0:
  12421. return new BABYLON.Vector3(1, 0, 0);
  12422. case 1:
  12423. return new BABYLON.Vector3(-1, 0, 0);
  12424. case 2:
  12425. return new BABYLON.Vector3(0, -1, 0);
  12426. case 3:
  12427. return new BABYLON.Vector3(0, 1, 0);
  12428. case 4:
  12429. return new BABYLON.Vector3(0, 0, 1);
  12430. case 5:
  12431. return new BABYLON.Vector3(0, 0, -1);
  12432. }
  12433. return BABYLON.Vector3.Zero();
  12434. };
  12435. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12436. var activeCamera = this.getScene().activeCamera;
  12437. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12438. };
  12439. PointLight.prototype._getWorldMatrix = function () {
  12440. if (!this._worldMatrix) {
  12441. this._worldMatrix = BABYLON.Matrix.Identity();
  12442. }
  12443. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12444. return this._worldMatrix;
  12445. };
  12446. PointLight.prototype.getTypeID = function () {
  12447. return 0;
  12448. };
  12449. return PointLight;
  12450. }(BABYLON.Light));
  12451. __decorate([
  12452. BABYLON.serializeAsVector3()
  12453. ], PointLight.prototype, "position", void 0);
  12454. BABYLON.PointLight = PointLight;
  12455. })(BABYLON || (BABYLON = {}));
  12456. //# sourceMappingURL=babylon.pointLight.js.map
  12457. var BABYLON;
  12458. (function (BABYLON) {
  12459. var SpotLight = (function (_super) {
  12460. __extends(SpotLight, _super);
  12461. function SpotLight(name, position, direction, angle, exponent, scene) {
  12462. var _this = _super.call(this, name, scene) || this;
  12463. _this.position = position;
  12464. _this.direction = direction;
  12465. _this.angle = angle;
  12466. _this.exponent = exponent;
  12467. return _this;
  12468. }
  12469. SpotLight.prototype.getClassName = function () {
  12470. return "SpotLight";
  12471. };
  12472. SpotLight.prototype.getAbsolutePosition = function () {
  12473. return this.transformedPosition ? this.transformedPosition : this.position;
  12474. };
  12475. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12476. var activeCamera = this.getScene().activeCamera;
  12477. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12478. };
  12479. SpotLight.prototype.needCube = function () {
  12480. return false;
  12481. };
  12482. SpotLight.prototype.supportsVSM = function () {
  12483. return true;
  12484. };
  12485. SpotLight.prototype.needRefreshPerFrame = function () {
  12486. return false;
  12487. };
  12488. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  12489. return this.direction;
  12490. };
  12491. SpotLight.prototype.setDirectionToTarget = function (target) {
  12492. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12493. return this.direction;
  12494. };
  12495. SpotLight.prototype.computeTransformedPosition = function () {
  12496. if (this.parent && this.parent.getWorldMatrix) {
  12497. if (!this.transformedPosition) {
  12498. this.transformedPosition = BABYLON.Vector3.Zero();
  12499. }
  12500. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12501. return true;
  12502. }
  12503. return false;
  12504. };
  12505. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  12506. var normalizeDirection;
  12507. if (this.parent && this.parent.getWorldMatrix) {
  12508. if (!this._transformedDirection) {
  12509. this._transformedDirection = BABYLON.Vector3.Zero();
  12510. }
  12511. this.computeTransformedPosition();
  12512. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12513. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  12514. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  12515. }
  12516. else {
  12517. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  12518. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12519. }
  12520. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  12521. };
  12522. SpotLight.prototype._getWorldMatrix = function () {
  12523. if (!this._worldMatrix) {
  12524. this._worldMatrix = BABYLON.Matrix.Identity();
  12525. }
  12526. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12527. return this._worldMatrix;
  12528. };
  12529. SpotLight.prototype.getTypeID = function () {
  12530. return 2;
  12531. };
  12532. SpotLight.prototype.getRotation = function () {
  12533. this.direction.normalize();
  12534. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  12535. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  12536. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  12537. };
  12538. return SpotLight;
  12539. }(BABYLON.Light));
  12540. __decorate([
  12541. BABYLON.serializeAsVector3()
  12542. ], SpotLight.prototype, "position", void 0);
  12543. __decorate([
  12544. BABYLON.serializeAsVector3()
  12545. ], SpotLight.prototype, "direction", void 0);
  12546. __decorate([
  12547. BABYLON.serialize()
  12548. ], SpotLight.prototype, "angle", void 0);
  12549. __decorate([
  12550. BABYLON.serialize()
  12551. ], SpotLight.prototype, "exponent", void 0);
  12552. BABYLON.SpotLight = SpotLight;
  12553. })(BABYLON || (BABYLON = {}));
  12554. //# sourceMappingURL=babylon.spotLight.js.map
  12555. var BABYLON;
  12556. (function (BABYLON) {
  12557. var HemisphericLight = (function (_super) {
  12558. __extends(HemisphericLight, _super);
  12559. function HemisphericLight(name, direction, scene) {
  12560. var _this = _super.call(this, name, scene) || this;
  12561. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  12562. _this.direction = direction;
  12563. return _this;
  12564. }
  12565. HemisphericLight.prototype.getClassName = function () {
  12566. return "HemisphericLight";
  12567. };
  12568. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  12569. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  12570. return this.direction;
  12571. };
  12572. HemisphericLight.prototype.getShadowGenerator = function () {
  12573. return null;
  12574. };
  12575. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  12576. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12577. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  12578. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  12579. };
  12580. HemisphericLight.prototype._getWorldMatrix = function () {
  12581. if (!this._worldMatrix) {
  12582. this._worldMatrix = BABYLON.Matrix.Identity();
  12583. }
  12584. return this._worldMatrix;
  12585. };
  12586. HemisphericLight.prototype.getTypeID = function () {
  12587. return 3;
  12588. };
  12589. return HemisphericLight;
  12590. }(BABYLON.Light));
  12591. __decorate([
  12592. BABYLON.serializeAsColor3()
  12593. ], HemisphericLight.prototype, "groundColor", void 0);
  12594. __decorate([
  12595. BABYLON.serializeAsVector3()
  12596. ], HemisphericLight.prototype, "direction", void 0);
  12597. BABYLON.HemisphericLight = HemisphericLight;
  12598. })(BABYLON || (BABYLON = {}));
  12599. //# sourceMappingURL=babylon.hemisphericLight.js.map
  12600. var BABYLON;
  12601. (function (BABYLON) {
  12602. var DirectionalLight = (function (_super) {
  12603. __extends(DirectionalLight, _super);
  12604. function DirectionalLight(name, direction, scene) {
  12605. var _this = _super.call(this, name, scene) || this;
  12606. _this.shadowOrthoScale = 0.5;
  12607. _this.autoUpdateExtends = true;
  12608. // Cache
  12609. _this._orthoLeft = Number.MAX_VALUE;
  12610. _this._orthoRight = Number.MIN_VALUE;
  12611. _this._orthoTop = Number.MIN_VALUE;
  12612. _this._orthoBottom = Number.MAX_VALUE;
  12613. _this.position = direction.scale(-1);
  12614. _this.direction = direction;
  12615. return _this;
  12616. }
  12617. DirectionalLight.prototype.getClassName = function () {
  12618. return "DirectionalLight";
  12619. };
  12620. DirectionalLight.prototype.getAbsolutePosition = function () {
  12621. return this.transformedPosition ? this.transformedPosition : this.position;
  12622. };
  12623. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  12624. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12625. return this.direction;
  12626. };
  12627. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12628. var activeCamera = this.getScene().activeCamera;
  12629. // Check extends
  12630. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  12631. var tempVector3 = BABYLON.Vector3.Zero();
  12632. this._orthoLeft = Number.MAX_VALUE;
  12633. this._orthoRight = Number.MIN_VALUE;
  12634. this._orthoTop = Number.MIN_VALUE;
  12635. this._orthoBottom = Number.MAX_VALUE;
  12636. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  12637. var mesh = renderList[meshIndex];
  12638. if (!mesh) {
  12639. continue;
  12640. }
  12641. var boundingInfo = mesh.getBoundingInfo();
  12642. if (!boundingInfo) {
  12643. continue;
  12644. }
  12645. var boundingBox = boundingInfo.boundingBox;
  12646. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  12647. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  12648. if (tempVector3.x < this._orthoLeft)
  12649. this._orthoLeft = tempVector3.x;
  12650. if (tempVector3.y < this._orthoBottom)
  12651. this._orthoBottom = tempVector3.y;
  12652. if (tempVector3.x > this._orthoRight)
  12653. this._orthoRight = tempVector3.x;
  12654. if (tempVector3.y > this._orthoTop)
  12655. this._orthoTop = tempVector3.y;
  12656. }
  12657. }
  12658. }
  12659. var xOffset = this._orthoRight - this._orthoLeft;
  12660. var yOffset = this._orthoTop - this._orthoBottom;
  12661. 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);
  12662. };
  12663. DirectionalLight.prototype.supportsVSM = function () {
  12664. return true;
  12665. };
  12666. DirectionalLight.prototype.needRefreshPerFrame = function () {
  12667. return true;
  12668. };
  12669. DirectionalLight.prototype.needCube = function () {
  12670. return false;
  12671. };
  12672. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12673. return this.direction;
  12674. };
  12675. DirectionalLight.prototype.computeTransformedPosition = function () {
  12676. if (this.parent && this.parent.getWorldMatrix) {
  12677. if (!this.transformedPosition) {
  12678. this.transformedPosition = BABYLON.Vector3.Zero();
  12679. }
  12680. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12681. return true;
  12682. }
  12683. return false;
  12684. };
  12685. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12686. if (this.parent && this.parent.getWorldMatrix) {
  12687. if (!this._transformedDirection) {
  12688. this._transformedDirection = BABYLON.Vector3.Zero();
  12689. }
  12690. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12691. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12692. return;
  12693. }
  12694. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12695. };
  12696. DirectionalLight.prototype._getWorldMatrix = function () {
  12697. if (!this._worldMatrix) {
  12698. this._worldMatrix = BABYLON.Matrix.Identity();
  12699. }
  12700. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12701. return this._worldMatrix;
  12702. };
  12703. DirectionalLight.prototype.getTypeID = function () {
  12704. return 1;
  12705. };
  12706. return DirectionalLight;
  12707. }(BABYLON.Light));
  12708. __decorate([
  12709. BABYLON.serializeAsVector3()
  12710. ], DirectionalLight.prototype, "position", void 0);
  12711. __decorate([
  12712. BABYLON.serializeAsVector3()
  12713. ], DirectionalLight.prototype, "direction", void 0);
  12714. __decorate([
  12715. BABYLON.serialize()
  12716. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12717. __decorate([
  12718. BABYLON.serialize()
  12719. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12720. BABYLON.DirectionalLight = DirectionalLight;
  12721. })(BABYLON || (BABYLON = {}));
  12722. //# sourceMappingURL=babylon.directionalLight.js.map
  12723. var BABYLON;
  12724. (function (BABYLON) {
  12725. var ShadowGenerator = (function () {
  12726. function ShadowGenerator(mapSize, light) {
  12727. var _this = this;
  12728. // Members
  12729. this._filter = ShadowGenerator.FILTER_NONE;
  12730. this.blurScale = 2;
  12731. this._blurBoxOffset = 0;
  12732. this._bias = 0.00005;
  12733. this._lightDirection = BABYLON.Vector3.Zero();
  12734. this.forceBackFacesOnly = false;
  12735. this._darkness = 0;
  12736. this._transparencyShadow = false;
  12737. this._viewMatrix = BABYLON.Matrix.Zero();
  12738. this._projectionMatrix = BABYLON.Matrix.Zero();
  12739. this._transformMatrix = BABYLON.Matrix.Zero();
  12740. this._worldViewProjection = BABYLON.Matrix.Zero();
  12741. this._currentFaceIndex = 0;
  12742. this._currentFaceIndexCache = 0;
  12743. this._useFullFloat = true;
  12744. this._light = light;
  12745. this._scene = light.getScene();
  12746. this._mapSize = mapSize;
  12747. light._shadowGenerator = this;
  12748. // Texture type fallback from float to int if not supported.
  12749. var textureType;
  12750. var caps = this._scene.getEngine().getCaps();
  12751. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12752. this._useFullFloat = true;
  12753. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12754. }
  12755. else {
  12756. this._useFullFloat = false;
  12757. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12758. }
  12759. // Render target
  12760. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12761. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12762. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12763. this._shadowMap.anisotropicFilteringLevel = 1;
  12764. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12765. this._shadowMap.renderParticles = false;
  12766. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12767. _this._currentFaceIndex = faceIndex;
  12768. });
  12769. this._shadowMap.onAfterUnbindObservable.add(function () {
  12770. if (!_this.useBlurVarianceShadowMap) {
  12771. return;
  12772. }
  12773. if (!_this._shadowMap2) {
  12774. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12775. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12776. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12777. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12778. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12779. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12780. effect.setTexture("textureSampler", _this._shadowMap);
  12781. });
  12782. _this.blurBoxOffset = 1;
  12783. }
  12784. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12785. });
  12786. // Custom render function
  12787. var renderSubMesh = function (subMesh) {
  12788. var mesh = subMesh.getRenderingMesh();
  12789. var scene = _this._scene;
  12790. var engine = scene.getEngine();
  12791. // Culling
  12792. engine.setState(subMesh.getMaterial().backFaceCulling);
  12793. // Managing instances
  12794. var batch = mesh._getInstancesRenderList(subMesh._id);
  12795. if (batch.mustReturn) {
  12796. return;
  12797. }
  12798. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12799. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12800. engine.enableEffect(_this._effect);
  12801. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12802. var material = subMesh.getMaterial();
  12803. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12804. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12805. if (_this.getLight().needCube()) {
  12806. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12807. }
  12808. // Alpha test
  12809. if (material && material.needAlphaTesting()) {
  12810. var alphaTexture = material.getAlphaTestTexture();
  12811. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12812. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12813. }
  12814. // Bones
  12815. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12816. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12817. }
  12818. if (_this.forceBackFacesOnly) {
  12819. engine.setState(true, 0, false, true);
  12820. }
  12821. // Draw
  12822. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12823. if (_this.forceBackFacesOnly) {
  12824. engine.setState(true, 0, false, false);
  12825. }
  12826. }
  12827. else {
  12828. // Need to reset refresh rate of the shadowMap
  12829. _this._shadowMap.resetRefreshCounter();
  12830. }
  12831. };
  12832. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12833. var index;
  12834. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12835. renderSubMesh(opaqueSubMeshes.data[index]);
  12836. }
  12837. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12838. renderSubMesh(alphaTestSubMeshes.data[index]);
  12839. }
  12840. if (_this._transparencyShadow) {
  12841. for (index = 0; index < transparentSubMeshes.length; index++) {
  12842. renderSubMesh(transparentSubMeshes.data[index]);
  12843. }
  12844. }
  12845. };
  12846. this._shadowMap.onClearObservable.add(function (engine) {
  12847. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12848. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12849. }
  12850. else {
  12851. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12852. }
  12853. });
  12854. }
  12855. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12856. // Static
  12857. get: function () {
  12858. return ShadowGenerator._FILTER_NONE;
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12864. get: function () {
  12865. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12866. },
  12867. enumerable: true,
  12868. configurable: true
  12869. });
  12870. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12871. get: function () {
  12872. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12873. },
  12874. enumerable: true,
  12875. configurable: true
  12876. });
  12877. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12878. get: function () {
  12879. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12880. },
  12881. enumerable: true,
  12882. configurable: true
  12883. });
  12884. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12885. get: function () {
  12886. return this._bias;
  12887. },
  12888. set: function (bias) {
  12889. this._bias = bias;
  12890. },
  12891. enumerable: true,
  12892. configurable: true
  12893. });
  12894. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12895. get: function () {
  12896. return this._blurBoxOffset;
  12897. },
  12898. set: function (value) {
  12899. var _this = this;
  12900. if (this._blurBoxOffset === value) {
  12901. return;
  12902. }
  12903. this._blurBoxOffset = value;
  12904. if (this._boxBlurPostprocess) {
  12905. this._boxBlurPostprocess.dispose();
  12906. }
  12907. 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);
  12908. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12909. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12910. });
  12911. },
  12912. enumerable: true,
  12913. configurable: true
  12914. });
  12915. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12916. get: function () {
  12917. return this._filter;
  12918. },
  12919. set: function (value) {
  12920. if (this._filter === value) {
  12921. return;
  12922. }
  12923. this._filter = value;
  12924. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12925. this._shadowMap.anisotropicFilteringLevel = 16;
  12926. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12927. }
  12928. else {
  12929. this._shadowMap.anisotropicFilteringLevel = 1;
  12930. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12931. }
  12932. },
  12933. enumerable: true,
  12934. configurable: true
  12935. });
  12936. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12937. get: function () {
  12938. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12939. },
  12940. set: function (value) {
  12941. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12942. },
  12943. enumerable: true,
  12944. configurable: true
  12945. });
  12946. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12947. get: function () {
  12948. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12949. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12950. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12951. },
  12952. set: function (value) {
  12953. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12959. get: function () {
  12960. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12961. },
  12962. set: function (value) {
  12963. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12964. },
  12965. enumerable: true,
  12966. configurable: true
  12967. });
  12968. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12969. var defines = [];
  12970. if (this._useFullFloat) {
  12971. defines.push("#define FULLFLOAT");
  12972. }
  12973. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12974. defines.push("#define VSM");
  12975. }
  12976. if (this.getLight().needCube()) {
  12977. defines.push("#define CUBEMAP");
  12978. }
  12979. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12980. var mesh = subMesh.getMesh();
  12981. var material = subMesh.getMaterial();
  12982. // Alpha test
  12983. if (material && material.needAlphaTesting()) {
  12984. defines.push("#define ALPHATEST");
  12985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12986. attribs.push(BABYLON.VertexBuffer.UVKind);
  12987. defines.push("#define UV1");
  12988. }
  12989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12990. var alphaTexture = material.getAlphaTestTexture();
  12991. if (alphaTexture.coordinatesIndex === 1) {
  12992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12993. defines.push("#define UV2");
  12994. }
  12995. }
  12996. }
  12997. // Bones
  12998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13001. if (mesh.numBoneInfluencers > 4) {
  13002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  13003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  13004. }
  13005. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  13006. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13007. }
  13008. else {
  13009. defines.push("#define NUM_BONE_INFLUENCERS 0");
  13010. }
  13011. // Instances
  13012. if (useInstances) {
  13013. defines.push("#define INSTANCES");
  13014. attribs.push("world0");
  13015. attribs.push("world1");
  13016. attribs.push("world2");
  13017. attribs.push("world3");
  13018. }
  13019. // Get correct effect
  13020. var join = defines.join("\n");
  13021. if (this._cachedDefines !== join) {
  13022. this._cachedDefines = join;
  13023. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  13024. }
  13025. return this._effect.isReady();
  13026. };
  13027. ShadowGenerator.prototype.getShadowMap = function () {
  13028. return this._shadowMap;
  13029. };
  13030. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  13031. if (this._shadowMap2) {
  13032. return this._shadowMap2;
  13033. }
  13034. return this._shadowMap;
  13035. };
  13036. ShadowGenerator.prototype.getLight = function () {
  13037. return this._light;
  13038. };
  13039. // Methods
  13040. ShadowGenerator.prototype.getTransformMatrix = function () {
  13041. var scene = this._scene;
  13042. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  13043. return this._transformMatrix;
  13044. }
  13045. this._currentRenderID = scene.getRenderId();
  13046. this._currentFaceIndexCache = this._currentFaceIndex;
  13047. var lightPosition = this._light.position;
  13048. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  13049. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  13050. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  13051. }
  13052. if (this._light.computeTransformedPosition()) {
  13053. lightPosition = this._light.transformedPosition;
  13054. }
  13055. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  13056. this._cachedPosition = lightPosition.clone();
  13057. this._cachedDirection = this._lightDirection.clone();
  13058. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  13059. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  13060. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13061. }
  13062. return this._transformMatrix;
  13063. };
  13064. ShadowGenerator.prototype.getDarkness = function () {
  13065. return this._darkness;
  13066. };
  13067. ShadowGenerator.prototype.setDarkness = function (darkness) {
  13068. if (darkness >= 1.0)
  13069. this._darkness = 1.0;
  13070. else if (darkness <= 0.0)
  13071. this._darkness = 0.0;
  13072. else
  13073. this._darkness = darkness;
  13074. };
  13075. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  13076. this._transparencyShadow = hasShadow;
  13077. };
  13078. ShadowGenerator.prototype._packHalf = function (depth) {
  13079. var scale = depth * 255.0;
  13080. var fract = scale - Math.floor(scale);
  13081. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  13082. };
  13083. ShadowGenerator.prototype.dispose = function () {
  13084. this._shadowMap.dispose();
  13085. if (this._shadowMap2) {
  13086. this._shadowMap2.dispose();
  13087. }
  13088. if (this._downSamplePostprocess) {
  13089. this._downSamplePostprocess.dispose();
  13090. }
  13091. if (this._boxBlurPostprocess) {
  13092. this._boxBlurPostprocess.dispose();
  13093. }
  13094. this._light._shadowGenerator = null;
  13095. };
  13096. ShadowGenerator.prototype.serialize = function () {
  13097. var serializationObject = {};
  13098. serializationObject.lightId = this._light.id;
  13099. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  13100. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  13101. serializationObject.usePoissonSampling = this.usePoissonSampling;
  13102. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  13103. serializationObject.renderList = [];
  13104. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  13105. var mesh = this.getShadowMap().renderList[meshIndex];
  13106. serializationObject.renderList.push(mesh.id);
  13107. }
  13108. return serializationObject;
  13109. };
  13110. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  13111. //casting to point light, as light is missing the position attr and typescript complains.
  13112. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  13113. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  13114. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  13115. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  13116. meshes.forEach(function (mesh) {
  13117. shadowGenerator.getShadowMap().renderList.push(mesh);
  13118. });
  13119. }
  13120. if (parsedShadowGenerator.usePoissonSampling) {
  13121. shadowGenerator.usePoissonSampling = true;
  13122. }
  13123. else if (parsedShadowGenerator.useVarianceShadowMap) {
  13124. shadowGenerator.useVarianceShadowMap = true;
  13125. }
  13126. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  13127. shadowGenerator.useBlurVarianceShadowMap = true;
  13128. if (parsedShadowGenerator.blurScale) {
  13129. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  13130. }
  13131. if (parsedShadowGenerator.blurBoxOffset) {
  13132. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  13133. }
  13134. }
  13135. if (parsedShadowGenerator.bias !== undefined) {
  13136. shadowGenerator.bias = parsedShadowGenerator.bias;
  13137. }
  13138. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  13139. return shadowGenerator;
  13140. };
  13141. return ShadowGenerator;
  13142. }());
  13143. ShadowGenerator._FILTER_NONE = 0;
  13144. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  13145. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  13146. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  13147. BABYLON.ShadowGenerator = ShadowGenerator;
  13148. })(BABYLON || (BABYLON = {}));
  13149. //# sourceMappingURL=babylon.shadowGenerator.js.map
  13150. var BABYLON;
  13151. (function (BABYLON) {
  13152. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  13153. if (boxMin.x > sphereCenter.x + sphereRadius)
  13154. return false;
  13155. if (sphereCenter.x - sphereRadius > boxMax.x)
  13156. return false;
  13157. if (boxMin.y > sphereCenter.y + sphereRadius)
  13158. return false;
  13159. if (sphereCenter.y - sphereRadius > boxMax.y)
  13160. return false;
  13161. if (boxMin.z > sphereCenter.z + sphereRadius)
  13162. return false;
  13163. if (sphereCenter.z - sphereRadius > boxMax.z)
  13164. return false;
  13165. return true;
  13166. };
  13167. var getLowestRoot = (function () {
  13168. var result = { root: 0, found: false };
  13169. return function (a, b, c, maxR) {
  13170. result.root = 0;
  13171. result.found = false;
  13172. var determinant = b * b - 4.0 * a * c;
  13173. if (determinant < 0)
  13174. return result;
  13175. var sqrtD = Math.sqrt(determinant);
  13176. var r1 = (-b - sqrtD) / (2.0 * a);
  13177. var r2 = (-b + sqrtD) / (2.0 * a);
  13178. if (r1 > r2) {
  13179. var temp = r2;
  13180. r2 = r1;
  13181. r1 = temp;
  13182. }
  13183. if (r1 > 0 && r1 < maxR) {
  13184. result.root = r1;
  13185. result.found = true;
  13186. return result;
  13187. }
  13188. if (r2 > 0 && r2 < maxR) {
  13189. result.root = r2;
  13190. result.found = true;
  13191. return result;
  13192. }
  13193. return result;
  13194. };
  13195. })();
  13196. var Collider = (function () {
  13197. function Collider() {
  13198. this.radius = new BABYLON.Vector3(1, 1, 1);
  13199. this.retry = 0;
  13200. this.basePointWorld = BABYLON.Vector3.Zero();
  13201. this.velocityWorld = BABYLON.Vector3.Zero();
  13202. this.normalizedVelocity = BABYLON.Vector3.Zero();
  13203. this._collisionPoint = BABYLON.Vector3.Zero();
  13204. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  13205. this._tempVector = BABYLON.Vector3.Zero();
  13206. this._tempVector2 = BABYLON.Vector3.Zero();
  13207. this._tempVector3 = BABYLON.Vector3.Zero();
  13208. this._tempVector4 = BABYLON.Vector3.Zero();
  13209. this._edge = BABYLON.Vector3.Zero();
  13210. this._baseToVertex = BABYLON.Vector3.Zero();
  13211. this._destinationPoint = BABYLON.Vector3.Zero();
  13212. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  13213. this._displacementVector = BABYLON.Vector3.Zero();
  13214. }
  13215. // Methods
  13216. Collider.prototype._initialize = function (source, dir, e) {
  13217. this.velocity = dir;
  13218. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  13219. this.basePoint = source;
  13220. source.multiplyToRef(this.radius, this.basePointWorld);
  13221. dir.multiplyToRef(this.radius, this.velocityWorld);
  13222. this.velocityWorldLength = this.velocityWorld.length();
  13223. this.epsilon = e;
  13224. this.collisionFound = false;
  13225. };
  13226. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  13227. pa.subtractToRef(point, this._tempVector);
  13228. pb.subtractToRef(point, this._tempVector2);
  13229. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  13230. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13231. if (d < 0)
  13232. return false;
  13233. pc.subtractToRef(point, this._tempVector3);
  13234. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  13235. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13236. if (d < 0)
  13237. return false;
  13238. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  13239. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13240. return d >= 0;
  13241. };
  13242. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  13243. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  13244. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  13245. if (distance > this.velocityWorldLength + max + sphereRadius) {
  13246. return false;
  13247. }
  13248. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  13249. return false;
  13250. return true;
  13251. };
  13252. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  13253. var t0;
  13254. var embeddedInPlane = false;
  13255. //defensive programming, actually not needed.
  13256. if (!trianglePlaneArray) {
  13257. trianglePlaneArray = [];
  13258. }
  13259. if (!trianglePlaneArray[faceIndex]) {
  13260. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  13261. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  13262. }
  13263. var trianglePlane = trianglePlaneArray[faceIndex];
  13264. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  13265. return;
  13266. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  13267. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  13268. if (normalDotVelocity == 0) {
  13269. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  13270. return;
  13271. embeddedInPlane = true;
  13272. t0 = 0;
  13273. }
  13274. else {
  13275. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13276. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13277. if (t0 > t1) {
  13278. var temp = t1;
  13279. t1 = t0;
  13280. t0 = temp;
  13281. }
  13282. if (t0 > 1.0 || t1 < 0.0)
  13283. return;
  13284. if (t0 < 0)
  13285. t0 = 0;
  13286. if (t0 > 1.0)
  13287. t0 = 1.0;
  13288. }
  13289. this._collisionPoint.copyFromFloats(0, 0, 0);
  13290. var found = false;
  13291. var t = 1.0;
  13292. if (!embeddedInPlane) {
  13293. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  13294. this.velocity.scaleToRef(t0, this._tempVector);
  13295. this._planeIntersectionPoint.addInPlace(this._tempVector);
  13296. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  13297. found = true;
  13298. t = t0;
  13299. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  13300. }
  13301. }
  13302. if (!found) {
  13303. var velocitySquaredLength = this.velocity.lengthSquared();
  13304. var a = velocitySquaredLength;
  13305. this.basePoint.subtractToRef(p1, this._tempVector);
  13306. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13307. var c = this._tempVector.lengthSquared() - 1.0;
  13308. var lowestRoot = getLowestRoot(a, b, c, t);
  13309. if (lowestRoot.found) {
  13310. t = lowestRoot.root;
  13311. found = true;
  13312. this._collisionPoint.copyFrom(p1);
  13313. }
  13314. this.basePoint.subtractToRef(p2, this._tempVector);
  13315. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13316. c = this._tempVector.lengthSquared() - 1.0;
  13317. lowestRoot = getLowestRoot(a, b, c, t);
  13318. if (lowestRoot.found) {
  13319. t = lowestRoot.root;
  13320. found = true;
  13321. this._collisionPoint.copyFrom(p2);
  13322. }
  13323. this.basePoint.subtractToRef(p3, this._tempVector);
  13324. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13325. c = this._tempVector.lengthSquared() - 1.0;
  13326. lowestRoot = getLowestRoot(a, b, c, t);
  13327. if (lowestRoot.found) {
  13328. t = lowestRoot.root;
  13329. found = true;
  13330. this._collisionPoint.copyFrom(p3);
  13331. }
  13332. p2.subtractToRef(p1, this._edge);
  13333. p1.subtractToRef(this.basePoint, this._baseToVertex);
  13334. var edgeSquaredLength = this._edge.lengthSquared();
  13335. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13336. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13337. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13338. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13339. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13340. lowestRoot = getLowestRoot(a, b, c, t);
  13341. if (lowestRoot.found) {
  13342. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13343. if (f >= 0.0 && f <= 1.0) {
  13344. t = lowestRoot.root;
  13345. found = true;
  13346. this._edge.scaleInPlace(f);
  13347. p1.addToRef(this._edge, this._collisionPoint);
  13348. }
  13349. }
  13350. p3.subtractToRef(p2, this._edge);
  13351. p2.subtractToRef(this.basePoint, this._baseToVertex);
  13352. edgeSquaredLength = this._edge.lengthSquared();
  13353. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13354. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13355. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13356. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13357. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13358. lowestRoot = getLowestRoot(a, b, c, t);
  13359. if (lowestRoot.found) {
  13360. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13361. if (f >= 0.0 && f <= 1.0) {
  13362. t = lowestRoot.root;
  13363. found = true;
  13364. this._edge.scaleInPlace(f);
  13365. p2.addToRef(this._edge, this._collisionPoint);
  13366. }
  13367. }
  13368. p1.subtractToRef(p3, this._edge);
  13369. p3.subtractToRef(this.basePoint, this._baseToVertex);
  13370. edgeSquaredLength = this._edge.lengthSquared();
  13371. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13372. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13373. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13374. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13375. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13376. lowestRoot = getLowestRoot(a, b, c, t);
  13377. if (lowestRoot.found) {
  13378. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13379. if (f >= 0.0 && f <= 1.0) {
  13380. t = lowestRoot.root;
  13381. found = true;
  13382. this._edge.scaleInPlace(f);
  13383. p3.addToRef(this._edge, this._collisionPoint);
  13384. }
  13385. }
  13386. }
  13387. if (found) {
  13388. var distToCollision = t * this.velocity.length();
  13389. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  13390. if (!this.intersectionPoint) {
  13391. this.intersectionPoint = this._collisionPoint.clone();
  13392. }
  13393. else {
  13394. this.intersectionPoint.copyFrom(this._collisionPoint);
  13395. }
  13396. this.nearestDistance = distToCollision;
  13397. this.collisionFound = true;
  13398. }
  13399. }
  13400. };
  13401. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  13402. for (var i = indexStart; i < indexEnd; i += 3) {
  13403. var p1 = pts[indices[i] - decal];
  13404. var p2 = pts[indices[i + 1] - decal];
  13405. var p3 = pts[indices[i + 2] - decal];
  13406. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  13407. }
  13408. };
  13409. Collider.prototype._getResponse = function (pos, vel) {
  13410. pos.addToRef(vel, this._destinationPoint);
  13411. vel.scaleInPlace((this.nearestDistance / vel.length()));
  13412. this.basePoint.addToRef(vel, pos);
  13413. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  13414. this._slidePlaneNormal.normalize();
  13415. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  13416. pos.addInPlace(this._displacementVector);
  13417. this.intersectionPoint.addInPlace(this._displacementVector);
  13418. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  13419. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  13420. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  13421. };
  13422. return Collider;
  13423. }());
  13424. BABYLON.Collider = Collider;
  13425. })(BABYLON || (BABYLON = {}));
  13426. //# sourceMappingURL=babylon.collider.js.map
  13427. var BABYLON;
  13428. (function (BABYLON) {
  13429. //WebWorker code will be inserted to this variable.
  13430. BABYLON.CollisionWorker = "";
  13431. var WorkerTaskType;
  13432. (function (WorkerTaskType) {
  13433. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  13434. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  13435. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  13436. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  13437. var WorkerReplyType;
  13438. (function (WorkerReplyType) {
  13439. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  13440. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  13441. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  13442. var CollisionCoordinatorWorker = (function () {
  13443. function CollisionCoordinatorWorker() {
  13444. var _this = this;
  13445. this._scaledPosition = BABYLON.Vector3.Zero();
  13446. this._scaledVelocity = BABYLON.Vector3.Zero();
  13447. this.onMeshUpdated = function (mesh) {
  13448. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  13449. };
  13450. this.onGeometryUpdated = function (geometry) {
  13451. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  13452. };
  13453. this._afterRender = function () {
  13454. if (!_this._init)
  13455. return;
  13456. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  13457. return;
  13458. }
  13459. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  13460. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  13461. if (_this._runningUpdated > 4) {
  13462. return;
  13463. }
  13464. ++_this._runningUpdated;
  13465. var payload = {
  13466. updatedMeshes: _this._addUpdateMeshesList,
  13467. updatedGeometries: _this._addUpdateGeometriesList,
  13468. removedGeometries: _this._toRemoveGeometryArray,
  13469. removedMeshes: _this._toRemoveMeshesArray
  13470. };
  13471. var message = {
  13472. payload: payload,
  13473. taskType: WorkerTaskType.UPDATE
  13474. };
  13475. var serializable = [];
  13476. for (var id in payload.updatedGeometries) {
  13477. if (payload.updatedGeometries.hasOwnProperty(id)) {
  13478. //prepare transferables
  13479. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  13480. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  13481. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  13482. }
  13483. }
  13484. _this._worker.postMessage(message, serializable);
  13485. _this._addUpdateMeshesList = {};
  13486. _this._addUpdateGeometriesList = {};
  13487. _this._toRemoveGeometryArray = [];
  13488. _this._toRemoveMeshesArray = [];
  13489. };
  13490. this._onMessageFromWorker = function (e) {
  13491. var returnData = e.data;
  13492. if (returnData.error != WorkerReplyType.SUCCESS) {
  13493. //TODO what errors can be returned from the worker?
  13494. BABYLON.Tools.Warn("error returned from worker!");
  13495. return;
  13496. }
  13497. switch (returnData.taskType) {
  13498. case WorkerTaskType.INIT:
  13499. _this._init = true;
  13500. //Update the worked with ALL of the scene's current state
  13501. _this._scene.meshes.forEach(function (mesh) {
  13502. _this.onMeshAdded(mesh);
  13503. });
  13504. _this._scene.getGeometries().forEach(function (geometry) {
  13505. _this.onGeometryAdded(geometry);
  13506. });
  13507. break;
  13508. case WorkerTaskType.UPDATE:
  13509. _this._runningUpdated--;
  13510. break;
  13511. case WorkerTaskType.COLLIDE:
  13512. _this._runningCollisionTask = false;
  13513. var returnPayload = returnData.payload;
  13514. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  13515. return;
  13516. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  13517. //cleanup
  13518. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  13519. break;
  13520. }
  13521. };
  13522. this._collisionsCallbackArray = [];
  13523. this._init = false;
  13524. this._runningUpdated = 0;
  13525. this._runningCollisionTask = false;
  13526. this._addUpdateMeshesList = {};
  13527. this._addUpdateGeometriesList = {};
  13528. this._toRemoveGeometryArray = [];
  13529. this._toRemoveMeshesArray = [];
  13530. }
  13531. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13532. if (!this._init)
  13533. return;
  13534. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  13535. return;
  13536. position.divideToRef(collider.radius, this._scaledPosition);
  13537. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13538. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  13539. var payload = {
  13540. collider: {
  13541. position: this._scaledPosition.asArray(),
  13542. velocity: this._scaledVelocity.asArray(),
  13543. radius: collider.radius.asArray()
  13544. },
  13545. collisionId: collisionIndex,
  13546. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  13547. maximumRetry: maximumRetry
  13548. };
  13549. var message = {
  13550. payload: payload,
  13551. taskType: WorkerTaskType.COLLIDE
  13552. };
  13553. this._worker.postMessage(message);
  13554. };
  13555. CollisionCoordinatorWorker.prototype.init = function (scene) {
  13556. this._scene = scene;
  13557. this._scene.registerAfterRender(this._afterRender);
  13558. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  13559. this._worker = new Worker(workerUrl);
  13560. this._worker.onmessage = this._onMessageFromWorker;
  13561. var message = {
  13562. payload: {},
  13563. taskType: WorkerTaskType.INIT
  13564. };
  13565. this._worker.postMessage(message);
  13566. };
  13567. CollisionCoordinatorWorker.prototype.destroy = function () {
  13568. this._scene.unregisterAfterRender(this._afterRender);
  13569. this._worker.terminate();
  13570. };
  13571. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  13572. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  13573. this.onMeshUpdated(mesh);
  13574. };
  13575. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  13576. this._toRemoveMeshesArray.push(mesh.uniqueId);
  13577. };
  13578. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  13579. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  13580. geometry.onGeometryUpdated = this.onGeometryUpdated;
  13581. this.onGeometryUpdated(geometry);
  13582. };
  13583. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  13584. this._toRemoveGeometryArray.push(geometry.id);
  13585. };
  13586. return CollisionCoordinatorWorker;
  13587. }());
  13588. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  13589. var submeshes = [];
  13590. if (mesh.subMeshes) {
  13591. submeshes = mesh.subMeshes.map(function (sm, idx) {
  13592. return {
  13593. position: idx,
  13594. verticesStart: sm.verticesStart,
  13595. verticesCount: sm.verticesCount,
  13596. indexStart: sm.indexStart,
  13597. indexCount: sm.indexCount,
  13598. hasMaterial: !!sm.getMaterial(),
  13599. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13600. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  13601. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13602. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  13603. };
  13604. });
  13605. }
  13606. var geometryId = null;
  13607. if (mesh instanceof BABYLON.Mesh) {
  13608. geometryId = mesh.geometry ? mesh.geometry.id : null;
  13609. }
  13610. else if (mesh instanceof BABYLON.InstancedMesh) {
  13611. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  13612. }
  13613. return {
  13614. uniqueId: mesh.uniqueId,
  13615. id: mesh.id,
  13616. name: mesh.name,
  13617. geometryId: geometryId,
  13618. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13619. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  13620. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13621. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  13622. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  13623. subMeshes: submeshes,
  13624. checkCollisions: mesh.checkCollisions
  13625. };
  13626. };
  13627. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  13628. return {
  13629. id: geometry.id,
  13630. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  13631. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  13632. indices: new Uint32Array(geometry.getIndices() || []),
  13633. };
  13634. };
  13635. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  13636. var CollisionCoordinatorLegacy = (function () {
  13637. function CollisionCoordinatorLegacy() {
  13638. this._scaledPosition = BABYLON.Vector3.Zero();
  13639. this._scaledVelocity = BABYLON.Vector3.Zero();
  13640. this._finalPosition = BABYLON.Vector3.Zero();
  13641. }
  13642. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13643. position.divideToRef(collider.radius, this._scaledPosition);
  13644. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13645. collider.collidedMesh = null;
  13646. collider.retry = 0;
  13647. collider.initialVelocity = this._scaledVelocity;
  13648. collider.initialPosition = this._scaledPosition;
  13649. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  13650. this._finalPosition.multiplyInPlace(collider.radius);
  13651. //run the callback
  13652. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  13653. };
  13654. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  13655. this._scene = scene;
  13656. };
  13657. CollisionCoordinatorLegacy.prototype.destroy = function () {
  13658. //Legacy need no destruction method.
  13659. };
  13660. //No update in legacy mode
  13661. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  13662. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  13663. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  13664. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  13665. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  13666. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  13667. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  13668. if (excludedMesh === void 0) { excludedMesh = null; }
  13669. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  13670. if (collider.retry >= maximumRetry) {
  13671. finalPosition.copyFrom(position);
  13672. return;
  13673. }
  13674. collider._initialize(position, velocity, closeDistance);
  13675. // Check all meshes
  13676. for (var index = 0; index < this._scene.meshes.length; index++) {
  13677. var mesh = this._scene.meshes[index];
  13678. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13679. mesh._checkCollision(collider);
  13680. }
  13681. }
  13682. if (!collider.collisionFound) {
  13683. position.addToRef(velocity, finalPosition);
  13684. return;
  13685. }
  13686. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13687. collider._getResponse(position, velocity);
  13688. }
  13689. if (velocity.length() <= closeDistance) {
  13690. finalPosition.copyFrom(position);
  13691. return;
  13692. }
  13693. collider.retry++;
  13694. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13695. };
  13696. return CollisionCoordinatorLegacy;
  13697. }());
  13698. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13699. })(BABYLON || (BABYLON = {}));
  13700. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13701. var BABYLON;
  13702. (function (BABYLON) {
  13703. var Camera = (function (_super) {
  13704. __extends(Camera, _super);
  13705. function Camera(name, position, scene) {
  13706. var _this = _super.call(this, name, scene) || this;
  13707. _this.upVector = BABYLON.Vector3.Up();
  13708. _this.orthoLeft = null;
  13709. _this.orthoRight = null;
  13710. _this.orthoBottom = null;
  13711. _this.orthoTop = null;
  13712. _this.fov = 0.8;
  13713. _this.minZ = 1.0;
  13714. _this.maxZ = 10000.0;
  13715. _this.inertia = 0.9;
  13716. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13717. _this.isIntermediate = false;
  13718. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13719. _this.layerMask = 0x0FFFFFFF;
  13720. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13721. // Camera rig members
  13722. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13723. _this._rigCameras = new Array();
  13724. // Cache
  13725. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13726. _this._projectionMatrix = new BABYLON.Matrix();
  13727. _this._doNotComputeProjectionMatrix = false;
  13728. _this._postProcesses = new Array();
  13729. _this._transformMatrix = BABYLON.Matrix.Zero();
  13730. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13731. _this._activeMeshes = new BABYLON.SmartArray(256);
  13732. _this._globalPosition = BABYLON.Vector3.Zero();
  13733. _this._refreshFrustumPlanes = true;
  13734. scene.addCamera(_this);
  13735. if (!scene.activeCamera) {
  13736. scene.activeCamera = _this;
  13737. }
  13738. _this.position = position;
  13739. return _this;
  13740. }
  13741. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13742. get: function () {
  13743. return Camera._PERSPECTIVE_CAMERA;
  13744. },
  13745. enumerable: true,
  13746. configurable: true
  13747. });
  13748. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13749. get: function () {
  13750. return Camera._ORTHOGRAPHIC_CAMERA;
  13751. },
  13752. enumerable: true,
  13753. configurable: true
  13754. });
  13755. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13756. get: function () {
  13757. return Camera._FOVMODE_VERTICAL_FIXED;
  13758. },
  13759. enumerable: true,
  13760. configurable: true
  13761. });
  13762. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13763. get: function () {
  13764. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13765. },
  13766. enumerable: true,
  13767. configurable: true
  13768. });
  13769. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13770. get: function () {
  13771. return Camera._RIG_MODE_NONE;
  13772. },
  13773. enumerable: true,
  13774. configurable: true
  13775. });
  13776. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13777. get: function () {
  13778. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13779. },
  13780. enumerable: true,
  13781. configurable: true
  13782. });
  13783. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13784. get: function () {
  13785. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13786. },
  13787. enumerable: true,
  13788. configurable: true
  13789. });
  13790. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13791. get: function () {
  13792. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13793. },
  13794. enumerable: true,
  13795. configurable: true
  13796. });
  13797. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13798. get: function () {
  13799. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13800. },
  13801. enumerable: true,
  13802. configurable: true
  13803. });
  13804. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13805. get: function () {
  13806. return Camera._RIG_MODE_VR;
  13807. },
  13808. enumerable: true,
  13809. configurable: true
  13810. });
  13811. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13812. get: function () {
  13813. return Camera._RIG_MODE_WEBVR;
  13814. },
  13815. enumerable: true,
  13816. configurable: true
  13817. });
  13818. Camera.prototype.getClassName = function () {
  13819. return "Camera";
  13820. };
  13821. /**
  13822. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13823. */
  13824. Camera.prototype.toString = function (fullDetails) {
  13825. var ret = "Name: " + this.name;
  13826. ret += ", type: " + this.getClassName();
  13827. if (this.animations) {
  13828. for (var i = 0; i < this.animations.length; i++) {
  13829. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13830. }
  13831. }
  13832. if (fullDetails) {
  13833. }
  13834. return ret;
  13835. };
  13836. Object.defineProperty(Camera.prototype, "globalPosition", {
  13837. get: function () {
  13838. return this._globalPosition;
  13839. },
  13840. enumerable: true,
  13841. configurable: true
  13842. });
  13843. Camera.prototype.getActiveMeshes = function () {
  13844. return this._activeMeshes;
  13845. };
  13846. Camera.prototype.isActiveMesh = function (mesh) {
  13847. return (this._activeMeshes.indexOf(mesh) !== -1);
  13848. };
  13849. //Cache
  13850. Camera.prototype._initCache = function () {
  13851. _super.prototype._initCache.call(this);
  13852. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13853. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13854. this._cache.mode = undefined;
  13855. this._cache.minZ = undefined;
  13856. this._cache.maxZ = undefined;
  13857. this._cache.fov = undefined;
  13858. this._cache.fovMode = undefined;
  13859. this._cache.aspectRatio = undefined;
  13860. this._cache.orthoLeft = undefined;
  13861. this._cache.orthoRight = undefined;
  13862. this._cache.orthoBottom = undefined;
  13863. this._cache.orthoTop = undefined;
  13864. this._cache.renderWidth = undefined;
  13865. this._cache.renderHeight = undefined;
  13866. };
  13867. Camera.prototype._updateCache = function (ignoreParentClass) {
  13868. if (!ignoreParentClass) {
  13869. _super.prototype._updateCache.call(this);
  13870. }
  13871. var engine = this.getEngine();
  13872. this._cache.position.copyFrom(this.position);
  13873. this._cache.upVector.copyFrom(this.upVector);
  13874. this._cache.mode = this.mode;
  13875. this._cache.minZ = this.minZ;
  13876. this._cache.maxZ = this.maxZ;
  13877. this._cache.fov = this.fov;
  13878. this._cache.fovMode = this.fovMode;
  13879. this._cache.aspectRatio = engine.getAspectRatio(this);
  13880. this._cache.orthoLeft = this.orthoLeft;
  13881. this._cache.orthoRight = this.orthoRight;
  13882. this._cache.orthoBottom = this.orthoBottom;
  13883. this._cache.orthoTop = this.orthoTop;
  13884. this._cache.renderWidth = engine.getRenderWidth();
  13885. this._cache.renderHeight = engine.getRenderHeight();
  13886. };
  13887. Camera.prototype._updateFromScene = function () {
  13888. this.updateCache();
  13889. this.update();
  13890. };
  13891. // Synchronized
  13892. Camera.prototype._isSynchronized = function () {
  13893. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13894. };
  13895. Camera.prototype._isSynchronizedViewMatrix = function () {
  13896. if (!_super.prototype._isSynchronized.call(this))
  13897. return false;
  13898. return this._cache.position.equals(this.position)
  13899. && this._cache.upVector.equals(this.upVector)
  13900. && this.isSynchronizedWithParent();
  13901. };
  13902. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13903. var check = this._cache.mode === this.mode
  13904. && this._cache.minZ === this.minZ
  13905. && this._cache.maxZ === this.maxZ;
  13906. if (!check) {
  13907. return false;
  13908. }
  13909. var engine = this.getEngine();
  13910. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13911. check = this._cache.fov === this.fov
  13912. && this._cache.fovMode === this.fovMode
  13913. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13914. }
  13915. else {
  13916. check = this._cache.orthoLeft === this.orthoLeft
  13917. && this._cache.orthoRight === this.orthoRight
  13918. && this._cache.orthoBottom === this.orthoBottom
  13919. && this._cache.orthoTop === this.orthoTop
  13920. && this._cache.renderWidth === engine.getRenderWidth()
  13921. && this._cache.renderHeight === engine.getRenderHeight();
  13922. }
  13923. return check;
  13924. };
  13925. // Controls
  13926. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13927. };
  13928. Camera.prototype.detachControl = function (element) {
  13929. };
  13930. Camera.prototype.update = function () {
  13931. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13932. this._updateRigCameras();
  13933. }
  13934. this._checkInputs();
  13935. };
  13936. Camera.prototype._checkInputs = function () {
  13937. };
  13938. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13939. // invalidate framebuffer
  13940. if (this._postProcesses.length > 0) {
  13941. this._postProcesses[0].markTextureDirty();
  13942. }
  13943. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13944. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13945. var cam = this._rigCameras[i];
  13946. var rigPostProcess = cam._rigPostProcess;
  13947. // for VR rig, there does not have to be a post process
  13948. if (rigPostProcess) {
  13949. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13950. if (isPass) {
  13951. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13952. cam.isIntermediate = this._postProcesses.length === 0;
  13953. }
  13954. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13955. rigPostProcess.markTextureDirty();
  13956. }
  13957. else {
  13958. cam._postProcesses = this._postProcesses.slice(0);
  13959. }
  13960. }
  13961. };
  13962. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13963. if (insertAt === void 0) { insertAt = null; }
  13964. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13965. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13966. return 0;
  13967. }
  13968. if (insertAt == null || insertAt < 0) {
  13969. this._postProcesses.push(postProcess);
  13970. }
  13971. else {
  13972. this._postProcesses.splice(insertAt, 0, postProcess);
  13973. }
  13974. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13975. return this._postProcesses.indexOf(postProcess);
  13976. };
  13977. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13978. if (atIndices === void 0) { atIndices = null; }
  13979. var result = [];
  13980. var i;
  13981. var index;
  13982. if (!atIndices) {
  13983. var idx = this._postProcesses.indexOf(postProcess);
  13984. if (idx !== -1) {
  13985. this._postProcesses.splice(idx, 1);
  13986. }
  13987. }
  13988. else {
  13989. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13990. // iterate descending, so can just splice as we go
  13991. for (i = atIndices.length - 1; i >= 0; i--) {
  13992. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13993. result.push(i);
  13994. continue;
  13995. }
  13996. index = atIndices[i];
  13997. this._postProcesses.splice(index, 1);
  13998. }
  13999. }
  14000. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14001. return result;
  14002. };
  14003. Camera.prototype.getWorldMatrix = function () {
  14004. if (!this._worldMatrix) {
  14005. this._worldMatrix = BABYLON.Matrix.Identity();
  14006. }
  14007. var viewMatrix = this.getViewMatrix();
  14008. viewMatrix.invertToRef(this._worldMatrix);
  14009. return this._worldMatrix;
  14010. };
  14011. Camera.prototype._getViewMatrix = function () {
  14012. return BABYLON.Matrix.Identity();
  14013. };
  14014. Camera.prototype.getViewMatrix = function (force) {
  14015. this._computedViewMatrix = this._computeViewMatrix(force);
  14016. if (!force && this._isSynchronizedViewMatrix()) {
  14017. return this._computedViewMatrix;
  14018. }
  14019. this._refreshFrustumPlanes = true;
  14020. if (!this.parent || !this.parent.getWorldMatrix) {
  14021. this._globalPosition.copyFrom(this.position);
  14022. }
  14023. else {
  14024. if (!this._worldMatrix) {
  14025. this._worldMatrix = BABYLON.Matrix.Identity();
  14026. }
  14027. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14028. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14029. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14030. this._computedViewMatrix.invert();
  14031. this._markSyncedWithParent();
  14032. }
  14033. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14034. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14035. }
  14036. this._currentRenderId = this.getScene().getRenderId();
  14037. return this._computedViewMatrix;
  14038. };
  14039. Camera.prototype._computeViewMatrix = function (force) {
  14040. if (!force && this._isSynchronizedViewMatrix()) {
  14041. return this._computedViewMatrix;
  14042. }
  14043. this._computedViewMatrix = this._getViewMatrix();
  14044. this._currentRenderId = this.getScene().getRenderId();
  14045. return this._computedViewMatrix;
  14046. };
  14047. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14048. this._doNotComputeProjectionMatrix = true;
  14049. if (projection !== undefined) {
  14050. this._projectionMatrix = projection;
  14051. }
  14052. };
  14053. ;
  14054. Camera.prototype.unfreezeProjectionMatrix = function () {
  14055. this._doNotComputeProjectionMatrix = false;
  14056. };
  14057. ;
  14058. Camera.prototype.getProjectionMatrix = function (force) {
  14059. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14060. return this._projectionMatrix;
  14061. }
  14062. this._refreshFrustumPlanes = true;
  14063. var engine = this.getEngine();
  14064. var scene = this.getScene();
  14065. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14066. if (this.minZ <= 0) {
  14067. this.minZ = 0.1;
  14068. }
  14069. if (scene.useRightHandedSystem) {
  14070. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14071. }
  14072. else {
  14073. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14074. }
  14075. return this._projectionMatrix;
  14076. }
  14077. var halfWidth = engine.getRenderWidth() / 2.0;
  14078. var halfHeight = engine.getRenderHeight() / 2.0;
  14079. if (scene.useRightHandedSystem) {
  14080. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14081. }
  14082. else {
  14083. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14084. }
  14085. return this._projectionMatrix;
  14086. };
  14087. Camera.prototype.getTranformationMatrix = function () {
  14088. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14089. return this._transformMatrix;
  14090. };
  14091. Camera.prototype.updateFrustumPlanes = function () {
  14092. if (!this._refreshFrustumPlanes) {
  14093. return;
  14094. }
  14095. this.getTranformationMatrix();
  14096. if (!this._frustumPlanes) {
  14097. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14098. }
  14099. else {
  14100. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14101. }
  14102. this._refreshFrustumPlanes = false;
  14103. };
  14104. Camera.prototype.isInFrustum = function (target) {
  14105. this.updateFrustumPlanes();
  14106. return target.isInFrustum(this._frustumPlanes);
  14107. };
  14108. Camera.prototype.isCompletelyInFrustum = function (target) {
  14109. this.updateFrustumPlanes();
  14110. return target.isCompletelyInFrustum(this._frustumPlanes);
  14111. };
  14112. Camera.prototype.dispose = function () {
  14113. // Animations
  14114. this.getScene().stopAnimation(this);
  14115. // Remove from scene
  14116. this.getScene().removeCamera(this);
  14117. while (this._rigCameras.length > 0) {
  14118. this._rigCameras.pop().dispose();
  14119. }
  14120. // Postprocesses
  14121. var i = this._postProcesses.length;
  14122. while (--i >= 0) {
  14123. this._postProcesses[i].dispose(this);
  14124. }
  14125. _super.prototype.dispose.call(this);
  14126. };
  14127. // ---- Camera rigs section ----
  14128. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14129. while (this._rigCameras.length > 0) {
  14130. this._rigCameras.pop().dispose();
  14131. }
  14132. this.cameraRigMode = mode;
  14133. this._cameraRigParams = {};
  14134. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14135. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14136. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14137. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14138. // create the rig cameras, unless none
  14139. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14140. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14141. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14142. }
  14143. switch (this.cameraRigMode) {
  14144. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14145. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14146. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14147. break;
  14148. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14149. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14150. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14151. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14152. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14153. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14154. break;
  14155. case Camera.RIG_MODE_VR:
  14156. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14157. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14158. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14159. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14160. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14161. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14162. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14163. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14164. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14165. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14166. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14167. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14168. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14169. if (metrics.compensateDistortion) {
  14170. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14171. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14172. }
  14173. break;
  14174. case Camera.RIG_MODE_WEBVR:
  14175. if (rigParams.vrDisplay) {
  14176. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14177. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14178. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14179. this._rigCameras[0].setCameraRigParameter("left", true);
  14180. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14181. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  14182. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14183. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14184. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14185. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14186. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14187. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  14188. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14189. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14190. }
  14191. break;
  14192. }
  14193. this._cascadePostProcessesToRigCams();
  14194. this.
  14195. update();
  14196. };
  14197. Camera.prototype._getVRProjectionMatrix = function () {
  14198. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14199. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14200. return this._projectionMatrix;
  14201. };
  14202. Camera.prototype._getWebVRProjectionMatrix = function () {
  14203. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  14204. //babylon compatible matrix
  14205. [8, 9, 10, 11].forEach(function (num) {
  14206. projectionArray[num] *= -1;
  14207. });
  14208. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  14209. return this._projectionMatrix;
  14210. };
  14211. //Can be used, but we'll use the free camera's view matrix calculation
  14212. Camera.prototype._getWebVRViewMatrix = function () {
  14213. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  14214. //babylon compatible matrix
  14215. [8, 9, 10, 11].forEach(function (num) {
  14216. projectionArray[num] *= -1;
  14217. });
  14218. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  14219. return this._webvrViewMatrix;
  14220. };
  14221. Camera.prototype.setCameraRigParameter = function (name, value) {
  14222. if (!this._cameraRigParams) {
  14223. this._cameraRigParams = {};
  14224. }
  14225. this._cameraRigParams[name] = value;
  14226. //provisionnally:
  14227. if (name === "interaxialDistance") {
  14228. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14229. }
  14230. };
  14231. /**
  14232. * needs to be overridden by children so sub has required properties to be copied
  14233. */
  14234. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14235. return null;
  14236. };
  14237. /**
  14238. * May need to be overridden by children
  14239. */
  14240. Camera.prototype._updateRigCameras = function () {
  14241. for (var i = 0; i < this._rigCameras.length; i++) {
  14242. this._rigCameras[i].minZ = this.minZ;
  14243. this._rigCameras[i].maxZ = this.maxZ;
  14244. this._rigCameras[i].fov = this.fov;
  14245. }
  14246. // only update viewport when ANAGLYPH
  14247. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14248. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14249. }
  14250. };
  14251. Camera.prototype._setupInputs = function () {
  14252. };
  14253. Camera.prototype.serialize = function () {
  14254. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14255. // Type
  14256. serializationObject.type = this.getClassName();
  14257. // Parent
  14258. if (this.parent) {
  14259. serializationObject.parentId = this.parent.id;
  14260. }
  14261. if (this.inputs) {
  14262. this.inputs.serialize(serializationObject);
  14263. }
  14264. // Animations
  14265. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14266. serializationObject.ranges = this.serializeAnimationRanges();
  14267. return serializationObject;
  14268. };
  14269. Camera.prototype.clone = function (name) {
  14270. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14271. };
  14272. Camera.prototype.getDirection = function (localAxis) {
  14273. var result = BABYLON.Vector3.Zero();
  14274. this.getDirectionToRef(localAxis, result);
  14275. return result;
  14276. };
  14277. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14278. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14279. };
  14280. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14281. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14282. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14283. switch (type) {
  14284. case "ArcRotateCamera":
  14285. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14286. case "DeviceOrientationCamera":
  14287. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14288. case "FollowCamera":
  14289. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14290. case "ArcFollowCamera":
  14291. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14292. case "GamepadCamera":
  14293. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14294. case "TouchCamera":
  14295. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14296. case "VirtualJoysticksCamera":
  14297. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14298. case "HolographicCamera":
  14299. return function () { return new BABYLON.HolographicCamera(name, scene); };
  14300. case "WebVRFreeCamera":
  14301. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14302. case "VRDeviceOrientationFreeCamera":
  14303. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14304. case "VRDeviceOrientationGamepadCamera":
  14305. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14306. case "AnaglyphArcRotateCamera":
  14307. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14308. case "AnaglyphFreeCamera":
  14309. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14310. case "AnaglyphGamepadCamera":
  14311. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14312. case "AnaglyphUniversalCamera":
  14313. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14314. case "StereoscopicArcRotateCamera":
  14315. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14316. case "StereoscopicFreeCamera":
  14317. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14318. case "StereoscopicGamepadCamera":
  14319. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14320. case "StereoscopicUniversalCamera":
  14321. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14322. case "FreeCamera":
  14323. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14324. default:
  14325. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14326. }
  14327. };
  14328. Camera.Parse = function (parsedCamera, scene) {
  14329. var type = parsedCamera.type;
  14330. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14331. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14332. // Parent
  14333. if (parsedCamera.parentId) {
  14334. camera._waitingParentId = parsedCamera.parentId;
  14335. }
  14336. //If camera has an input manager, let it parse inputs settings
  14337. if (camera.inputs) {
  14338. camera.inputs.parse(parsedCamera);
  14339. camera._setupInputs();
  14340. }
  14341. // Target
  14342. if (parsedCamera.target) {
  14343. if (camera.setTarget) {
  14344. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14345. }
  14346. }
  14347. // Apply 3d rig, when found
  14348. if (parsedCamera.cameraRigMode) {
  14349. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14350. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14351. }
  14352. // Animations
  14353. if (parsedCamera.animations) {
  14354. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14355. var parsedAnimation = parsedCamera.animations[animationIndex];
  14356. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14357. }
  14358. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14359. }
  14360. if (parsedCamera.autoAnimate) {
  14361. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14362. }
  14363. return camera;
  14364. };
  14365. return Camera;
  14366. }(BABYLON.Node));
  14367. // Statics
  14368. Camera._PERSPECTIVE_CAMERA = 0;
  14369. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14370. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14371. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14372. Camera._RIG_MODE_NONE = 0;
  14373. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14374. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14375. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14376. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14377. Camera._RIG_MODE_VR = 20;
  14378. Camera._RIG_MODE_WEBVR = 21;
  14379. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14380. __decorate([
  14381. BABYLON.serializeAsVector3()
  14382. ], Camera.prototype, "position", void 0);
  14383. __decorate([
  14384. BABYLON.serializeAsVector3()
  14385. ], Camera.prototype, "upVector", void 0);
  14386. __decorate([
  14387. BABYLON.serialize()
  14388. ], Camera.prototype, "orthoLeft", void 0);
  14389. __decorate([
  14390. BABYLON.serialize()
  14391. ], Camera.prototype, "orthoRight", void 0);
  14392. __decorate([
  14393. BABYLON.serialize()
  14394. ], Camera.prototype, "orthoBottom", void 0);
  14395. __decorate([
  14396. BABYLON.serialize()
  14397. ], Camera.prototype, "orthoTop", void 0);
  14398. __decorate([
  14399. BABYLON.serialize()
  14400. ], Camera.prototype, "fov", void 0);
  14401. __decorate([
  14402. BABYLON.serialize()
  14403. ], Camera.prototype, "minZ", void 0);
  14404. __decorate([
  14405. BABYLON.serialize()
  14406. ], Camera.prototype, "maxZ", void 0);
  14407. __decorate([
  14408. BABYLON.serialize()
  14409. ], Camera.prototype, "inertia", void 0);
  14410. __decorate([
  14411. BABYLON.serialize()
  14412. ], Camera.prototype, "mode", void 0);
  14413. __decorate([
  14414. BABYLON.serialize()
  14415. ], Camera.prototype, "layerMask", void 0);
  14416. __decorate([
  14417. BABYLON.serialize()
  14418. ], Camera.prototype, "fovMode", void 0);
  14419. __decorate([
  14420. BABYLON.serialize()
  14421. ], Camera.prototype, "cameraRigMode", void 0);
  14422. __decorate([
  14423. BABYLON.serialize()
  14424. ], Camera.prototype, "interaxialDistance", void 0);
  14425. __decorate([
  14426. BABYLON.serialize()
  14427. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14428. BABYLON.Camera = Camera;
  14429. })(BABYLON || (BABYLON = {}));
  14430. //# sourceMappingURL=babylon.camera.js.map
  14431. var BABYLON;
  14432. (function (BABYLON) {
  14433. BABYLON.CameraInputTypes = {};
  14434. var CameraInputsManager = (function () {
  14435. function CameraInputsManager(camera) {
  14436. this.attached = {};
  14437. this.camera = camera;
  14438. this.checkInputs = function () { };
  14439. }
  14440. CameraInputsManager.prototype.add = function (input) {
  14441. var type = input.getSimpleName();
  14442. if (this.attached[type]) {
  14443. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  14444. return;
  14445. }
  14446. this.attached[type] = input;
  14447. input.camera = this.camera;
  14448. //for checkInputs, we are dynamically creating a function
  14449. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  14450. if (input.checkInputs) {
  14451. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14452. }
  14453. if (this.attachedElement) {
  14454. input.attachControl(this.attachedElement);
  14455. }
  14456. };
  14457. CameraInputsManager.prototype.remove = function (inputToRemove) {
  14458. for (var cam in this.attached) {
  14459. var input = this.attached[cam];
  14460. if (input === inputToRemove) {
  14461. input.detachControl(this.attachedElement);
  14462. delete this.attached[cam];
  14463. this.rebuildInputCheck();
  14464. }
  14465. }
  14466. };
  14467. CameraInputsManager.prototype.removeByType = function (inputType) {
  14468. for (var cam in this.attached) {
  14469. var input = this.attached[cam];
  14470. if (input.getTypeName() === inputType) {
  14471. input.detachControl(this.attachedElement);
  14472. delete this.attached[cam];
  14473. this.rebuildInputCheck();
  14474. }
  14475. }
  14476. };
  14477. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  14478. var current = this.checkInputs;
  14479. return function () {
  14480. current();
  14481. fn();
  14482. };
  14483. };
  14484. CameraInputsManager.prototype.attachInput = function (input) {
  14485. input.attachControl(this.attachedElement, this.noPreventDefault);
  14486. };
  14487. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  14488. if (this.attachedElement) {
  14489. return;
  14490. }
  14491. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  14492. this.attachedElement = element;
  14493. this.noPreventDefault = noPreventDefault;
  14494. for (var cam in this.attached) {
  14495. var input = this.attached[cam];
  14496. this.attached[cam].attachControl(element, noPreventDefault);
  14497. }
  14498. };
  14499. CameraInputsManager.prototype.detachElement = function (element) {
  14500. if (this.attachedElement !== element) {
  14501. return;
  14502. }
  14503. for (var cam in this.attached) {
  14504. var input = this.attached[cam];
  14505. this.attached[cam].detachControl(element);
  14506. }
  14507. this.attachedElement = null;
  14508. };
  14509. CameraInputsManager.prototype.rebuildInputCheck = function () {
  14510. this.checkInputs = function () { };
  14511. for (var cam in this.attached) {
  14512. var input = this.attached[cam];
  14513. if (input.checkInputs) {
  14514. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14515. }
  14516. }
  14517. };
  14518. CameraInputsManager.prototype.clear = function () {
  14519. if (this.attachedElement) {
  14520. this.detachElement(this.attachedElement);
  14521. }
  14522. this.attached = {};
  14523. this.attachedElement = null;
  14524. this.checkInputs = function () { };
  14525. };
  14526. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  14527. var inputs = {};
  14528. for (var cam in this.attached) {
  14529. var input = this.attached[cam];
  14530. var res = BABYLON.SerializationHelper.Serialize(input);
  14531. inputs[input.getTypeName()] = res;
  14532. }
  14533. serializedCamera.inputsmgr = inputs;
  14534. };
  14535. CameraInputsManager.prototype.parse = function (parsedCamera) {
  14536. var parsedInputs = parsedCamera.inputsmgr;
  14537. if (parsedInputs) {
  14538. this.clear();
  14539. for (var n in parsedInputs) {
  14540. var construct = BABYLON.CameraInputTypes[n];
  14541. if (construct) {
  14542. var parsedinput = parsedInputs[n];
  14543. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  14544. this.add(input);
  14545. }
  14546. }
  14547. }
  14548. else {
  14549. //2016-03-08 this part is for managing backward compatibility
  14550. for (var n in this.attached) {
  14551. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  14552. if (construct) {
  14553. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  14554. this.remove(this.attached[n]);
  14555. this.add(input);
  14556. }
  14557. }
  14558. }
  14559. };
  14560. return CameraInputsManager;
  14561. }());
  14562. BABYLON.CameraInputsManager = CameraInputsManager;
  14563. })(BABYLON || (BABYLON = {}));
  14564. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  14565. var BABYLON;
  14566. (function (BABYLON) {
  14567. var FreeCameraMouseInput = (function () {
  14568. function FreeCameraMouseInput(touchEnabled) {
  14569. if (touchEnabled === void 0) { touchEnabled = true; }
  14570. this.touchEnabled = touchEnabled;
  14571. this.buttons = [0, 1, 2];
  14572. this.angularSensibility = 2000.0;
  14573. }
  14574. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  14575. var _this = this;
  14576. var engine = this.camera.getEngine();
  14577. if (!this._pointerInput) {
  14578. this._pointerInput = function (p, s) {
  14579. var evt = p.event;
  14580. if (!_this.touchEnabled && evt.pointerType === "touch") {
  14581. return;
  14582. }
  14583. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14584. return;
  14585. }
  14586. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14587. try {
  14588. evt.srcElement.setPointerCapture(evt.pointerId);
  14589. }
  14590. catch (e) {
  14591. }
  14592. _this.previousPosition = {
  14593. x: evt.clientX,
  14594. y: evt.clientY
  14595. };
  14596. if (!noPreventDefault) {
  14597. evt.preventDefault();
  14598. element.focus();
  14599. }
  14600. }
  14601. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14602. try {
  14603. evt.srcElement.releasePointerCapture(evt.pointerId);
  14604. }
  14605. catch (e) {
  14606. }
  14607. _this.previousPosition = null;
  14608. if (!noPreventDefault) {
  14609. evt.preventDefault();
  14610. }
  14611. }
  14612. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14613. if (!_this.previousPosition || engine.isPointerLock) {
  14614. return;
  14615. }
  14616. var offsetX = evt.clientX - _this.previousPosition.x;
  14617. var offsetY = evt.clientY - _this.previousPosition.y;
  14618. if (_this.camera.getScene().useRightHandedSystem) {
  14619. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14620. }
  14621. else {
  14622. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14623. }
  14624. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14625. _this.previousPosition = {
  14626. x: evt.clientX,
  14627. y: evt.clientY
  14628. };
  14629. if (!noPreventDefault) {
  14630. evt.preventDefault();
  14631. }
  14632. }
  14633. };
  14634. }
  14635. this._onMouseMove = function (evt) {
  14636. if (!engine.isPointerLock) {
  14637. return;
  14638. }
  14639. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14640. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14641. if (_this.camera.getScene().useRightHandedSystem) {
  14642. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14643. }
  14644. else {
  14645. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14646. }
  14647. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14648. _this.previousPosition = null;
  14649. if (!noPreventDefault) {
  14650. evt.preventDefault();
  14651. }
  14652. };
  14653. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14654. element.addEventListener("mousemove", this._onMouseMove, false);
  14655. };
  14656. FreeCameraMouseInput.prototype.detachControl = function (element) {
  14657. if (this._observer && element) {
  14658. this.camera.getScene().onPointerObservable.remove(this._observer);
  14659. element.removeEventListener("mousemove", this._onMouseMove);
  14660. this._observer = null;
  14661. this._onMouseMove = null;
  14662. this.previousPosition = null;
  14663. }
  14664. };
  14665. FreeCameraMouseInput.prototype.getTypeName = function () {
  14666. return "FreeCameraMouseInput";
  14667. };
  14668. FreeCameraMouseInput.prototype.getSimpleName = function () {
  14669. return "mouse";
  14670. };
  14671. return FreeCameraMouseInput;
  14672. }());
  14673. __decorate([
  14674. BABYLON.serialize()
  14675. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  14676. __decorate([
  14677. BABYLON.serialize()
  14678. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  14679. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14680. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14681. })(BABYLON || (BABYLON = {}));
  14682. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14683. var BABYLON;
  14684. (function (BABYLON) {
  14685. var FreeCameraKeyboardMoveInput = (function () {
  14686. function FreeCameraKeyboardMoveInput() {
  14687. this._keys = [];
  14688. this.keysUp = [38];
  14689. this.keysDown = [40];
  14690. this.keysLeft = [37];
  14691. this.keysRight = [39];
  14692. }
  14693. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14694. var _this = this;
  14695. if (!this._onKeyDown) {
  14696. element.tabIndex = 1;
  14697. this._onKeyDown = function (evt) {
  14698. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14699. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14700. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14701. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14702. var index = _this._keys.indexOf(evt.keyCode);
  14703. if (index === -1) {
  14704. _this._keys.push(evt.keyCode);
  14705. }
  14706. if (!noPreventDefault) {
  14707. evt.preventDefault();
  14708. }
  14709. }
  14710. };
  14711. this._onKeyUp = function (evt) {
  14712. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14713. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14714. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14715. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14716. var index = _this._keys.indexOf(evt.keyCode);
  14717. if (index >= 0) {
  14718. _this._keys.splice(index, 1);
  14719. }
  14720. if (!noPreventDefault) {
  14721. evt.preventDefault();
  14722. }
  14723. }
  14724. };
  14725. element.addEventListener("keydown", this._onKeyDown, false);
  14726. element.addEventListener("keyup", this._onKeyUp, false);
  14727. BABYLON.Tools.RegisterTopRootEvents([
  14728. { name: "blur", handler: this._onLostFocus }
  14729. ]);
  14730. }
  14731. };
  14732. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14733. if (this._onKeyDown) {
  14734. element.removeEventListener("keydown", this._onKeyDown);
  14735. element.removeEventListener("keyup", this._onKeyUp);
  14736. BABYLON.Tools.UnregisterTopRootEvents([
  14737. { name: "blur", handler: this._onLostFocus }
  14738. ]);
  14739. this._keys = [];
  14740. this._onKeyDown = null;
  14741. this._onKeyUp = null;
  14742. }
  14743. };
  14744. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14745. if (this._onKeyDown) {
  14746. var camera = this.camera;
  14747. // Keyboard
  14748. for (var index = 0; index < this._keys.length; index++) {
  14749. var keyCode = this._keys[index];
  14750. var speed = camera._computeLocalCameraSpeed();
  14751. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14752. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14753. }
  14754. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14755. camera._localDirection.copyFromFloats(0, 0, speed);
  14756. }
  14757. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14758. camera._localDirection.copyFromFloats(speed, 0, 0);
  14759. }
  14760. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14761. camera._localDirection.copyFromFloats(0, 0, -speed);
  14762. }
  14763. if (camera.getScene().useRightHandedSystem) {
  14764. camera._localDirection.z *= -1;
  14765. }
  14766. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14767. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14768. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14769. }
  14770. }
  14771. };
  14772. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14773. return "FreeCameraKeyboardMoveInput";
  14774. };
  14775. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14776. this._keys = [];
  14777. };
  14778. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14779. return "keyboard";
  14780. };
  14781. return FreeCameraKeyboardMoveInput;
  14782. }());
  14783. __decorate([
  14784. BABYLON.serialize()
  14785. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14786. __decorate([
  14787. BABYLON.serialize()
  14788. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14789. __decorate([
  14790. BABYLON.serialize()
  14791. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14792. __decorate([
  14793. BABYLON.serialize()
  14794. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14795. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14796. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14797. })(BABYLON || (BABYLON = {}));
  14798. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14799. var BABYLON;
  14800. (function (BABYLON) {
  14801. var FreeCameraTouchInput = (function () {
  14802. function FreeCameraTouchInput() {
  14803. this._offsetX = null;
  14804. this._offsetY = null;
  14805. this._pointerCount = 0;
  14806. this._pointerPressed = [];
  14807. this.touchAngularSensibility = 200000.0;
  14808. this.touchMoveSensibility = 250.0;
  14809. }
  14810. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14811. var _this = this;
  14812. var previousPosition;
  14813. if (this._pointerInput === undefined) {
  14814. this._onLostFocus = function (evt) {
  14815. _this._offsetX = null;
  14816. _this._offsetY = null;
  14817. };
  14818. this._pointerInput = function (p, s) {
  14819. var evt = p.event;
  14820. if (evt.pointerType === "mouse") {
  14821. return;
  14822. }
  14823. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14824. if (!noPreventDefault) {
  14825. evt.preventDefault();
  14826. }
  14827. _this._pointerPressed.push(evt.pointerId);
  14828. if (_this._pointerPressed.length !== 1) {
  14829. return;
  14830. }
  14831. previousPosition = {
  14832. x: evt.clientX,
  14833. y: evt.clientY
  14834. };
  14835. }
  14836. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14837. if (!noPreventDefault) {
  14838. evt.preventDefault();
  14839. }
  14840. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14841. if (index === -1) {
  14842. return;
  14843. }
  14844. _this._pointerPressed.splice(index, 1);
  14845. if (index != 0) {
  14846. return;
  14847. }
  14848. previousPosition = null;
  14849. _this._offsetX = null;
  14850. _this._offsetY = null;
  14851. }
  14852. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14853. if (!noPreventDefault) {
  14854. evt.preventDefault();
  14855. }
  14856. if (!previousPosition) {
  14857. return;
  14858. }
  14859. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14860. if (index != 0) {
  14861. return;
  14862. }
  14863. _this._offsetX = evt.clientX - previousPosition.x;
  14864. _this._offsetY = -(evt.clientY - previousPosition.y);
  14865. }
  14866. };
  14867. }
  14868. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14869. element.addEventListener("blur", this._onLostFocus);
  14870. };
  14871. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14872. if (this._pointerInput && element) {
  14873. this.camera.getScene().onPointerObservable.remove(this._observer);
  14874. this._observer = null;
  14875. element.removeEventListener("blur", this._onLostFocus);
  14876. this._onLostFocus = null;
  14877. this._pointerPressed = [];
  14878. this._offsetX = null;
  14879. this._offsetY = null;
  14880. this._pointerCount = 0;
  14881. }
  14882. };
  14883. FreeCameraTouchInput.prototype.checkInputs = function () {
  14884. if (this._offsetX) {
  14885. var camera = this.camera;
  14886. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14887. if (this._pointerPressed.length > 1) {
  14888. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14889. }
  14890. else {
  14891. var speed = camera._computeLocalCameraSpeed();
  14892. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14893. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14894. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14895. }
  14896. }
  14897. };
  14898. FreeCameraTouchInput.prototype.getTypeName = function () {
  14899. return "FreeCameraTouchInput";
  14900. };
  14901. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14902. return "touch";
  14903. };
  14904. return FreeCameraTouchInput;
  14905. }());
  14906. __decorate([
  14907. BABYLON.serialize()
  14908. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14909. __decorate([
  14910. BABYLON.serialize()
  14911. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14912. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14913. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14914. })(BABYLON || (BABYLON = {}));
  14915. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14916. var BABYLON;
  14917. (function (BABYLON) {
  14918. var FreeCameraDeviceOrientationInput = (function () {
  14919. function FreeCameraDeviceOrientationInput() {
  14920. var _this = this;
  14921. this._screenOrientationAngle = 0;
  14922. this._screenQuaternion = new BABYLON.Quaternion();
  14923. this._alpha = 0;
  14924. this._beta = 0;
  14925. this._gamma = 0;
  14926. this._orientationChanged = function () {
  14927. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14928. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14929. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14930. };
  14931. this._deviceOrientation = function (evt) {
  14932. _this._alpha = evt.alpha;
  14933. _this._beta = evt.beta;
  14934. _this._gamma = evt.gamma;
  14935. };
  14936. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14937. this._orientationChanged();
  14938. }
  14939. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14940. get: function () {
  14941. return this._camera;
  14942. },
  14943. set: function (camera) {
  14944. this._camera = camera;
  14945. if (!this._camera.rotationQuaternion)
  14946. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14952. window.addEventListener("orientationchange", this._orientationChanged);
  14953. window.addEventListener("deviceorientation", this._deviceOrientation);
  14954. //In certain cases, the attach control is called AFTER orientation was changed,
  14955. //So this is needed.
  14956. this._orientationChanged();
  14957. };
  14958. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14959. window.removeEventListener("orientationchange", this._orientationChanged);
  14960. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14961. };
  14962. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14963. //if no device orientation provided, don't update the rotation.
  14964. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14965. if (!this._alpha)
  14966. return;
  14967. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14968. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14969. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14970. //Mirror on XY Plane
  14971. this._camera.rotationQuaternion.z *= -1;
  14972. this._camera.rotationQuaternion.w *= -1;
  14973. };
  14974. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14975. return "FreeCameraDeviceOrientationInput";
  14976. };
  14977. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14978. return "deviceOrientation";
  14979. };
  14980. return FreeCameraDeviceOrientationInput;
  14981. }());
  14982. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14983. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14984. })(BABYLON || (BABYLON = {}));
  14985. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14986. var BABYLON;
  14987. (function (BABYLON) {
  14988. var FreeCameraGamepadInput = (function () {
  14989. function FreeCameraGamepadInput() {
  14990. this.gamepadAngularSensibility = 200;
  14991. this.gamepadMoveSensibility = 40;
  14992. }
  14993. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14994. var _this = this;
  14995. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14996. };
  14997. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14998. if (this._gamepads) {
  14999. this._gamepads.dispose();
  15000. }
  15001. this.gamepad = null;
  15002. };
  15003. FreeCameraGamepadInput.prototype.checkInputs = function () {
  15004. if (this.gamepad) {
  15005. var camera = this.camera;
  15006. var LSValues = this.gamepad.leftStick;
  15007. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  15008. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15009. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  15010. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  15011. var RSValues = this.gamepad.rightStick;
  15012. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  15013. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  15014. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  15015. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  15016. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  15017. var speed = camera._computeLocalCameraSpeed() * 50.0;
  15018. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  15019. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  15020. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  15021. }
  15022. };
  15023. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15024. // Only the first gamepad can control the camera
  15025. if (gamepad.index === 0) {
  15026. this.gamepad = gamepad;
  15027. }
  15028. };
  15029. FreeCameraGamepadInput.prototype.getTypeName = function () {
  15030. return "FreeCameraGamepadInput";
  15031. };
  15032. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  15033. return "gamepad";
  15034. };
  15035. return FreeCameraGamepadInput;
  15036. }());
  15037. __decorate([
  15038. BABYLON.serialize()
  15039. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  15040. __decorate([
  15041. BABYLON.serialize()
  15042. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15043. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  15044. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  15045. })(BABYLON || (BABYLON = {}));
  15046. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  15047. var BABYLON;
  15048. (function (BABYLON) {
  15049. var ArcRotateCameraKeyboardMoveInput = (function () {
  15050. function ArcRotateCameraKeyboardMoveInput() {
  15051. this._keys = [];
  15052. this.keysUp = [38];
  15053. this.keysDown = [40];
  15054. this.keysLeft = [37];
  15055. this.keysRight = [39];
  15056. }
  15057. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  15058. var _this = this;
  15059. element.tabIndex = 1;
  15060. this._onKeyDown = function (evt) {
  15061. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  15062. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  15063. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  15064. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  15065. var index = _this._keys.indexOf(evt.keyCode);
  15066. if (index === -1) {
  15067. _this._keys.push(evt.keyCode);
  15068. }
  15069. if (evt.preventDefault) {
  15070. if (!noPreventDefault) {
  15071. evt.preventDefault();
  15072. }
  15073. }
  15074. }
  15075. };
  15076. this._onKeyUp = function (evt) {
  15077. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  15078. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  15079. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  15080. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  15081. var index = _this._keys.indexOf(evt.keyCode);
  15082. if (index >= 0) {
  15083. _this._keys.splice(index, 1);
  15084. }
  15085. if (evt.preventDefault) {
  15086. if (!noPreventDefault) {
  15087. evt.preventDefault();
  15088. }
  15089. }
  15090. }
  15091. };
  15092. this._onLostFocus = function () {
  15093. _this._keys = [];
  15094. };
  15095. element.addEventListener("keydown", this._onKeyDown, false);
  15096. element.addEventListener("keyup", this._onKeyUp, false);
  15097. BABYLON.Tools.RegisterTopRootEvents([
  15098. { name: "blur", handler: this._onLostFocus }
  15099. ]);
  15100. };
  15101. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  15102. if (element) {
  15103. element.removeEventListener("keydown", this._onKeyDown);
  15104. element.removeEventListener("keyup", this._onKeyUp);
  15105. }
  15106. BABYLON.Tools.UnregisterTopRootEvents([
  15107. { name: "blur", handler: this._onLostFocus }
  15108. ]);
  15109. this._keys = [];
  15110. this._onKeyDown = null;
  15111. this._onKeyUp = null;
  15112. this._onLostFocus = null;
  15113. };
  15114. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  15115. if (this._onKeyDown) {
  15116. var camera = this.camera;
  15117. for (var index = 0; index < this._keys.length; index++) {
  15118. var keyCode = this._keys[index];
  15119. if (this.keysLeft.indexOf(keyCode) !== -1) {
  15120. camera.inertialAlphaOffset -= 0.01;
  15121. }
  15122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  15123. camera.inertialBetaOffset -= 0.01;
  15124. }
  15125. else if (this.keysRight.indexOf(keyCode) !== -1) {
  15126. camera.inertialAlphaOffset += 0.01;
  15127. }
  15128. else if (this.keysDown.indexOf(keyCode) !== -1) {
  15129. camera.inertialBetaOffset += 0.01;
  15130. }
  15131. }
  15132. }
  15133. };
  15134. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  15135. return "ArcRotateCameraKeyboardMoveInput";
  15136. };
  15137. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  15138. return "keyboard";
  15139. };
  15140. return ArcRotateCameraKeyboardMoveInput;
  15141. }());
  15142. __decorate([
  15143. BABYLON.serialize()
  15144. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  15145. __decorate([
  15146. BABYLON.serialize()
  15147. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  15148. __decorate([
  15149. BABYLON.serialize()
  15150. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  15151. __decorate([
  15152. BABYLON.serialize()
  15153. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  15154. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  15155. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  15156. })(BABYLON || (BABYLON = {}));
  15157. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  15158. var BABYLON;
  15159. (function (BABYLON) {
  15160. var ArcRotateCameraMouseWheelInput = (function () {
  15161. function ArcRotateCameraMouseWheelInput() {
  15162. this.wheelPrecision = 3.0;
  15163. }
  15164. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  15165. var _this = this;
  15166. this._wheel = function (p, s) {
  15167. //sanity check - this should be a PointerWheel event.
  15168. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  15169. return;
  15170. var event = p.event;
  15171. var delta = 0;
  15172. if (event.wheelDelta) {
  15173. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  15174. }
  15175. else if (event.detail) {
  15176. delta = -event.detail / _this.wheelPrecision;
  15177. }
  15178. if (delta)
  15179. _this.camera.inertialRadiusOffset += delta;
  15180. if (event.preventDefault) {
  15181. if (!noPreventDefault) {
  15182. event.preventDefault();
  15183. }
  15184. }
  15185. };
  15186. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  15187. };
  15188. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  15189. if (this._observer && element) {
  15190. this.camera.getScene().onPointerObservable.remove(this._observer);
  15191. this._observer = null;
  15192. this._wheel = null;
  15193. }
  15194. };
  15195. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  15196. return "ArcRotateCameraMouseWheelInput";
  15197. };
  15198. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  15199. return "mousewheel";
  15200. };
  15201. return ArcRotateCameraMouseWheelInput;
  15202. }());
  15203. __decorate([
  15204. BABYLON.serialize()
  15205. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  15206. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  15207. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  15208. })(BABYLON || (BABYLON = {}));
  15209. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  15210. var BABYLON;
  15211. (function (BABYLON) {
  15212. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15213. var ArcRotateCameraPointersInput = (function () {
  15214. function ArcRotateCameraPointersInput() {
  15215. this.buttons = [0, 1, 2];
  15216. this.angularSensibilityX = 1000.0;
  15217. this.angularSensibilityY = 1000.0;
  15218. this.pinchPrecision = 6.0;
  15219. this.panningSensibility = 50.0;
  15220. this._isPanClick = false;
  15221. this.pinchInwards = true;
  15222. }
  15223. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  15224. var _this = this;
  15225. var engine = this.camera.getEngine();
  15226. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  15227. var pointA, pointB;
  15228. var previousPinchDistance = 0;
  15229. this._pointerInput = function (p, s) {
  15230. var evt = p.event;
  15231. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  15232. return;
  15233. }
  15234. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15235. try {
  15236. evt.srcElement.setPointerCapture(evt.pointerId);
  15237. }
  15238. catch (e) {
  15239. }
  15240. // Manage panning with pan button click
  15241. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  15242. // manage pointers
  15243. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  15244. if (pointA === undefined) {
  15245. pointA = cacheSoloPointer;
  15246. }
  15247. else if (pointB === undefined) {
  15248. pointB = cacheSoloPointer;
  15249. }
  15250. if (!noPreventDefault) {
  15251. evt.preventDefault();
  15252. element.focus();
  15253. }
  15254. }
  15255. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  15256. try {
  15257. evt.srcElement.releasePointerCapture(evt.pointerId);
  15258. }
  15259. catch (e) {
  15260. }
  15261. cacheSoloPointer = null;
  15262. previousPinchDistance = 0;
  15263. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  15264. //but emptying completly pointers collection is required to fix a bug on iPhone :
  15265. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  15266. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  15267. pointA = pointB = undefined;
  15268. if (!noPreventDefault) {
  15269. evt.preventDefault();
  15270. }
  15271. }
  15272. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15273. if (!noPreventDefault) {
  15274. evt.preventDefault();
  15275. }
  15276. // One button down
  15277. if (pointA && pointB === undefined) {
  15278. if (_this.panningSensibility !== 0 &&
  15279. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  15280. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  15281. _this.camera
  15282. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  15283. _this.camera
  15284. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  15285. }
  15286. else {
  15287. var offsetX = evt.clientX - cacheSoloPointer.x;
  15288. var offsetY = evt.clientY - cacheSoloPointer.y;
  15289. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15290. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15291. }
  15292. cacheSoloPointer.x = evt.clientX;
  15293. cacheSoloPointer.y = evt.clientY;
  15294. }
  15295. else if (pointA && pointB) {
  15296. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  15297. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  15298. ed.x = evt.clientX;
  15299. ed.y = evt.clientY;
  15300. var direction = _this.pinchInwards ? 1 : -1;
  15301. var distX = pointA.x - pointB.x;
  15302. var distY = pointA.y - pointB.y;
  15303. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  15304. if (previousPinchDistance === 0) {
  15305. previousPinchDistance = pinchSquaredDistance;
  15306. return;
  15307. }
  15308. if (pinchSquaredDistance !== previousPinchDistance) {
  15309. _this.camera
  15310. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  15311. (_this.pinchPrecision *
  15312. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  15313. direction);
  15314. previousPinchDistance = pinchSquaredDistance;
  15315. }
  15316. }
  15317. }
  15318. };
  15319. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  15320. this._onContextMenu = function (evt) {
  15321. evt.preventDefault();
  15322. };
  15323. if (!this.camera._useCtrlForPanning) {
  15324. element.addEventListener("contextmenu", this._onContextMenu, false);
  15325. }
  15326. this._onLostFocus = function () {
  15327. //this._keys = [];
  15328. pointA = pointB = undefined;
  15329. previousPinchDistance = 0;
  15330. cacheSoloPointer = null;
  15331. };
  15332. this._onMouseMove = function (evt) {
  15333. if (!engine.isPointerLock) {
  15334. return;
  15335. }
  15336. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  15337. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  15338. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15339. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15340. if (!noPreventDefault) {
  15341. evt.preventDefault();
  15342. }
  15343. };
  15344. this._onGestureStart = function (e) {
  15345. if (window.MSGesture === undefined) {
  15346. return;
  15347. }
  15348. if (!_this._MSGestureHandler) {
  15349. _this._MSGestureHandler = new MSGesture();
  15350. _this._MSGestureHandler.target = element;
  15351. }
  15352. _this._MSGestureHandler.addPointer(e.pointerId);
  15353. };
  15354. this._onGesture = function (e) {
  15355. _this.camera.radius *= e.scale;
  15356. if (e.preventDefault) {
  15357. if (!noPreventDefault) {
  15358. e.stopPropagation();
  15359. e.preventDefault();
  15360. }
  15361. }
  15362. };
  15363. element.addEventListener("mousemove", this._onMouseMove, false);
  15364. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  15365. element.addEventListener("MSGestureChange", this._onGesture, false);
  15366. element.addEventListener("keydown", this._onKeyDown, false);
  15367. element.addEventListener("keyup", this._onKeyUp, false);
  15368. BABYLON.Tools.RegisterTopRootEvents([
  15369. { name: "blur", handler: this._onLostFocus }
  15370. ]);
  15371. };
  15372. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  15373. if (element && this._observer) {
  15374. this.camera.getScene().onPointerObservable.remove(this._observer);
  15375. this._observer = null;
  15376. element.removeEventListener("contextmenu", this._onContextMenu);
  15377. element.removeEventListener("mousemove", this._onMouseMove);
  15378. element.removeEventListener("MSPointerDown", this._onGestureStart);
  15379. element.removeEventListener("MSGestureChange", this._onGesture);
  15380. element.removeEventListener("keydown", this._onKeyDown);
  15381. element.removeEventListener("keyup", this._onKeyUp);
  15382. this._isPanClick = false;
  15383. this.pinchInwards = true;
  15384. this._onKeyDown = null;
  15385. this._onKeyUp = null;
  15386. this._onMouseMove = null;
  15387. this._onGestureStart = null;
  15388. this._onGesture = null;
  15389. this._MSGestureHandler = null;
  15390. this._onLostFocus = null;
  15391. this._onContextMenu = null;
  15392. }
  15393. BABYLON.Tools.UnregisterTopRootEvents([
  15394. { name: "blur", handler: this._onLostFocus }
  15395. ]);
  15396. };
  15397. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  15398. return "ArcRotateCameraPointersInput";
  15399. };
  15400. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  15401. return "pointers";
  15402. };
  15403. return ArcRotateCameraPointersInput;
  15404. }());
  15405. __decorate([
  15406. BABYLON.serialize()
  15407. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  15408. __decorate([
  15409. BABYLON.serialize()
  15410. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  15411. __decorate([
  15412. BABYLON.serialize()
  15413. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  15414. __decorate([
  15415. BABYLON.serialize()
  15416. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  15417. __decorate([
  15418. BABYLON.serialize()
  15419. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  15420. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  15421. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  15422. })(BABYLON || (BABYLON = {}));
  15423. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  15424. var BABYLON;
  15425. (function (BABYLON) {
  15426. var ArcRotateCameraGamepadInput = (function () {
  15427. function ArcRotateCameraGamepadInput() {
  15428. this.gamepadRotationSensibility = 80;
  15429. this.gamepadMoveSensibility = 40;
  15430. }
  15431. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  15432. var _this = this;
  15433. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  15434. };
  15435. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  15436. if (this._gamepads) {
  15437. this._gamepads.dispose();
  15438. }
  15439. this.gamepad = null;
  15440. };
  15441. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  15442. if (this.gamepad) {
  15443. var camera = this.camera;
  15444. var RSValues = this.gamepad.rightStick;
  15445. if (RSValues.x != 0) {
  15446. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  15447. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  15448. camera.inertialAlphaOffset += normalizedRX;
  15449. }
  15450. }
  15451. if (RSValues.y != 0) {
  15452. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  15453. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  15454. camera.inertialBetaOffset += normalizedRY;
  15455. }
  15456. }
  15457. var LSValues = this.gamepad.leftStick;
  15458. if (LSValues.y != 0) {
  15459. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15460. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  15461. this.camera.inertialRadiusOffset -= normalizedLY;
  15462. }
  15463. }
  15464. }
  15465. };
  15466. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15467. // Only the first gamepad can control the camera
  15468. if (gamepad.index === 0) {
  15469. this.gamepad = gamepad;
  15470. }
  15471. };
  15472. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  15473. return "ArcRotateCameraGamepadInput";
  15474. };
  15475. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  15476. return "gamepad";
  15477. };
  15478. return ArcRotateCameraGamepadInput;
  15479. }());
  15480. __decorate([
  15481. BABYLON.serialize()
  15482. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  15483. __decorate([
  15484. BABYLON.serialize()
  15485. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15486. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  15487. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  15488. })(BABYLON || (BABYLON = {}));
  15489. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  15490. var BABYLON;
  15491. (function (BABYLON) {
  15492. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  15493. function ArcRotateCameraVRDeviceOrientationInput() {
  15494. this.alphaCorrection = 1;
  15495. this.betaCorrection = 1;
  15496. this.gammaCorrection = 1;
  15497. this._alpha = 0;
  15498. this._beta = 0;
  15499. this._gamma = 0;
  15500. this._dirty = false;
  15501. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15502. }
  15503. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15504. this.camera.attachControl(element, noPreventDefault);
  15505. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15506. };
  15507. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  15508. var camera = this.camera;
  15509. this._alpha = +evt.alpha | 0;
  15510. this._beta = +evt.beta | 0;
  15511. this._gamma = +evt.gamma | 0;
  15512. this._dirty = true;
  15513. };
  15514. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  15515. if (this._dirty) {
  15516. this._dirty = false;
  15517. if (this._gamma < 0) {
  15518. this._gamma = 180 + this._gamma;
  15519. }
  15520. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  15521. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  15522. }
  15523. };
  15524. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  15525. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15526. };
  15527. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  15528. return "ArcRotateCameraVRDeviceOrientationInput";
  15529. };
  15530. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  15531. return "VRDeviceOrientation";
  15532. };
  15533. return ArcRotateCameraVRDeviceOrientationInput;
  15534. }());
  15535. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  15536. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  15537. })(BABYLON || (BABYLON = {}));
  15538. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  15539. var BABYLON;
  15540. (function (BABYLON) {
  15541. var TargetCamera = (function (_super) {
  15542. __extends(TargetCamera, _super);
  15543. function TargetCamera(name, position, scene) {
  15544. var _this = _super.call(this, name, position, scene) || this;
  15545. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15546. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  15547. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  15548. _this.speed = 2.0;
  15549. _this.noRotationConstraint = false;
  15550. _this.lockedTarget = null;
  15551. _this._currentTarget = BABYLON.Vector3.Zero();
  15552. _this._viewMatrix = BABYLON.Matrix.Zero();
  15553. _this._camMatrix = BABYLON.Matrix.Zero();
  15554. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  15555. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  15556. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  15557. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  15558. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  15559. _this._lookAtTemp = BABYLON.Matrix.Zero();
  15560. _this._tempMatrix = BABYLON.Matrix.Zero();
  15561. return _this;
  15562. }
  15563. TargetCamera.prototype.getFrontPosition = function (distance) {
  15564. var direction = this.getTarget().subtract(this.position);
  15565. direction.normalize();
  15566. direction.scaleInPlace(distance);
  15567. return this.globalPosition.add(direction);
  15568. };
  15569. TargetCamera.prototype._getLockedTargetPosition = function () {
  15570. if (!this.lockedTarget) {
  15571. return null;
  15572. }
  15573. if (this.lockedTarget.absolutePosition) {
  15574. this.lockedTarget.computeWorldMatrix();
  15575. }
  15576. return this.lockedTarget.absolutePosition || this.lockedTarget;
  15577. };
  15578. // Cache
  15579. TargetCamera.prototype._initCache = function () {
  15580. _super.prototype._initCache.call(this);
  15581. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15582. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15583. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15584. };
  15585. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  15586. if (!ignoreParentClass) {
  15587. _super.prototype._updateCache.call(this);
  15588. }
  15589. var lockedTargetPosition = this._getLockedTargetPosition();
  15590. if (!lockedTargetPosition) {
  15591. this._cache.lockedTarget = null;
  15592. }
  15593. else {
  15594. if (!this._cache.lockedTarget) {
  15595. this._cache.lockedTarget = lockedTargetPosition.clone();
  15596. }
  15597. else {
  15598. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  15599. }
  15600. }
  15601. this._cache.rotation.copyFrom(this.rotation);
  15602. if (this.rotationQuaternion)
  15603. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15604. };
  15605. // Synchronized
  15606. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  15607. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  15608. return false;
  15609. }
  15610. var lockedTargetPosition = this._getLockedTargetPosition();
  15611. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  15612. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  15613. };
  15614. // Methods
  15615. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  15616. var engine = this.getEngine();
  15617. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  15618. };
  15619. // Target
  15620. TargetCamera.prototype.setTarget = function (target) {
  15621. this.upVector.normalize();
  15622. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  15623. this._camMatrix.invert();
  15624. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  15625. var vDir = target.subtract(this.position);
  15626. if (vDir.x >= 0.0) {
  15627. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  15628. }
  15629. else {
  15630. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  15631. }
  15632. this.rotation.z = 0;
  15633. if (isNaN(this.rotation.x)) {
  15634. this.rotation.x = 0;
  15635. }
  15636. if (isNaN(this.rotation.y)) {
  15637. this.rotation.y = 0;
  15638. }
  15639. if (isNaN(this.rotation.z)) {
  15640. this.rotation.z = 0;
  15641. }
  15642. if (this.rotationQuaternion) {
  15643. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  15644. }
  15645. };
  15646. TargetCamera.prototype.getTarget = function () {
  15647. return this._currentTarget;
  15648. };
  15649. TargetCamera.prototype._decideIfNeedsToMove = function () {
  15650. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15651. };
  15652. TargetCamera.prototype._updatePosition = function () {
  15653. this.position.addInPlace(this.cameraDirection);
  15654. };
  15655. TargetCamera.prototype._checkInputs = function () {
  15656. var needToMove = this._decideIfNeedsToMove();
  15657. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  15658. // Move
  15659. if (needToMove) {
  15660. this._updatePosition();
  15661. }
  15662. // Rotate
  15663. if (needToRotate) {
  15664. this.rotation.x += this.cameraRotation.x;
  15665. this.rotation.y += this.cameraRotation.y;
  15666. if (!this.noRotationConstraint) {
  15667. var limit = (Math.PI / 2) * 0.95;
  15668. if (this.rotation.x > limit)
  15669. this.rotation.x = limit;
  15670. if (this.rotation.x < -limit)
  15671. this.rotation.x = -limit;
  15672. }
  15673. }
  15674. // Inertia
  15675. if (needToMove) {
  15676. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  15677. this.cameraDirection.x = 0;
  15678. }
  15679. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15680. this.cameraDirection.y = 0;
  15681. }
  15682. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15683. this.cameraDirection.z = 0;
  15684. }
  15685. this.cameraDirection.scaleInPlace(this.inertia);
  15686. }
  15687. if (needToRotate) {
  15688. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15689. this.cameraRotation.x = 0;
  15690. }
  15691. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15692. this.cameraRotation.y = 0;
  15693. }
  15694. this.cameraRotation.scaleInPlace(this.inertia);
  15695. }
  15696. _super.prototype._checkInputs.call(this);
  15697. };
  15698. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15699. if (this.rotationQuaternion) {
  15700. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15701. //update the up vector!
  15702. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15703. }
  15704. else {
  15705. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15706. }
  15707. };
  15708. TargetCamera.prototype._getViewMatrix = function () {
  15709. if (!this.lockedTarget) {
  15710. // Compute
  15711. this._updateCameraRotationMatrix();
  15712. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15713. // Computing target and final matrix
  15714. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15715. }
  15716. else {
  15717. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15718. }
  15719. if (this.getScene().useRightHandedSystem) {
  15720. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15721. }
  15722. else {
  15723. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15724. }
  15725. return this._viewMatrix;
  15726. };
  15727. /**
  15728. * @override
  15729. * Override Camera.createRigCamera
  15730. */
  15731. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15732. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15733. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15734. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15735. if (!this.rotationQuaternion) {
  15736. this.rotationQuaternion = new BABYLON.Quaternion();
  15737. }
  15738. rigCamera._cameraRigParams = {};
  15739. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15740. }
  15741. return rigCamera;
  15742. }
  15743. return null;
  15744. };
  15745. /**
  15746. * @override
  15747. * Override Camera._updateRigCameras
  15748. */
  15749. TargetCamera.prototype._updateRigCameras = function () {
  15750. var camLeft = this._rigCameras[0];
  15751. var camRight = this._rigCameras[1];
  15752. switch (this.cameraRigMode) {
  15753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15755. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15756. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15757. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15758. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15759. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15760. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15761. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15762. camLeft.setTarget(this.getTarget());
  15763. camRight.setTarget(this.getTarget());
  15764. break;
  15765. case BABYLON.Camera.RIG_MODE_VR:
  15766. case BABYLON.Camera.RIG_MODE_WEBVR:
  15767. if (camLeft.rotationQuaternion) {
  15768. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15769. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15770. }
  15771. else {
  15772. camLeft.rotation.copyFrom(this.rotation);
  15773. camRight.rotation.copyFrom(this.rotation);
  15774. }
  15775. camLeft.position.copyFrom(this.position);
  15776. camRight.position.copyFrom(this.position);
  15777. break;
  15778. }
  15779. _super.prototype._updateRigCameras.call(this);
  15780. };
  15781. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15782. if (!this._rigCamTransformMatrix) {
  15783. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15784. }
  15785. var target = this.getTarget();
  15786. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15787. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15788. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15789. };
  15790. TargetCamera.prototype.getClassName = function () {
  15791. return "TargetCamera";
  15792. };
  15793. return TargetCamera;
  15794. }(BABYLON.Camera));
  15795. __decorate([
  15796. BABYLON.serializeAsVector3()
  15797. ], TargetCamera.prototype, "rotation", void 0);
  15798. __decorate([
  15799. BABYLON.serialize()
  15800. ], TargetCamera.prototype, "speed", void 0);
  15801. __decorate([
  15802. BABYLON.serializeAsMeshReference("lockedTargetId")
  15803. ], TargetCamera.prototype, "lockedTarget", void 0);
  15804. BABYLON.TargetCamera = TargetCamera;
  15805. })(BABYLON || (BABYLON = {}));
  15806. //# sourceMappingURL=babylon.targetCamera.js.map
  15807. var BABYLON;
  15808. (function (BABYLON) {
  15809. var FreeCamera = (function (_super) {
  15810. __extends(FreeCamera, _super);
  15811. function FreeCamera(name, position, scene) {
  15812. var _this = _super.call(this, name, position, scene) || this;
  15813. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15814. _this.checkCollisions = false;
  15815. _this.applyGravity = false;
  15816. _this._collider = new BABYLON.Collider();
  15817. _this._needMoveForGravity = false;
  15818. _this._oldPosition = BABYLON.Vector3.Zero();
  15819. _this._diffPosition = BABYLON.Vector3.Zero();
  15820. _this._newPosition = BABYLON.Vector3.Zero();
  15821. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15822. if (collidedMesh === void 0) { collidedMesh = null; }
  15823. //TODO move this to the collision coordinator!
  15824. if (_this.getScene().workerCollisions)
  15825. newPosition.multiplyInPlace(_this._collider.radius);
  15826. var updatePosition = function (newPos) {
  15827. _this._newPosition.copyFrom(newPos);
  15828. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15829. var oldPosition = _this.position.clone();
  15830. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15831. _this.position.addInPlace(_this._diffPosition);
  15832. if (_this.onCollide && collidedMesh) {
  15833. _this.onCollide(collidedMesh);
  15834. }
  15835. }
  15836. };
  15837. updatePosition(newPosition);
  15838. };
  15839. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15840. _this.inputs.addKeyboard().addMouse();
  15841. return _this;
  15842. }
  15843. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15844. //-- begin properties for backward compatibility for inputs
  15845. get: function () {
  15846. var mouse = this.inputs.attached["mouse"];
  15847. if (mouse)
  15848. return mouse.angularSensibility;
  15849. },
  15850. set: function (value) {
  15851. var mouse = this.inputs.attached["mouse"];
  15852. if (mouse)
  15853. mouse.angularSensibility = value;
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15859. get: function () {
  15860. var keyboard = this.inputs.attached["keyboard"];
  15861. if (keyboard)
  15862. return keyboard.keysUp;
  15863. },
  15864. set: function (value) {
  15865. var keyboard = this.inputs.attached["keyboard"];
  15866. if (keyboard)
  15867. keyboard.keysUp = value;
  15868. },
  15869. enumerable: true,
  15870. configurable: true
  15871. });
  15872. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15873. get: function () {
  15874. var keyboard = this.inputs.attached["keyboard"];
  15875. if (keyboard)
  15876. return keyboard.keysDown;
  15877. },
  15878. set: function (value) {
  15879. var keyboard = this.inputs.attached["keyboard"];
  15880. if (keyboard)
  15881. keyboard.keysDown = value;
  15882. },
  15883. enumerable: true,
  15884. configurable: true
  15885. });
  15886. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15887. get: function () {
  15888. var keyboard = this.inputs.attached["keyboard"];
  15889. if (keyboard)
  15890. return keyboard.keysLeft;
  15891. },
  15892. set: function (value) {
  15893. var keyboard = this.inputs.attached["keyboard"];
  15894. if (keyboard)
  15895. keyboard.keysLeft = value;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15901. get: function () {
  15902. var keyboard = this.inputs.attached["keyboard"];
  15903. if (keyboard)
  15904. return keyboard.keysRight;
  15905. },
  15906. set: function (value) {
  15907. var keyboard = this.inputs.attached["keyboard"];
  15908. if (keyboard)
  15909. keyboard.keysRight = value;
  15910. },
  15911. enumerable: true,
  15912. configurable: true
  15913. });
  15914. // Controls
  15915. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15916. this.inputs.attachElement(element, noPreventDefault);
  15917. };
  15918. FreeCamera.prototype.detachControl = function (element) {
  15919. this.inputs.detachElement(element);
  15920. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15921. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15922. };
  15923. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15924. var globalPosition;
  15925. if (this.parent) {
  15926. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15927. }
  15928. else {
  15929. globalPosition = this.position;
  15930. }
  15931. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15932. this._collider.radius = this.ellipsoid;
  15933. //no need for clone, as long as gravity is not on.
  15934. var actualVelocity = velocity;
  15935. //add gravity to the velocity to prevent the dual-collision checking
  15936. if (this.applyGravity) {
  15937. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15938. actualVelocity = velocity.add(this.getScene().gravity);
  15939. }
  15940. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15941. };
  15942. FreeCamera.prototype._checkInputs = function () {
  15943. if (!this._localDirection) {
  15944. this._localDirection = BABYLON.Vector3.Zero();
  15945. this._transformedDirection = BABYLON.Vector3.Zero();
  15946. }
  15947. this.inputs.checkInputs();
  15948. _super.prototype._checkInputs.call(this);
  15949. };
  15950. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15951. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15952. };
  15953. FreeCamera.prototype._updatePosition = function () {
  15954. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15955. this._collideWithWorld(this.cameraDirection);
  15956. }
  15957. else {
  15958. this.position.addInPlace(this.cameraDirection);
  15959. }
  15960. };
  15961. FreeCamera.prototype.dispose = function () {
  15962. this.inputs.clear();
  15963. _super.prototype.dispose.call(this);
  15964. };
  15965. FreeCamera.prototype.getClassName = function () {
  15966. return "FreeCamera";
  15967. };
  15968. return FreeCamera;
  15969. }(BABYLON.TargetCamera));
  15970. __decorate([
  15971. BABYLON.serializeAsVector3()
  15972. ], FreeCamera.prototype, "ellipsoid", void 0);
  15973. __decorate([
  15974. BABYLON.serialize()
  15975. ], FreeCamera.prototype, "checkCollisions", void 0);
  15976. __decorate([
  15977. BABYLON.serialize()
  15978. ], FreeCamera.prototype, "applyGravity", void 0);
  15979. BABYLON.FreeCamera = FreeCamera;
  15980. })(BABYLON || (BABYLON = {}));
  15981. //# sourceMappingURL=babylon.freeCamera.js.map
  15982. var BABYLON;
  15983. (function (BABYLON) {
  15984. var FreeCameraInputsManager = (function (_super) {
  15985. __extends(FreeCameraInputsManager, _super);
  15986. function FreeCameraInputsManager(camera) {
  15987. return _super.call(this, camera) || this;
  15988. }
  15989. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15990. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15991. return this;
  15992. };
  15993. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15994. if (touchEnabled === void 0) { touchEnabled = true; }
  15995. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15996. return this;
  15997. };
  15998. FreeCameraInputsManager.prototype.addGamepad = function () {
  15999. this.add(new BABYLON.FreeCameraGamepadInput());
  16000. return this;
  16001. };
  16002. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  16003. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  16004. return this;
  16005. };
  16006. FreeCameraInputsManager.prototype.addTouch = function () {
  16007. this.add(new BABYLON.FreeCameraTouchInput());
  16008. return this;
  16009. };
  16010. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  16011. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  16012. return this;
  16013. };
  16014. return FreeCameraInputsManager;
  16015. }(BABYLON.CameraInputsManager));
  16016. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  16017. })(BABYLON || (BABYLON = {}));
  16018. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  16019. var BABYLON;
  16020. (function (BABYLON) {
  16021. var FollowCamera = (function (_super) {
  16022. __extends(FollowCamera, _super);
  16023. function FollowCamera(name, position, scene, lockedTarget) {
  16024. var _this = _super.call(this, name, position, scene) || this;
  16025. _this.radius = 12;
  16026. _this.rotationOffset = 0;
  16027. _this.heightOffset = 4;
  16028. _this.cameraAcceleration = 0.05;
  16029. _this.maxCameraSpeed = 20;
  16030. _this.lockedTarget = lockedTarget;
  16031. return _this;
  16032. }
  16033. FollowCamera.prototype.getRadians = function (degrees) {
  16034. return degrees * Math.PI / 180;
  16035. };
  16036. FollowCamera.prototype.follow = function (cameraTarget) {
  16037. if (!cameraTarget)
  16038. return;
  16039. var yRotation;
  16040. if (cameraTarget.rotationQuaternion) {
  16041. var rotMatrix = new BABYLON.Matrix();
  16042. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  16043. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  16044. }
  16045. else {
  16046. yRotation = cameraTarget.rotation.y;
  16047. }
  16048. var radians = this.getRadians(this.rotationOffset) + yRotation;
  16049. var targetPosition = cameraTarget.getAbsolutePosition();
  16050. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  16051. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  16052. var dx = targetX - this.position.x;
  16053. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  16054. var dz = (targetZ) - this.position.z;
  16055. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  16056. var vy = dy * this.cameraAcceleration;
  16057. var vz = dz * this.cameraAcceleration * 2;
  16058. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  16059. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16060. }
  16061. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  16062. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16063. }
  16064. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  16065. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16066. }
  16067. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  16068. this.setTarget(targetPosition);
  16069. };
  16070. FollowCamera.prototype._checkInputs = function () {
  16071. _super.prototype._checkInputs.call(this);
  16072. this.follow(this.lockedTarget);
  16073. };
  16074. FollowCamera.prototype.getClassName = function () {
  16075. return "FollowCamera";
  16076. };
  16077. return FollowCamera;
  16078. }(BABYLON.TargetCamera));
  16079. __decorate([
  16080. BABYLON.serialize()
  16081. ], FollowCamera.prototype, "radius", void 0);
  16082. __decorate([
  16083. BABYLON.serialize()
  16084. ], FollowCamera.prototype, "rotationOffset", void 0);
  16085. __decorate([
  16086. BABYLON.serialize()
  16087. ], FollowCamera.prototype, "heightOffset", void 0);
  16088. __decorate([
  16089. BABYLON.serialize()
  16090. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  16091. __decorate([
  16092. BABYLON.serialize()
  16093. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  16094. __decorate([
  16095. BABYLON.serializeAsMeshReference("lockedTargetId")
  16096. ], FollowCamera.prototype, "lockedTarget", void 0);
  16097. BABYLON.FollowCamera = FollowCamera;
  16098. var ArcFollowCamera = (function (_super) {
  16099. __extends(ArcFollowCamera, _super);
  16100. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  16101. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16102. _this.alpha = alpha;
  16103. _this.beta = beta;
  16104. _this.radius = radius;
  16105. _this.target = target;
  16106. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  16107. _this.follow();
  16108. return _this;
  16109. }
  16110. ArcFollowCamera.prototype.follow = function () {
  16111. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  16112. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  16113. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  16114. var targetPosition = this.target.getAbsolutePosition();
  16115. this.position = targetPosition.add(this._cartesianCoordinates);
  16116. this.setTarget(targetPosition);
  16117. };
  16118. ArcFollowCamera.prototype._checkInputs = function () {
  16119. _super.prototype._checkInputs.call(this);
  16120. this.follow();
  16121. };
  16122. ArcFollowCamera.prototype.getClassName = function () {
  16123. return "ArcFollowCamera";
  16124. };
  16125. return ArcFollowCamera;
  16126. }(BABYLON.TargetCamera));
  16127. BABYLON.ArcFollowCamera = ArcFollowCamera;
  16128. })(BABYLON || (BABYLON = {}));
  16129. //# sourceMappingURL=babylon.followCamera.js.map
  16130. var BABYLON;
  16131. (function (BABYLON) {
  16132. // We're mainly based on the logic defined into the FreeCamera code
  16133. var TouchCamera = (function (_super) {
  16134. __extends(TouchCamera, _super);
  16135. //-- end properties for backward compatibility for inputs
  16136. function TouchCamera(name, position, scene) {
  16137. var _this = _super.call(this, name, position, scene) || this;
  16138. _this.inputs.addTouch();
  16139. _this._setupInputs();
  16140. return _this;
  16141. }
  16142. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  16143. //-- Begin properties for backward compatibility for inputs
  16144. get: function () {
  16145. var touch = this.inputs.attached["touch"];
  16146. if (touch)
  16147. return touch.touchAngularSensibility;
  16148. },
  16149. set: function (value) {
  16150. var touch = this.inputs.attached["touch"];
  16151. if (touch)
  16152. touch.touchAngularSensibility = value;
  16153. },
  16154. enumerable: true,
  16155. configurable: true
  16156. });
  16157. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  16158. get: function () {
  16159. var touch = this.inputs.attached["touch"];
  16160. if (touch)
  16161. return touch.touchMoveSensibility;
  16162. },
  16163. set: function (value) {
  16164. var touch = this.inputs.attached["touch"];
  16165. if (touch)
  16166. touch.touchMoveSensibility = value;
  16167. },
  16168. enumerable: true,
  16169. configurable: true
  16170. });
  16171. TouchCamera.prototype.getClassName = function () {
  16172. return "TouchCamera";
  16173. };
  16174. TouchCamera.prototype._setupInputs = function () {
  16175. var mouse = this.inputs.attached["mouse"];
  16176. if (mouse) {
  16177. mouse.touchEnabled = false;
  16178. }
  16179. };
  16180. return TouchCamera;
  16181. }(BABYLON.FreeCamera));
  16182. BABYLON.TouchCamera = TouchCamera;
  16183. })(BABYLON || (BABYLON = {}));
  16184. //# sourceMappingURL=babylon.touchCamera.js.map
  16185. var BABYLON;
  16186. (function (BABYLON) {
  16187. var ArcRotateCamera = (function (_super) {
  16188. __extends(ArcRotateCamera, _super);
  16189. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  16190. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16191. _this.inertialAlphaOffset = 0;
  16192. _this.inertialBetaOffset = 0;
  16193. _this.inertialRadiusOffset = 0;
  16194. _this.lowerAlphaLimit = null;
  16195. _this.upperAlphaLimit = null;
  16196. _this.lowerBetaLimit = 0.01;
  16197. _this.upperBetaLimit = Math.PI;
  16198. _this.lowerRadiusLimit = null;
  16199. _this.upperRadiusLimit = null;
  16200. _this.inertialPanningX = 0;
  16201. _this.inertialPanningY = 0;
  16202. //-- end properties for backward compatibility for inputs
  16203. _this.zoomOnFactor = 1;
  16204. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  16205. _this.allowUpsideDown = true;
  16206. _this._viewMatrix = new BABYLON.Matrix();
  16207. // Panning
  16208. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  16209. _this.checkCollisions = false;
  16210. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16211. _this._collider = new BABYLON.Collider();
  16212. _this._previousPosition = BABYLON.Vector3.Zero();
  16213. _this._collisionVelocity = BABYLON.Vector3.Zero();
  16214. _this._newPosition = BABYLON.Vector3.Zero();
  16215. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16216. if (collidedMesh === void 0) { collidedMesh = null; }
  16217. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  16218. newPosition.multiplyInPlace(_this._collider.radius);
  16219. }
  16220. if (!collidedMesh) {
  16221. _this._previousPosition.copyFrom(_this.position);
  16222. }
  16223. else {
  16224. _this.setPosition(newPosition);
  16225. if (_this.onCollide) {
  16226. _this.onCollide(collidedMesh);
  16227. }
  16228. }
  16229. // Recompute because of constraints
  16230. var cosa = Math.cos(_this.alpha);
  16231. var sina = Math.sin(_this.alpha);
  16232. var cosb = Math.cos(_this.beta);
  16233. var sinb = Math.sin(_this.beta);
  16234. if (sinb === 0) {
  16235. sinb = 0.0001;
  16236. }
  16237. var target = _this._getTargetPosition();
  16238. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  16239. _this.position.copyFrom(_this._newPosition);
  16240. var up = _this.upVector;
  16241. if (_this.allowUpsideDown && _this.beta < 0) {
  16242. up = up.clone();
  16243. up = up.negate();
  16244. }
  16245. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  16246. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  16247. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  16248. _this._collisionTriggered = false;
  16249. };
  16250. if (!target) {
  16251. _this.target = BABYLON.Vector3.Zero();
  16252. }
  16253. else {
  16254. _this.target = target;
  16255. }
  16256. _this.alpha = alpha;
  16257. _this.beta = beta;
  16258. _this.radius = radius;
  16259. _this.getViewMatrix();
  16260. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  16261. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  16262. return _this;
  16263. }
  16264. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  16265. //-- begin properties for backward compatibility for inputs
  16266. get: function () {
  16267. var pointers = this.inputs.attached["pointers"];
  16268. if (pointers)
  16269. return pointers.angularSensibilityX;
  16270. },
  16271. set: function (value) {
  16272. var pointers = this.inputs.attached["pointers"];
  16273. if (pointers) {
  16274. pointers.angularSensibilityX = value;
  16275. }
  16276. },
  16277. enumerable: true,
  16278. configurable: true
  16279. });
  16280. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  16281. get: function () {
  16282. var pointers = this.inputs.attached["pointers"];
  16283. if (pointers)
  16284. return pointers.angularSensibilityY;
  16285. },
  16286. set: function (value) {
  16287. var pointers = this.inputs.attached["pointers"];
  16288. if (pointers) {
  16289. pointers.angularSensibilityY = value;
  16290. }
  16291. },
  16292. enumerable: true,
  16293. configurable: true
  16294. });
  16295. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  16296. get: function () {
  16297. var pointers = this.inputs.attached["pointers"];
  16298. if (pointers)
  16299. return pointers.pinchPrecision;
  16300. },
  16301. set: function (value) {
  16302. var pointers = this.inputs.attached["pointers"];
  16303. if (pointers) {
  16304. pointers.pinchPrecision = value;
  16305. }
  16306. },
  16307. enumerable: true,
  16308. configurable: true
  16309. });
  16310. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  16311. get: function () {
  16312. var pointers = this.inputs.attached["pointers"];
  16313. if (pointers)
  16314. return pointers.panningSensibility;
  16315. },
  16316. set: function (value) {
  16317. var pointers = this.inputs.attached["pointers"];
  16318. if (pointers) {
  16319. pointers.panningSensibility = value;
  16320. }
  16321. },
  16322. enumerable: true,
  16323. configurable: true
  16324. });
  16325. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  16326. get: function () {
  16327. var keyboard = this.inputs.attached["keyboard"];
  16328. if (keyboard)
  16329. return keyboard.keysUp;
  16330. },
  16331. set: function (value) {
  16332. var keyboard = this.inputs.attached["keyboard"];
  16333. if (keyboard)
  16334. keyboard.keysUp = value;
  16335. },
  16336. enumerable: true,
  16337. configurable: true
  16338. });
  16339. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  16340. get: function () {
  16341. var keyboard = this.inputs.attached["keyboard"];
  16342. if (keyboard)
  16343. return keyboard.keysDown;
  16344. },
  16345. set: function (value) {
  16346. var keyboard = this.inputs.attached["keyboard"];
  16347. if (keyboard)
  16348. keyboard.keysDown = value;
  16349. },
  16350. enumerable: true,
  16351. configurable: true
  16352. });
  16353. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  16354. get: function () {
  16355. var keyboard = this.inputs.attached["keyboard"];
  16356. if (keyboard)
  16357. return keyboard.keysLeft;
  16358. },
  16359. set: function (value) {
  16360. var keyboard = this.inputs.attached["keyboard"];
  16361. if (keyboard)
  16362. keyboard.keysLeft = value;
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  16368. get: function () {
  16369. var keyboard = this.inputs.attached["keyboard"];
  16370. if (keyboard)
  16371. return keyboard.keysRight;
  16372. },
  16373. set: function (value) {
  16374. var keyboard = this.inputs.attached["keyboard"];
  16375. if (keyboard)
  16376. keyboard.keysRight = value;
  16377. },
  16378. enumerable: true,
  16379. configurable: true
  16380. });
  16381. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  16382. get: function () {
  16383. var mousewheel = this.inputs.attached["mousewheel"];
  16384. if (mousewheel)
  16385. return mousewheel.wheelPrecision;
  16386. },
  16387. set: function (value) {
  16388. var mousewheel = this.inputs.attached["mousewheel"];
  16389. if (mousewheel)
  16390. mousewheel.wheelPrecision = value;
  16391. },
  16392. enumerable: true,
  16393. configurable: true
  16394. });
  16395. // Cache
  16396. ArcRotateCamera.prototype._initCache = function () {
  16397. _super.prototype._initCache.call(this);
  16398. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16399. this._cache.alpha = undefined;
  16400. this._cache.beta = undefined;
  16401. this._cache.radius = undefined;
  16402. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  16403. };
  16404. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  16405. if (!ignoreParentClass) {
  16406. _super.prototype._updateCache.call(this);
  16407. }
  16408. this._cache.target.copyFrom(this._getTargetPosition());
  16409. this._cache.alpha = this.alpha;
  16410. this._cache.beta = this.beta;
  16411. this._cache.radius = this.radius;
  16412. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  16413. };
  16414. ArcRotateCamera.prototype._getTargetPosition = function () {
  16415. if (this.target.getAbsolutePosition) {
  16416. var pos = this.target.getAbsolutePosition();
  16417. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  16418. }
  16419. return this.target;
  16420. };
  16421. // Synchronized
  16422. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  16423. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  16424. return false;
  16425. return this._cache.target.equals(this.target)
  16426. && this._cache.alpha === this.alpha
  16427. && this._cache.beta === this.beta
  16428. && this._cache.radius === this.radius
  16429. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  16430. };
  16431. // Methods
  16432. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  16433. var _this = this;
  16434. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  16435. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  16436. this._useCtrlForPanning = useCtrlForPanning;
  16437. this._panningMouseButton = panningMouseButton;
  16438. this.inputs.attachElement(element, noPreventDefault);
  16439. this._reset = function () {
  16440. _this.inertialAlphaOffset = 0;
  16441. _this.inertialBetaOffset = 0;
  16442. _this.inertialRadiusOffset = 0;
  16443. };
  16444. };
  16445. ArcRotateCamera.prototype.detachControl = function (element) {
  16446. this.inputs.detachElement(element);
  16447. if (this._reset) {
  16448. this._reset();
  16449. }
  16450. };
  16451. ArcRotateCamera.prototype._checkInputs = function () {
  16452. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  16453. if (this._collisionTriggered) {
  16454. return;
  16455. }
  16456. this.inputs.checkInputs();
  16457. // Inertia
  16458. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  16459. if (this.getScene().useRightHandedSystem) {
  16460. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16461. }
  16462. else {
  16463. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16464. }
  16465. this.beta += this.inertialBetaOffset;
  16466. this.radius -= this.inertialRadiusOffset;
  16467. this.inertialAlphaOffset *= this.inertia;
  16468. this.inertialBetaOffset *= this.inertia;
  16469. this.inertialRadiusOffset *= this.inertia;
  16470. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  16471. this.inertialAlphaOffset = 0;
  16472. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  16473. this.inertialBetaOffset = 0;
  16474. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  16475. this.inertialRadiusOffset = 0;
  16476. }
  16477. // Panning inertia
  16478. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  16479. if (!this._localDirection) {
  16480. this._localDirection = BABYLON.Vector3.Zero();
  16481. this._transformedDirection = BABYLON.Vector3.Zero();
  16482. }
  16483. this.inertialPanningX *= this.inertia;
  16484. this.inertialPanningY *= this.inertia;
  16485. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  16486. this.inertialPanningX = 0;
  16487. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  16488. this.inertialPanningY = 0;
  16489. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  16490. this._localDirection.multiplyInPlace(this.panningAxis);
  16491. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  16492. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  16493. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  16494. if (!this.panningAxis.y) {
  16495. this._transformedDirection.y = 0;
  16496. }
  16497. if (!this.target.getAbsolutePosition) {
  16498. this.target.addInPlace(this._transformedDirection);
  16499. }
  16500. }
  16501. // Limits
  16502. this._checkLimits();
  16503. _super.prototype._checkInputs.call(this);
  16504. };
  16505. ArcRotateCamera.prototype._checkLimits = function () {
  16506. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  16507. if (this.allowUpsideDown && this.beta > Math.PI) {
  16508. this.beta = this.beta - (2 * Math.PI);
  16509. }
  16510. }
  16511. else {
  16512. if (this.beta < this.lowerBetaLimit) {
  16513. this.beta = this.lowerBetaLimit;
  16514. }
  16515. }
  16516. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  16517. if (this.allowUpsideDown && this.beta < -Math.PI) {
  16518. this.beta = this.beta + (2 * Math.PI);
  16519. }
  16520. }
  16521. else {
  16522. if (this.beta > this.upperBetaLimit) {
  16523. this.beta = this.upperBetaLimit;
  16524. }
  16525. }
  16526. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  16527. this.alpha = this.lowerAlphaLimit;
  16528. }
  16529. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  16530. this.alpha = this.upperAlphaLimit;
  16531. }
  16532. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  16533. this.radius = this.lowerRadiusLimit;
  16534. }
  16535. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  16536. this.radius = this.upperRadiusLimit;
  16537. }
  16538. };
  16539. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  16540. var radiusv3 = this.position.subtract(this._getTargetPosition());
  16541. this.radius = radiusv3.length();
  16542. // Alpha
  16543. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  16544. if (radiusv3.z < 0) {
  16545. this.alpha = 2 * Math.PI - this.alpha;
  16546. }
  16547. // Beta
  16548. this.beta = Math.acos(radiusv3.y / this.radius);
  16549. this._checkLimits();
  16550. };
  16551. ArcRotateCamera.prototype.setPosition = function (position) {
  16552. if (this.position.equals(position)) {
  16553. return;
  16554. }
  16555. this.position.copyFrom(position);
  16556. this.rebuildAnglesAndRadius();
  16557. };
  16558. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  16559. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  16560. if (allowSamePosition === void 0) { allowSamePosition = false; }
  16561. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  16562. return;
  16563. }
  16564. if (toBoundingCenter && target.getBoundingInfo) {
  16565. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  16566. }
  16567. else {
  16568. this._targetBoundingCenter = null;
  16569. }
  16570. this.target = target;
  16571. this.rebuildAnglesAndRadius();
  16572. };
  16573. ArcRotateCamera.prototype._getViewMatrix = function () {
  16574. // Compute
  16575. var cosa = Math.cos(this.alpha);
  16576. var sina = Math.sin(this.alpha);
  16577. var cosb = Math.cos(this.beta);
  16578. var sinb = Math.sin(this.beta);
  16579. if (sinb === 0) {
  16580. sinb = 0.0001;
  16581. }
  16582. var target = this._getTargetPosition();
  16583. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  16584. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  16585. this._collider.radius = this.collisionRadius;
  16586. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  16587. this._collisionTriggered = true;
  16588. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16589. }
  16590. else {
  16591. this.position.copyFrom(this._newPosition);
  16592. var up = this.upVector;
  16593. if (this.allowUpsideDown && this.beta < 0) {
  16594. up = up.clone();
  16595. up = up.negate();
  16596. }
  16597. if (this.getScene().useRightHandedSystem) {
  16598. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  16599. }
  16600. else {
  16601. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  16602. }
  16603. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  16604. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  16605. }
  16606. this._currentTarget = target;
  16607. return this._viewMatrix;
  16608. };
  16609. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  16610. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16611. meshes = meshes || this.getScene().meshes;
  16612. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  16613. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  16614. this.radius = distance * this.zoomOnFactor;
  16615. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  16616. };
  16617. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  16618. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16619. var meshesOrMinMaxVector;
  16620. var distance;
  16621. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  16622. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  16623. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  16624. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  16625. }
  16626. else {
  16627. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  16628. distance = meshesOrMinMaxVectorAndDistance.distance;
  16629. }
  16630. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  16631. if (!doNotUpdateMaxZ) {
  16632. this.maxZ = distance * 2;
  16633. }
  16634. };
  16635. /**
  16636. * @override
  16637. * Override Camera.createRigCamera
  16638. */
  16639. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  16640. var alphaShift;
  16641. switch (this.cameraRigMode) {
  16642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16645. case BABYLON.Camera.RIG_MODE_VR:
  16646. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  16647. break;
  16648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16649. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  16650. break;
  16651. }
  16652. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  16653. rigCam._cameraRigParams = {};
  16654. return rigCam;
  16655. };
  16656. /**
  16657. * @override
  16658. * Override Camera._updateRigCameras
  16659. */
  16660. ArcRotateCamera.prototype._updateRigCameras = function () {
  16661. var camLeft = this._rigCameras[0];
  16662. var camRight = this._rigCameras[1];
  16663. camLeft.beta = camRight.beta = this.beta;
  16664. camLeft.radius = camRight.radius = this.radius;
  16665. switch (this.cameraRigMode) {
  16666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16668. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16669. case BABYLON.Camera.RIG_MODE_VR:
  16670. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16671. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16672. break;
  16673. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16674. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16675. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16676. break;
  16677. }
  16678. _super.prototype._updateRigCameras.call(this);
  16679. };
  16680. ArcRotateCamera.prototype.dispose = function () {
  16681. this.inputs.clear();
  16682. _super.prototype.dispose.call(this);
  16683. };
  16684. ArcRotateCamera.prototype.getClassName = function () {
  16685. return "ArcRotateCamera";
  16686. };
  16687. return ArcRotateCamera;
  16688. }(BABYLON.TargetCamera));
  16689. __decorate([
  16690. BABYLON.serialize()
  16691. ], ArcRotateCamera.prototype, "alpha", void 0);
  16692. __decorate([
  16693. BABYLON.serialize()
  16694. ], ArcRotateCamera.prototype, "beta", void 0);
  16695. __decorate([
  16696. BABYLON.serialize()
  16697. ], ArcRotateCamera.prototype, "radius", void 0);
  16698. __decorate([
  16699. BABYLON.serializeAsVector3()
  16700. ], ArcRotateCamera.prototype, "target", void 0);
  16701. __decorate([
  16702. BABYLON.serialize()
  16703. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16704. __decorate([
  16705. BABYLON.serialize()
  16706. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16707. __decorate([
  16708. BABYLON.serialize()
  16709. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16710. __decorate([
  16711. BABYLON.serialize()
  16712. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16713. __decorate([
  16714. BABYLON.serialize()
  16715. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16716. __decorate([
  16717. BABYLON.serialize()
  16718. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16719. __decorate([
  16720. BABYLON.serialize()
  16721. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16722. __decorate([
  16723. BABYLON.serialize()
  16724. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16725. __decorate([
  16726. BABYLON.serialize()
  16727. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16728. __decorate([
  16729. BABYLON.serialize()
  16730. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16731. __decorate([
  16732. BABYLON.serialize()
  16733. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16734. __decorate([
  16735. BABYLON.serialize()
  16736. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16737. __decorate([
  16738. BABYLON.serialize()
  16739. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16740. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16741. })(BABYLON || (BABYLON = {}));
  16742. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16743. var BABYLON;
  16744. (function (BABYLON) {
  16745. var ArcRotateCameraInputsManager = (function (_super) {
  16746. __extends(ArcRotateCameraInputsManager, _super);
  16747. function ArcRotateCameraInputsManager(camera) {
  16748. return _super.call(this, camera) || this;
  16749. }
  16750. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16751. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16752. return this;
  16753. };
  16754. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16755. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16756. return this;
  16757. };
  16758. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16759. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16760. return this;
  16761. };
  16762. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16763. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16764. return this;
  16765. };
  16766. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16767. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16768. return this;
  16769. };
  16770. return ArcRotateCameraInputsManager;
  16771. }(BABYLON.CameraInputsManager));
  16772. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16773. })(BABYLON || (BABYLON = {}));
  16774. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16775. var BABYLON;
  16776. (function (BABYLON) {
  16777. var RenderingManager = (function () {
  16778. function RenderingManager(scene) {
  16779. this._renderingGroups = new Array();
  16780. this._autoClearDepthStencil = {};
  16781. this._customOpaqueSortCompareFn = {};
  16782. this._customAlphaTestSortCompareFn = {};
  16783. this._customTransparentSortCompareFn = {};
  16784. this._renderinGroupInfo = null;
  16785. this._scene = scene;
  16786. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16787. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16788. }
  16789. }
  16790. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16791. if (depth === void 0) { depth = true; }
  16792. if (stencil === void 0) { stencil = true; }
  16793. if (this._depthStencilBufferAlreadyCleaned) {
  16794. return;
  16795. }
  16796. this._scene.getEngine().clear(null, false, depth, stencil);
  16797. this._depthStencilBufferAlreadyCleaned = true;
  16798. };
  16799. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16800. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16801. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16802. var info = null;
  16803. if (observable) {
  16804. if (!this._renderinGroupInfo) {
  16805. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16806. }
  16807. info = this._renderinGroupInfo;
  16808. info.scene = this._scene;
  16809. info.camera = this._scene.activeCamera;
  16810. }
  16811. // Dispatch sprites
  16812. if (renderSprites) {
  16813. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16814. var manager = this._scene.spriteManagers[index];
  16815. this.dispatchSprites(manager);
  16816. }
  16817. }
  16818. // Render
  16819. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16820. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16821. var renderingGroup = this._renderingGroups[index];
  16822. if (!renderingGroup && !observable)
  16823. continue;
  16824. this._currentIndex = index;
  16825. var renderingGroupMask = 0;
  16826. // Fire PRECLEAR stage
  16827. if (observable) {
  16828. renderingGroupMask = Math.pow(2, index);
  16829. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16830. info.renderingGroupId = index;
  16831. observable.notifyObservers(info, renderingGroupMask);
  16832. }
  16833. // Clear depth/stencil if needed
  16834. var autoClear = this._autoClearDepthStencil[index];
  16835. if (autoClear && autoClear.autoClear) {
  16836. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16837. }
  16838. if (observable) {
  16839. // Fire PREOPAQUE stage
  16840. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16841. observable.notifyObservers(info, renderingGroupMask);
  16842. // Fire PRETRANSPARENT stage
  16843. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16844. observable.notifyObservers(info, renderingGroupMask);
  16845. }
  16846. if (renderingGroup)
  16847. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16848. // Fire POSTTRANSPARENT stage
  16849. if (observable) {
  16850. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16851. observable.notifyObservers(info, renderingGroupMask);
  16852. }
  16853. }
  16854. };
  16855. RenderingManager.prototype.reset = function () {
  16856. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16857. var renderingGroup = this._renderingGroups[index];
  16858. if (renderingGroup) {
  16859. renderingGroup.prepare();
  16860. }
  16861. }
  16862. };
  16863. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16864. if (!this._renderingGroups[renderingGroupId]) {
  16865. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16866. }
  16867. };
  16868. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16869. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16870. this._prepareRenderingGroup(renderingGroupId);
  16871. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16872. };
  16873. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16874. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16875. this._prepareRenderingGroup(renderingGroupId);
  16876. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16877. };
  16878. RenderingManager.prototype.dispatch = function (subMesh) {
  16879. var mesh = subMesh.getMesh();
  16880. var renderingGroupId = mesh.renderingGroupId || 0;
  16881. this._prepareRenderingGroup(renderingGroupId);
  16882. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16883. };
  16884. /**
  16885. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16886. * This allowed control for front to back rendering or reversly depending of the special needs.
  16887. *
  16888. * @param renderingGroupId The rendering group id corresponding to its index
  16889. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16890. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16891. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16892. */
  16893. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16894. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16895. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16896. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16897. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16898. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16899. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16900. if (this._renderingGroups[renderingGroupId]) {
  16901. var group = this._renderingGroups[renderingGroupId];
  16902. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16903. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16904. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16905. }
  16906. };
  16907. /**
  16908. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16909. *
  16910. * @param renderingGroupId The rendering group id corresponding to its index
  16911. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16912. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16913. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16914. */
  16915. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16916. if (depth === void 0) { depth = true; }
  16917. if (stencil === void 0) { stencil = true; }
  16918. this._autoClearDepthStencil[renderingGroupId] = {
  16919. autoClear: autoClearDepthStencil,
  16920. depth: depth,
  16921. stencil: stencil
  16922. };
  16923. };
  16924. return RenderingManager;
  16925. }());
  16926. /**
  16927. * The max id used for rendering groups (not included)
  16928. */
  16929. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16930. /**
  16931. * The min id used for rendering groups (included)
  16932. */
  16933. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16934. BABYLON.RenderingManager = RenderingManager;
  16935. })(BABYLON || (BABYLON = {}));
  16936. //# sourceMappingURL=babylon.renderingManager.js.map
  16937. var BABYLON;
  16938. (function (BABYLON) {
  16939. var RenderingGroup = (function () {
  16940. /**
  16941. * Creates a new rendering group.
  16942. * @param index The rendering group index
  16943. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16944. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16945. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16946. */
  16947. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16948. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16949. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16950. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16951. this.index = index;
  16952. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16953. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16954. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16955. this._particleSystems = new BABYLON.SmartArray(256);
  16956. this._spriteManagers = new BABYLON.SmartArray(256);
  16957. this._scene = scene;
  16958. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16959. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16960. this.transparentSortCompareFn = transparentSortCompareFn;
  16961. }
  16962. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16963. /**
  16964. * Set the opaque sort comparison function.
  16965. * If null the sub meshes will be render in the order they were created
  16966. */
  16967. set: function (value) {
  16968. this._opaqueSortCompareFn = value;
  16969. if (value) {
  16970. this._renderOpaque = this.renderOpaqueSorted;
  16971. }
  16972. else {
  16973. this._renderOpaque = RenderingGroup.renderUnsorted;
  16974. }
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16980. /**
  16981. * Set the alpha test sort comparison function.
  16982. * If null the sub meshes will be render in the order they were created
  16983. */
  16984. set: function (value) {
  16985. this._alphaTestSortCompareFn = value;
  16986. if (value) {
  16987. this._renderAlphaTest = this.renderAlphaTestSorted;
  16988. }
  16989. else {
  16990. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16991. }
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16997. /**
  16998. * Set the transparent sort comparison function.
  16999. * If null the sub meshes will be render in the order they were created
  17000. */
  17001. set: function (value) {
  17002. if (value) {
  17003. this._transparentSortCompareFn = value;
  17004. }
  17005. else {
  17006. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17007. }
  17008. this._renderTransparent = this.renderTransparentSorted;
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. /**
  17014. * Render all the sub meshes contained in the group.
  17015. * @param customRenderFunction Used to override the default render behaviour of the group.
  17016. * @returns true if rendered some submeshes.
  17017. */
  17018. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17019. if (customRenderFunction) {
  17020. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  17021. return;
  17022. }
  17023. var engine = this._scene.getEngine();
  17024. // Opaque
  17025. if (this._opaqueSubMeshes.length !== 0) {
  17026. this._renderOpaque(this._opaqueSubMeshes);
  17027. }
  17028. // Alpha test
  17029. if (this._alphaTestSubMeshes.length !== 0) {
  17030. engine.setAlphaTesting(true);
  17031. this._renderAlphaTest(this._alphaTestSubMeshes);
  17032. engine.setAlphaTesting(false);
  17033. }
  17034. // Sprites
  17035. if (renderSprites) {
  17036. this._renderSprites();
  17037. }
  17038. // Particles
  17039. if (renderParticles) {
  17040. this._renderParticles(activeMeshes);
  17041. }
  17042. if (this.onBeforeTransparentRendering) {
  17043. this.onBeforeTransparentRendering();
  17044. }
  17045. // Transparent
  17046. if (this._transparentSubMeshes.length !== 0) {
  17047. this._renderTransparent(this._transparentSubMeshes);
  17048. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17049. }
  17050. };
  17051. /**
  17052. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17053. * @param subMeshes The submeshes to render
  17054. */
  17055. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17056. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  17057. };
  17058. /**
  17059. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17060. * @param subMeshes The submeshes to render
  17061. */
  17062. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17063. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  17064. };
  17065. /**
  17066. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17067. * @param subMeshes The submeshes to render
  17068. */
  17069. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17070. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  17071. };
  17072. /**
  17073. * Renders the submeshes in a specified order.
  17074. * @param subMeshes The submeshes to sort before render
  17075. * @param sortCompareFn The comparison function use to sort
  17076. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17077. * @param transparent Specifies to activate blending if true
  17078. */
  17079. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  17080. var subIndex = 0;
  17081. var subMesh;
  17082. for (; subIndex < subMeshes.length; subIndex++) {
  17083. subMesh = subMeshes.data[subIndex];
  17084. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17085. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17086. }
  17087. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17088. sortedArray.sort(sortCompareFn);
  17089. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17090. subMesh = sortedArray[subIndex];
  17091. subMesh.render(transparent);
  17092. }
  17093. };
  17094. /**
  17095. * Renders the submeshes in the order they were dispatched (no sort applied).
  17096. * @param subMeshes The submeshes to render
  17097. */
  17098. RenderingGroup.renderUnsorted = function (subMeshes) {
  17099. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17100. var submesh = subMeshes.data[subIndex];
  17101. submesh.render(false);
  17102. }
  17103. };
  17104. /**
  17105. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17106. * are rendered back to front if in the same alpha index.
  17107. *
  17108. * @param a The first submesh
  17109. * @param b The second submesh
  17110. * @returns The result of the comparison
  17111. */
  17112. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17113. // Alpha index first
  17114. if (a._alphaIndex > b._alphaIndex) {
  17115. return 1;
  17116. }
  17117. if (a._alphaIndex < b._alphaIndex) {
  17118. return -1;
  17119. }
  17120. // Then distance to camera
  17121. return RenderingGroup.backToFrontSortCompare(a, b);
  17122. };
  17123. /**
  17124. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17125. * are rendered back to front.
  17126. *
  17127. * @param a The first submesh
  17128. * @param b The second submesh
  17129. * @returns The result of the comparison
  17130. */
  17131. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17132. // Then distance to camera
  17133. if (a._distanceToCamera < b._distanceToCamera) {
  17134. return 1;
  17135. }
  17136. if (a._distanceToCamera > b._distanceToCamera) {
  17137. return -1;
  17138. }
  17139. return 0;
  17140. };
  17141. /**
  17142. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17143. * are rendered front to back (prevent overdraw).
  17144. *
  17145. * @param a The first submesh
  17146. * @param b The second submesh
  17147. * @returns The result of the comparison
  17148. */
  17149. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17150. // Then distance to camera
  17151. if (a._distanceToCamera < b._distanceToCamera) {
  17152. return -1;
  17153. }
  17154. if (a._distanceToCamera > b._distanceToCamera) {
  17155. return 1;
  17156. }
  17157. return 0;
  17158. };
  17159. /**
  17160. * Resets the different lists of submeshes to prepare a new frame.
  17161. */
  17162. RenderingGroup.prototype.prepare = function () {
  17163. this._opaqueSubMeshes.reset();
  17164. this._transparentSubMeshes.reset();
  17165. this._alphaTestSubMeshes.reset();
  17166. this._particleSystems.reset();
  17167. this._spriteManagers.reset();
  17168. };
  17169. /**
  17170. * Inserts the submesh in its correct queue depending on its material.
  17171. * @param subMesh The submesh to dispatch
  17172. */
  17173. RenderingGroup.prototype.dispatch = function (subMesh) {
  17174. var material = subMesh.getMaterial();
  17175. var mesh = subMesh.getMesh();
  17176. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17177. this._transparentSubMeshes.push(subMesh);
  17178. }
  17179. else if (material.needAlphaTesting()) {
  17180. this._alphaTestSubMeshes.push(subMesh);
  17181. }
  17182. else {
  17183. this._opaqueSubMeshes.push(subMesh); // Opaque
  17184. }
  17185. };
  17186. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17187. this._spriteManagers.push(spriteManager);
  17188. };
  17189. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17190. this._particleSystems.push(particleSystem);
  17191. };
  17192. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17193. if (this._particleSystems.length === 0) {
  17194. return;
  17195. }
  17196. // Particles
  17197. var activeCamera = this._scene.activeCamera;
  17198. this._scene._particlesDuration.beginMonitoring();
  17199. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17200. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17201. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17202. continue;
  17203. }
  17204. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  17205. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17206. }
  17207. }
  17208. this._scene._particlesDuration.endMonitoring(false);
  17209. };
  17210. RenderingGroup.prototype._renderSprites = function () {
  17211. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17212. return;
  17213. }
  17214. // Sprites
  17215. var activeCamera = this._scene.activeCamera;
  17216. this._scene._spritesDuration.beginMonitoring();
  17217. for (var id = 0; id < this._spriteManagers.length; id++) {
  17218. var spriteManager = this._scene.spriteManagers[id];
  17219. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17220. spriteManager.render();
  17221. }
  17222. }
  17223. this._scene._spritesDuration.endMonitoring(false);
  17224. };
  17225. return RenderingGroup;
  17226. }());
  17227. BABYLON.RenderingGroup = RenderingGroup;
  17228. })(BABYLON || (BABYLON = {}));
  17229. //# sourceMappingURL=babylon.renderingGroup.js.map
  17230. var BABYLON;
  17231. (function (BABYLON) {
  17232. var PointerEventTypes = (function () {
  17233. function PointerEventTypes() {
  17234. }
  17235. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  17236. get: function () {
  17237. return PointerEventTypes._POINTERDOWN;
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  17243. get: function () {
  17244. return PointerEventTypes._POINTERUP;
  17245. },
  17246. enumerable: true,
  17247. configurable: true
  17248. });
  17249. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  17250. get: function () {
  17251. return PointerEventTypes._POINTERMOVE;
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  17257. get: function () {
  17258. return PointerEventTypes._POINTERWHEEL;
  17259. },
  17260. enumerable: true,
  17261. configurable: true
  17262. });
  17263. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  17264. get: function () {
  17265. return PointerEventTypes._POINTERPICK;
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. return PointerEventTypes;
  17271. }());
  17272. PointerEventTypes._POINTERDOWN = 0x01;
  17273. PointerEventTypes._POINTERUP = 0x02;
  17274. PointerEventTypes._POINTERMOVE = 0x04;
  17275. PointerEventTypes._POINTERWHEEL = 0x08;
  17276. PointerEventTypes._POINTERPICK = 0x10;
  17277. BABYLON.PointerEventTypes = PointerEventTypes;
  17278. var PointerInfoBase = (function () {
  17279. function PointerInfoBase(type, event) {
  17280. this.type = type;
  17281. this.event = event;
  17282. }
  17283. return PointerInfoBase;
  17284. }());
  17285. BABYLON.PointerInfoBase = PointerInfoBase;
  17286. /**
  17287. * This class is used to store pointer related info for the onPrePointerObservable event.
  17288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  17289. */
  17290. var PointerInfoPre = (function (_super) {
  17291. __extends(PointerInfoPre, _super);
  17292. function PointerInfoPre(type, event, localX, localY) {
  17293. var _this = _super.call(this, type, event) || this;
  17294. _this.skipOnPointerObservable = false;
  17295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  17296. return _this;
  17297. }
  17298. return PointerInfoPre;
  17299. }(PointerInfoBase));
  17300. BABYLON.PointerInfoPre = PointerInfoPre;
  17301. /**
  17302. * This type contains all the data related to a pointer event in Babylon.js.
  17303. * 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.
  17304. */
  17305. var PointerInfo = (function (_super) {
  17306. __extends(PointerInfo, _super);
  17307. function PointerInfo(type, event, pickInfo) {
  17308. var _this = _super.call(this, type, event) || this;
  17309. _this.pickInfo = pickInfo;
  17310. return _this;
  17311. }
  17312. return PointerInfo;
  17313. }(PointerInfoBase));
  17314. BABYLON.PointerInfo = PointerInfo;
  17315. /**
  17316. * This class is used by the onRenderingGroupObservable
  17317. */
  17318. var RenderingGroupInfo = (function () {
  17319. function RenderingGroupInfo() {
  17320. }
  17321. return RenderingGroupInfo;
  17322. }());
  17323. /**
  17324. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17325. * This stage will be fired no matter what
  17326. */
  17327. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17328. /**
  17329. * Called before opaque object are rendered.
  17330. * This stage will be fired only if there's 3D Opaque content to render
  17331. */
  17332. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17333. /**
  17334. * Called after the opaque objects are rendered and before the transparent ones
  17335. * This stage will be fired only if there's 3D transparent content to render
  17336. */
  17337. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17338. /**
  17339. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17340. * This stage will be fired no matter what
  17341. */
  17342. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17343. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17344. /**
  17345. * Represents a scene to be rendered by the engine.
  17346. * @see http://doc.babylonjs.com/page.php?p=21911
  17347. */
  17348. var Scene = (function () {
  17349. /**
  17350. * @constructor
  17351. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17352. */
  17353. function Scene(engine) {
  17354. // Members
  17355. this.autoClear = true;
  17356. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17357. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17358. this.forceWireframe = false;
  17359. this.forcePointsCloud = false;
  17360. this.forceShowBoundingBoxes = false;
  17361. this.animationsEnabled = true;
  17362. this.constantlyUpdateMeshUnderPointer = false;
  17363. this.useRightHandedSystem = false;
  17364. this.hoverCursor = "pointer";
  17365. // Metadata
  17366. this.metadata = null;
  17367. // Events
  17368. /**
  17369. * An event triggered when the scene is disposed.
  17370. * @type {BABYLON.Observable}
  17371. */
  17372. this.onDisposeObservable = new BABYLON.Observable();
  17373. /**
  17374. * An event triggered before rendering the scene
  17375. * @type {BABYLON.Observable}
  17376. */
  17377. this.onBeforeRenderObservable = new BABYLON.Observable();
  17378. /**
  17379. * An event triggered after rendering the scene
  17380. * @type {BABYLON.Observable}
  17381. */
  17382. this.onAfterRenderObservable = new BABYLON.Observable();
  17383. /**
  17384. * An event triggered when the scene is ready
  17385. * @type {BABYLON.Observable}
  17386. */
  17387. this.onReadyObservable = new BABYLON.Observable();
  17388. /**
  17389. * An event triggered before rendering a camera
  17390. * @type {BABYLON.Observable}
  17391. */
  17392. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17393. /**
  17394. * An event triggered after rendering a camera
  17395. * @type {BABYLON.Observable}
  17396. */
  17397. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17398. /**
  17399. * An event triggered when a camera is created
  17400. * @type {BABYLON.Observable}
  17401. */
  17402. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17403. /**
  17404. * An event triggered when a camera is removed
  17405. * @type {BABYLON.Observable}
  17406. */
  17407. this.onCameraRemovedObservable = new BABYLON.Observable();
  17408. /**
  17409. * An event triggered when a light is created
  17410. * @type {BABYLON.Observable}
  17411. */
  17412. this.onNewLightAddedObservable = new BABYLON.Observable();
  17413. /**
  17414. * An event triggered when a light is removed
  17415. * @type {BABYLON.Observable}
  17416. */
  17417. this.onLightRemovedObservable = new BABYLON.Observable();
  17418. /**
  17419. * An event triggered when a geometry is created
  17420. * @type {BABYLON.Observable}
  17421. */
  17422. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17423. /**
  17424. * An event triggered when a geometry is removed
  17425. * @type {BABYLON.Observable}
  17426. */
  17427. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17428. /**
  17429. * An event triggered when a mesh is created
  17430. * @type {BABYLON.Observable}
  17431. */
  17432. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17433. /**
  17434. * An event triggered when a mesh is removed
  17435. * @type {BABYLON.Observable}
  17436. */
  17437. this.onMeshRemovedObservable = new BABYLON.Observable();
  17438. /**
  17439. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17440. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17441. * 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)
  17442. */
  17443. this.onRenderingGroupObservable = new BABYLON.Observable();
  17444. // Animations
  17445. this.animations = [];
  17446. /**
  17447. * 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).
  17448. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  17449. */
  17450. this.onPrePointerObservable = new BABYLON.Observable();
  17451. /**
  17452. * Observable event triggered each time an input event is received from the rendering canvas
  17453. */
  17454. this.onPointerObservable = new BABYLON.Observable();
  17455. 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
  17456. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17457. this._startingPointerTime = 0;
  17458. // Fog
  17459. /**
  17460. * is fog enabled on this scene.
  17461. * @type {boolean}
  17462. */
  17463. this.fogEnabled = true;
  17464. this.fogMode = Scene.FOGMODE_NONE;
  17465. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17466. this.fogDensity = 0.1;
  17467. this.fogStart = 0;
  17468. this.fogEnd = 1000.0;
  17469. // Lights
  17470. /**
  17471. * is shadow enabled on this scene.
  17472. * @type {boolean}
  17473. */
  17474. this.shadowsEnabled = true;
  17475. /**
  17476. * is light enabled on this scene.
  17477. * @type {boolean}
  17478. */
  17479. this.lightsEnabled = true;
  17480. /**
  17481. * All of the lights added to this scene.
  17482. * @see BABYLON.Light
  17483. * @type {BABYLON.Light[]}
  17484. */
  17485. this.lights = new Array();
  17486. // Cameras
  17487. /**
  17488. * All of the cameras added to this scene.
  17489. * @see BABYLON.Camera
  17490. * @type {BABYLON.Camera[]}
  17491. */
  17492. this.cameras = new Array();
  17493. this.activeCameras = new Array();
  17494. // Meshes
  17495. /**
  17496. * All of the (abstract) meshes added to this scene.
  17497. * @see BABYLON.AbstractMesh
  17498. * @type {BABYLON.AbstractMesh[]}
  17499. */
  17500. this.meshes = new Array();
  17501. // Geometries
  17502. this._geometries = new Array();
  17503. this.materials = new Array();
  17504. this.multiMaterials = new Array();
  17505. // Textures
  17506. this.texturesEnabled = true;
  17507. this.textures = new Array();
  17508. // Particles
  17509. this.particlesEnabled = true;
  17510. this.particleSystems = new Array();
  17511. // Sprites
  17512. this.spritesEnabled = true;
  17513. this.spriteManagers = new Array();
  17514. // Layers
  17515. this.layers = new Array();
  17516. this.highlightLayers = new Array();
  17517. // Skeletons
  17518. this.skeletonsEnabled = true;
  17519. this.skeletons = new Array();
  17520. // Lens flares
  17521. this.lensFlaresEnabled = true;
  17522. this.lensFlareSystems = new Array();
  17523. // Collisions
  17524. this.collisionsEnabled = true;
  17525. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17526. // Postprocesses
  17527. this.postProcessesEnabled = true;
  17528. // Customs render targets
  17529. this.renderTargetsEnabled = true;
  17530. this.dumpNextRenderTargets = false;
  17531. this.customRenderTargets = new Array();
  17532. // Imported meshes
  17533. this.importedMeshesFiles = new Array();
  17534. // Probes
  17535. this.probesEnabled = true;
  17536. this.reflectionProbes = new Array();
  17537. this._actionManagers = new Array();
  17538. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17539. // Procedural textures
  17540. this.proceduralTexturesEnabled = true;
  17541. this._proceduralTextures = new Array();
  17542. this.soundTracks = new Array();
  17543. this._audioEnabled = true;
  17544. this._headphone = false;
  17545. // Performance counters
  17546. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17547. this._totalLightsCounter = new BABYLON.PerfCounter();
  17548. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17549. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17550. this._totalVertices = new BABYLON.PerfCounter();
  17551. this._activeIndices = new BABYLON.PerfCounter();
  17552. this._activeParticles = new BABYLON.PerfCounter();
  17553. this._lastFrameDuration = new BABYLON.PerfCounter();
  17554. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17555. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17556. this._particlesDuration = new BABYLON.PerfCounter();
  17557. this._renderDuration = new BABYLON.PerfCounter();
  17558. this._spritesDuration = new BABYLON.PerfCounter();
  17559. this._activeBones = new BABYLON.PerfCounter();
  17560. this._animationTime = 0;
  17561. this.animationTimeScale = 1;
  17562. this._renderId = 0;
  17563. this._executeWhenReadyTimeoutId = -1;
  17564. this._intermediateRendering = false;
  17565. this._toBeDisposed = new BABYLON.SmartArray(256);
  17566. this._pendingData = []; //ANY
  17567. this._activeMeshes = new BABYLON.SmartArray(256);
  17568. this._processedMaterials = new BABYLON.SmartArray(256);
  17569. this._renderTargets = new BABYLON.SmartArray(256);
  17570. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17571. this._activeSkeletons = new BABYLON.SmartArray(32);
  17572. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17573. this._activeAnimatables = new Array();
  17574. this._transformMatrix = BABYLON.Matrix.Zero();
  17575. this._edgesRenderers = new BABYLON.SmartArray(16);
  17576. this._uniqueIdCounter = 0;
  17577. this._engine = engine;
  17578. engine.scenes.push(this);
  17579. this._externalData = new BABYLON.StringDictionary();
  17580. this._uid = null;
  17581. this._renderingManager = new BABYLON.RenderingManager(this);
  17582. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17583. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17584. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17585. if (BABYLON.OutlineRenderer) {
  17586. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17587. }
  17588. this.attachControl();
  17589. if (BABYLON.SoundTrack) {
  17590. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17591. }
  17592. //simplification queue
  17593. if (BABYLON.SimplificationQueue) {
  17594. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17595. }
  17596. //collision coordinator initialization. For now legacy per default.
  17597. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17598. }
  17599. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17600. get: function () {
  17601. return Scene._FOGMODE_NONE;
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17607. get: function () {
  17608. return Scene._FOGMODE_EXP;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17614. get: function () {
  17615. return Scene._FOGMODE_EXP2;
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17621. get: function () {
  17622. return Scene._FOGMODE_LINEAR;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. Object.defineProperty(Scene.prototype, "onDispose", {
  17628. set: function (callback) {
  17629. if (this._onDisposeObserver) {
  17630. this.onDisposeObservable.remove(this._onDisposeObserver);
  17631. }
  17632. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17633. },
  17634. enumerable: true,
  17635. configurable: true
  17636. });
  17637. Object.defineProperty(Scene.prototype, "beforeRender", {
  17638. set: function (callback) {
  17639. if (this._onBeforeRenderObserver) {
  17640. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17641. }
  17642. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(Scene.prototype, "afterRender", {
  17648. set: function (callback) {
  17649. if (this._onAfterRenderObserver) {
  17650. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17651. }
  17652. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17658. set: function (callback) {
  17659. if (this._onBeforeCameraRenderObserver) {
  17660. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17661. }
  17662. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17668. set: function (callback) {
  17669. if (this._onAfterCameraRenderObserver) {
  17670. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17671. }
  17672. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17678. get: function () {
  17679. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17680. },
  17681. enumerable: true,
  17682. configurable: true
  17683. });
  17684. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17685. get: function () {
  17686. if (!this._defaultMaterial) {
  17687. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17688. }
  17689. return this._defaultMaterial;
  17690. },
  17691. enumerable: true,
  17692. configurable: true
  17693. });
  17694. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17695. get: function () {
  17696. return this._frustumPlanes;
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. Object.defineProperty(Scene.prototype, "debugLayer", {
  17702. // Properties
  17703. get: function () {
  17704. if (!this._debugLayer) {
  17705. this._debugLayer = new BABYLON.DebugLayer(this);
  17706. }
  17707. return this._debugLayer;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17713. get: function () {
  17714. return this._workerCollisions;
  17715. },
  17716. set: function (enabled) {
  17717. enabled = (enabled && !!Worker);
  17718. this._workerCollisions = enabled;
  17719. if (this.collisionCoordinator) {
  17720. this.collisionCoordinator.destroy();
  17721. }
  17722. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17723. this.collisionCoordinator.init(this);
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17729. get: function () {
  17730. return this._selectionOctree;
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17736. /**
  17737. * The mesh that is currently under the pointer.
  17738. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17739. */
  17740. get: function () {
  17741. return this._pointerOverMesh;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Scene.prototype, "pointerX", {
  17747. /**
  17748. * Current on-screen X position of the pointer
  17749. * @return {number} X position of the pointer
  17750. */
  17751. get: function () {
  17752. return this._pointerX;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(Scene.prototype, "pointerY", {
  17758. /**
  17759. * Current on-screen Y position of the pointer
  17760. * @return {number} Y position of the pointer
  17761. */
  17762. get: function () {
  17763. return this._pointerY;
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Scene.prototype.getCachedMaterial = function () {
  17769. return this._cachedMaterial;
  17770. };
  17771. Scene.prototype.getBoundingBoxRenderer = function () {
  17772. return this._boundingBoxRenderer;
  17773. };
  17774. Scene.prototype.getOutlineRenderer = function () {
  17775. return this._outlineRenderer;
  17776. };
  17777. Scene.prototype.getEngine = function () {
  17778. return this._engine;
  17779. };
  17780. Scene.prototype.getTotalVertices = function () {
  17781. return this._totalVertices.current;
  17782. };
  17783. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17784. get: function () {
  17785. return this._totalVertices;
  17786. },
  17787. enumerable: true,
  17788. configurable: true
  17789. });
  17790. Scene.prototype.getActiveIndices = function () {
  17791. return this._activeIndices.current;
  17792. };
  17793. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17794. get: function () {
  17795. return this._activeIndices;
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Scene.prototype.getActiveParticles = function () {
  17801. return this._activeParticles.current;
  17802. };
  17803. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17804. get: function () {
  17805. return this._activeParticles;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. Scene.prototype.getActiveBones = function () {
  17811. return this._activeBones.current;
  17812. };
  17813. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17814. get: function () {
  17815. return this._activeBones;
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. // Stats
  17821. Scene.prototype.getLastFrameDuration = function () {
  17822. return this._lastFrameDuration.current;
  17823. };
  17824. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17825. get: function () {
  17826. return this._lastFrameDuration;
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17832. return this._evaluateActiveMeshesDuration.current;
  17833. };
  17834. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17835. get: function () {
  17836. return this._evaluateActiveMeshesDuration;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Scene.prototype.getActiveMeshes = function () {
  17842. return this._activeMeshes;
  17843. };
  17844. Scene.prototype.getRenderTargetsDuration = function () {
  17845. return this._renderTargetsDuration.current;
  17846. };
  17847. Scene.prototype.getRenderDuration = function () {
  17848. return this._renderDuration.current;
  17849. };
  17850. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17851. get: function () {
  17852. return this._renderDuration;
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. Scene.prototype.getParticlesDuration = function () {
  17858. return this._particlesDuration.current;
  17859. };
  17860. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17861. get: function () {
  17862. return this._particlesDuration;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Scene.prototype.getSpritesDuration = function () {
  17868. return this._spritesDuration.current;
  17869. };
  17870. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17871. get: function () {
  17872. return this._spritesDuration;
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Scene.prototype.getAnimationRatio = function () {
  17878. return this._animationRatio;
  17879. };
  17880. Scene.prototype.getRenderId = function () {
  17881. return this._renderId;
  17882. };
  17883. Scene.prototype.incrementRenderId = function () {
  17884. this._renderId++;
  17885. };
  17886. Scene.prototype._updatePointerPosition = function (evt) {
  17887. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17888. this._pointerX = evt.clientX - canvasRect.left;
  17889. this._pointerY = evt.clientY - canvasRect.top;
  17890. this._unTranslatedPointerX = this._pointerX;
  17891. this._unTranslatedPointerY = this._pointerY;
  17892. if (this.cameraToUseForPointers) {
  17893. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17894. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17895. }
  17896. };
  17897. // Pointers handling
  17898. /**
  17899. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17900. * @param attachUp defines if you want to attach events to pointerup
  17901. * @param attachDown defines if you want to attach events to pointerdown
  17902. * @param attachMove defines if you want to attach events to pointermove
  17903. */
  17904. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17905. var _this = this;
  17906. if (attachUp === void 0) { attachUp = true; }
  17907. if (attachDown === void 0) { attachDown = true; }
  17908. if (attachMove === void 0) { attachMove = true; }
  17909. var spritePredicate = function (sprite) {
  17910. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17911. };
  17912. this._onPointerMove = function (evt) {
  17913. _this._updatePointerPosition(evt);
  17914. // PreObservable support
  17915. if (_this.onPrePointerObservable.hasObservers()) {
  17916. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17917. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17918. _this.onPrePointerObservable.notifyObservers(pi, type);
  17919. if (pi.skipOnPointerObservable) {
  17920. return;
  17921. }
  17922. }
  17923. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17924. return;
  17925. }
  17926. var canvas = _this._engine.getRenderingCanvas();
  17927. if (!_this.pointerMovePredicate) {
  17928. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17929. }
  17930. // Meshes
  17931. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17932. if (pickResult.hit && pickResult.pickedMesh) {
  17933. _this.setPointerOverSprite(null);
  17934. _this.setPointerOverMesh(pickResult.pickedMesh);
  17935. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17936. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17937. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17938. }
  17939. else {
  17940. canvas.style.cursor = _this.hoverCursor;
  17941. }
  17942. }
  17943. else {
  17944. canvas.style.cursor = "";
  17945. }
  17946. }
  17947. else {
  17948. _this.setPointerOverMesh(null);
  17949. // Sprites
  17950. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17951. if (pickResult.hit && pickResult.pickedSprite) {
  17952. _this.setPointerOverSprite(pickResult.pickedSprite);
  17953. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17954. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17955. }
  17956. else {
  17957. canvas.style.cursor = _this.hoverCursor;
  17958. }
  17959. }
  17960. else {
  17961. _this.setPointerOverSprite(null);
  17962. // Restore pointer
  17963. canvas.style.cursor = "";
  17964. }
  17965. }
  17966. if (_this.onPointerMove) {
  17967. _this.onPointerMove(evt, pickResult);
  17968. }
  17969. if (_this.onPointerObservable.hasObservers()) {
  17970. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17971. var pi = new PointerInfo(type, evt, pickResult);
  17972. _this.onPointerObservable.notifyObservers(pi, type);
  17973. }
  17974. };
  17975. this._onPointerDown = function (evt) {
  17976. _this._updatePointerPosition(evt);
  17977. // PreObservable support
  17978. if (_this.onPrePointerObservable.hasObservers()) {
  17979. var type = PointerEventTypes.POINTERDOWN;
  17980. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17981. _this.onPrePointerObservable.notifyObservers(pi, type);
  17982. if (pi.skipOnPointerObservable) {
  17983. return;
  17984. }
  17985. }
  17986. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17987. return;
  17988. }
  17989. _this._startingPointerPosition.x = _this._pointerX;
  17990. _this._startingPointerPosition.y = _this._pointerY;
  17991. _this._startingPointerTime = new Date().getTime();
  17992. if (!_this.pointerDownPredicate) {
  17993. _this.pointerDownPredicate = function (mesh) {
  17994. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17995. };
  17996. }
  17997. // Meshes
  17998. _this._pickedDownMesh = null;
  17999. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18000. if (pickResult.hit && pickResult.pickedMesh) {
  18001. if (pickResult.pickedMesh.actionManager) {
  18002. _this._pickedDownMesh = pickResult.pickedMesh;
  18003. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  18004. switch (evt.button) {
  18005. case 0:
  18006. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18007. break;
  18008. case 1:
  18009. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18010. break;
  18011. case 2:
  18012. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18013. break;
  18014. }
  18015. if (pickResult.pickedMesh.actionManager) {
  18016. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18017. }
  18018. }
  18019. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18020. var that = _this;
  18021. window.setTimeout(function () {
  18022. 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);
  18023. if (pickResult.hit && pickResult.pickedMesh) {
  18024. if (pickResult.pickedMesh.actionManager) {
  18025. 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)) {
  18026. that._startingPointerTime = 0;
  18027. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18028. }
  18029. }
  18030. }
  18031. }, BABYLON.ActionManager.LongPressDelay);
  18032. }
  18033. }
  18034. }
  18035. if (_this.onPointerDown) {
  18036. _this.onPointerDown(evt, pickResult);
  18037. }
  18038. if (_this.onPointerObservable.hasObservers()) {
  18039. var type = PointerEventTypes.POINTERDOWN;
  18040. var pi = new PointerInfo(type, evt, pickResult);
  18041. _this.onPointerObservable.notifyObservers(pi, type);
  18042. }
  18043. // Sprites
  18044. _this._pickedDownSprite = null;
  18045. if (_this.spriteManagers.length > 0) {
  18046. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  18047. if (pickResult.hit && pickResult.pickedSprite) {
  18048. if (pickResult.pickedSprite.actionManager) {
  18049. _this._pickedDownSprite = pickResult.pickedSprite;
  18050. switch (evt.button) {
  18051. case 0:
  18052. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18053. break;
  18054. case 1:
  18055. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18056. break;
  18057. case 2:
  18058. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18059. break;
  18060. }
  18061. if (pickResult.pickedSprite.actionManager) {
  18062. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18063. }
  18064. }
  18065. }
  18066. }
  18067. };
  18068. this._onPointerUp = function (evt) {
  18069. _this._updatePointerPosition(evt);
  18070. // PreObservable support
  18071. if (_this.onPrePointerObservable.hasObservers()) {
  18072. var type = PointerEventTypes.POINTERUP;
  18073. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18074. _this.onPrePointerObservable.notifyObservers(pi, type);
  18075. if (pi.skipOnPointerObservable) {
  18076. return;
  18077. }
  18078. }
  18079. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18080. return;
  18081. }
  18082. if (!_this.pointerUpPredicate) {
  18083. _this.pointerUpPredicate = function (mesh) {
  18084. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  18085. };
  18086. }
  18087. // Meshes
  18088. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  18089. if (pickResult.hit && pickResult.pickedMesh) {
  18090. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  18091. if (_this.onPointerPick) {
  18092. _this.onPointerPick(evt, pickResult);
  18093. }
  18094. if (_this.onPointerObservable.hasObservers()) {
  18095. var type = PointerEventTypes.POINTERPICK;
  18096. var pi = new PointerInfo(type, evt, pickResult);
  18097. _this.onPointerObservable.notifyObservers(pi, type);
  18098. }
  18099. }
  18100. if (pickResult.pickedMesh.actionManager) {
  18101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18102. if (pickResult.pickedMesh.actionManager) {
  18103. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  18104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18105. }
  18106. }
  18107. }
  18108. }
  18109. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  18110. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  18111. }
  18112. if (_this.onPointerUp) {
  18113. _this.onPointerUp(evt, pickResult);
  18114. }
  18115. if (_this.onPointerObservable.hasObservers()) {
  18116. var type = PointerEventTypes.POINTERUP;
  18117. var pi = new PointerInfo(type, evt, pickResult);
  18118. _this.onPointerObservable.notifyObservers(pi, type);
  18119. }
  18120. _this._startingPointerTime = 0;
  18121. // Sprites
  18122. if (_this.spriteManagers.length > 0) {
  18123. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  18124. if (pickResult.hit && pickResult.pickedSprite) {
  18125. if (pickResult.pickedSprite.actionManager) {
  18126. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18127. if (pickResult.pickedSprite.actionManager) {
  18128. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  18129. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18130. }
  18131. }
  18132. }
  18133. }
  18134. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  18135. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18136. }
  18137. }
  18138. };
  18139. this._onKeyDown = function (evt) {
  18140. if (_this.actionManager) {
  18141. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18142. }
  18143. };
  18144. this._onKeyUp = function (evt) {
  18145. if (_this.actionManager) {
  18146. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18147. }
  18148. };
  18149. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18150. var canvas = this._engine.getRenderingCanvas();
  18151. if (attachMove) {
  18152. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18153. // Wheel
  18154. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18155. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18156. }
  18157. if (attachDown) {
  18158. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18159. }
  18160. if (attachUp) {
  18161. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18162. }
  18163. canvas.tabIndex = 1;
  18164. canvas.addEventListener("keydown", this._onKeyDown, false);
  18165. canvas.addEventListener("keyup", this._onKeyUp, false);
  18166. };
  18167. Scene.prototype.detachControl = function () {
  18168. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18169. var canvas = this._engine.getRenderingCanvas();
  18170. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18171. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18172. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18173. // Wheel
  18174. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18175. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18176. canvas.removeEventListener("keydown", this._onKeyDown);
  18177. canvas.removeEventListener("keyup", this._onKeyUp);
  18178. };
  18179. // Ready
  18180. Scene.prototype.isReady = function () {
  18181. if (this._pendingData.length > 0) {
  18182. return false;
  18183. }
  18184. var index;
  18185. for (index = 0; index < this._geometries.length; index++) {
  18186. var geometry = this._geometries[index];
  18187. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18188. return false;
  18189. }
  18190. }
  18191. for (index = 0; index < this.meshes.length; index++) {
  18192. var mesh = this.meshes[index];
  18193. if (!mesh.isReady()) {
  18194. return false;
  18195. }
  18196. var mat = mesh.material;
  18197. if (mat) {
  18198. if (!mat.isReady(mesh)) {
  18199. return false;
  18200. }
  18201. }
  18202. }
  18203. return true;
  18204. };
  18205. Scene.prototype.resetCachedMaterial = function () {
  18206. this._cachedMaterial = null;
  18207. };
  18208. Scene.prototype.registerBeforeRender = function (func) {
  18209. this.onBeforeRenderObservable.add(func);
  18210. };
  18211. Scene.prototype.unregisterBeforeRender = function (func) {
  18212. this.onBeforeRenderObservable.removeCallback(func);
  18213. };
  18214. Scene.prototype.registerAfterRender = function (func) {
  18215. this.onAfterRenderObservable.add(func);
  18216. };
  18217. Scene.prototype.unregisterAfterRender = function (func) {
  18218. this.onAfterRenderObservable.removeCallback(func);
  18219. };
  18220. Scene.prototype._addPendingData = function (data) {
  18221. this._pendingData.push(data);
  18222. };
  18223. Scene.prototype._removePendingData = function (data) {
  18224. var index = this._pendingData.indexOf(data);
  18225. if (index !== -1) {
  18226. this._pendingData.splice(index, 1);
  18227. }
  18228. };
  18229. Scene.prototype.getWaitingItemsCount = function () {
  18230. return this._pendingData.length;
  18231. };
  18232. /**
  18233. * Registers a function to be executed when the scene is ready.
  18234. * @param {Function} func - the function to be executed.
  18235. */
  18236. Scene.prototype.executeWhenReady = function (func) {
  18237. var _this = this;
  18238. this.onReadyObservable.add(func);
  18239. if (this._executeWhenReadyTimeoutId !== -1) {
  18240. return;
  18241. }
  18242. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18243. _this._checkIsReady();
  18244. }, 150);
  18245. };
  18246. Scene.prototype._checkIsReady = function () {
  18247. var _this = this;
  18248. if (this.isReady()) {
  18249. this.onReadyObservable.notifyObservers(this);
  18250. this.onReadyObservable.clear();
  18251. this._executeWhenReadyTimeoutId = -1;
  18252. return;
  18253. }
  18254. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18255. _this._checkIsReady();
  18256. }, 150);
  18257. };
  18258. // Animations
  18259. /**
  18260. * Will start the animation sequence of a given target
  18261. * @param target - the target
  18262. * @param {number} from - from which frame should animation start
  18263. * @param {number} to - till which frame should animation run.
  18264. * @param {boolean} [loop] - should the animation loop
  18265. * @param {number} [speedRatio] - the speed in which to run the animation
  18266. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18267. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18268. * @return {BABYLON.Animatable} the animatable object created for this animation
  18269. * @see BABYLON.Animatable
  18270. * @see http://doc.babylonjs.com/page.php?p=22081
  18271. */
  18272. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18273. if (speedRatio === void 0) { speedRatio = 1.0; }
  18274. this.stopAnimation(target);
  18275. if (!animatable) {
  18276. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18277. }
  18278. // Local animations
  18279. if (target.animations) {
  18280. animatable.appendAnimations(target, target.animations);
  18281. }
  18282. // Children animations
  18283. if (target.getAnimatables) {
  18284. var animatables = target.getAnimatables();
  18285. for (var index = 0; index < animatables.length; index++) {
  18286. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18287. }
  18288. }
  18289. animatable.reset();
  18290. return animatable;
  18291. };
  18292. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18293. if (speedRatio === undefined) {
  18294. speedRatio = 1.0;
  18295. }
  18296. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18297. return animatable;
  18298. };
  18299. Scene.prototype.getAnimatableByTarget = function (target) {
  18300. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18301. if (this._activeAnimatables[index].target === target) {
  18302. return this._activeAnimatables[index];
  18303. }
  18304. }
  18305. return null;
  18306. };
  18307. Object.defineProperty(Scene.prototype, "Animatables", {
  18308. get: function () {
  18309. return this._activeAnimatables;
  18310. },
  18311. enumerable: true,
  18312. configurable: true
  18313. });
  18314. /**
  18315. * Will stop the animation of the given target
  18316. * @param target - the target
  18317. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18318. * @see beginAnimation
  18319. */
  18320. Scene.prototype.stopAnimation = function (target, animationName) {
  18321. var animatable = this.getAnimatableByTarget(target);
  18322. if (animatable) {
  18323. animatable.stop(animationName);
  18324. }
  18325. };
  18326. Scene.prototype._animate = function () {
  18327. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18328. return;
  18329. }
  18330. // Getting time
  18331. var now = BABYLON.Tools.Now;
  18332. if (!this._animationTimeLast) {
  18333. if (this._pendingData.length > 0) {
  18334. return;
  18335. }
  18336. this._animationTimeLast = now;
  18337. }
  18338. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18339. this._animationTime += deltaTime;
  18340. this._animationTimeLast = now;
  18341. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18342. this._activeAnimatables[index]._animate(this._animationTime);
  18343. }
  18344. };
  18345. // Matrix
  18346. Scene.prototype.getViewMatrix = function () {
  18347. return this._viewMatrix;
  18348. };
  18349. Scene.prototype.getProjectionMatrix = function () {
  18350. return this._projectionMatrix;
  18351. };
  18352. Scene.prototype.getTransformMatrix = function () {
  18353. return this._transformMatrix;
  18354. };
  18355. Scene.prototype.setTransformMatrix = function (view, projection) {
  18356. this._viewMatrix = view;
  18357. this._projectionMatrix = projection;
  18358. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18359. // Update frustum
  18360. if (!this._frustumPlanes) {
  18361. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18362. }
  18363. else {
  18364. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18365. }
  18366. };
  18367. // Methods
  18368. Scene.prototype.addMesh = function (newMesh) {
  18369. newMesh.uniqueId = this._uniqueIdCounter++;
  18370. var position = this.meshes.push(newMesh);
  18371. //notify the collision coordinator
  18372. this.collisionCoordinator.onMeshAdded(newMesh);
  18373. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18374. };
  18375. Scene.prototype.removeMesh = function (toRemove) {
  18376. var index = this.meshes.indexOf(toRemove);
  18377. if (index !== -1) {
  18378. // Remove from the scene if mesh found
  18379. this.meshes.splice(index, 1);
  18380. }
  18381. //notify the collision coordinator
  18382. this.collisionCoordinator.onMeshRemoved(toRemove);
  18383. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18384. return index;
  18385. };
  18386. Scene.prototype.removeSkeleton = function (toRemove) {
  18387. var index = this.skeletons.indexOf(toRemove);
  18388. if (index !== -1) {
  18389. // Remove from the scene if mesh found
  18390. this.skeletons.splice(index, 1);
  18391. }
  18392. return index;
  18393. };
  18394. Scene.prototype.removeLight = function (toRemove) {
  18395. var index = this.lights.indexOf(toRemove);
  18396. if (index !== -1) {
  18397. // Remove from the scene if mesh found
  18398. this.lights.splice(index, 1);
  18399. }
  18400. this.onLightRemovedObservable.notifyObservers(toRemove);
  18401. return index;
  18402. };
  18403. Scene.prototype.removeCamera = function (toRemove) {
  18404. var index = this.cameras.indexOf(toRemove);
  18405. if (index !== -1) {
  18406. // Remove from the scene if mesh found
  18407. this.cameras.splice(index, 1);
  18408. }
  18409. // Remove from activeCameras
  18410. var index2 = this.activeCameras.indexOf(toRemove);
  18411. if (index2 !== -1) {
  18412. // Remove from the scene if mesh found
  18413. this.activeCameras.splice(index2, 1);
  18414. }
  18415. // Reset the activeCamera
  18416. if (this.activeCamera === toRemove) {
  18417. if (this.cameras.length > 0) {
  18418. this.activeCamera = this.cameras[0];
  18419. }
  18420. else {
  18421. this.activeCamera = null;
  18422. }
  18423. }
  18424. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18425. return index;
  18426. };
  18427. Scene.prototype.addLight = function (newLight) {
  18428. newLight.uniqueId = this._uniqueIdCounter++;
  18429. var position = this.lights.push(newLight);
  18430. this.onNewLightAddedObservable.notifyObservers(newLight);
  18431. };
  18432. Scene.prototype.addCamera = function (newCamera) {
  18433. newCamera.uniqueId = this._uniqueIdCounter++;
  18434. var position = this.cameras.push(newCamera);
  18435. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18436. };
  18437. /**
  18438. * Switch active camera
  18439. * @param {Camera} newCamera - new active camera
  18440. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18441. */
  18442. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18443. if (attachControl === void 0) { attachControl = true; }
  18444. var canvas = this._engine.getRenderingCanvas();
  18445. this.activeCamera.detachControl(canvas);
  18446. this.activeCamera = newCamera;
  18447. if (attachControl) {
  18448. newCamera.attachControl(canvas);
  18449. }
  18450. };
  18451. /**
  18452. * sets the active camera of the scene using its ID
  18453. * @param {string} id - the camera's ID
  18454. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18455. * @see activeCamera
  18456. */
  18457. Scene.prototype.setActiveCameraByID = function (id) {
  18458. var camera = this.getCameraByID(id);
  18459. if (camera) {
  18460. this.activeCamera = camera;
  18461. return camera;
  18462. }
  18463. return null;
  18464. };
  18465. /**
  18466. * sets the active camera of the scene using its name
  18467. * @param {string} name - the camera's name
  18468. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18469. * @see activeCamera
  18470. */
  18471. Scene.prototype.setActiveCameraByName = function (name) {
  18472. var camera = this.getCameraByName(name);
  18473. if (camera) {
  18474. this.activeCamera = camera;
  18475. return camera;
  18476. }
  18477. return null;
  18478. };
  18479. /**
  18480. * get a material using its id
  18481. * @param {string} the material's ID
  18482. * @return {BABYLON.Material|null} the material or null if none found.
  18483. */
  18484. Scene.prototype.getMaterialByID = function (id) {
  18485. for (var index = 0; index < this.materials.length; index++) {
  18486. if (this.materials[index].id === id) {
  18487. return this.materials[index];
  18488. }
  18489. }
  18490. return null;
  18491. };
  18492. /**
  18493. * get a material using its name
  18494. * @param {string} the material's name
  18495. * @return {BABYLON.Material|null} the material or null if none found.
  18496. */
  18497. Scene.prototype.getMaterialByName = function (name) {
  18498. for (var index = 0; index < this.materials.length; index++) {
  18499. if (this.materials[index].name === name) {
  18500. return this.materials[index];
  18501. }
  18502. }
  18503. return null;
  18504. };
  18505. Scene.prototype.getLensFlareSystemByName = function (name) {
  18506. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18507. if (this.lensFlareSystems[index].name === name) {
  18508. return this.lensFlareSystems[index];
  18509. }
  18510. }
  18511. return null;
  18512. };
  18513. Scene.prototype.getLensFlareSystemByID = function (id) {
  18514. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18515. if (this.lensFlareSystems[index].id === id) {
  18516. return this.lensFlareSystems[index];
  18517. }
  18518. }
  18519. return null;
  18520. };
  18521. Scene.prototype.getCameraByID = function (id) {
  18522. for (var index = 0; index < this.cameras.length; index++) {
  18523. if (this.cameras[index].id === id) {
  18524. return this.cameras[index];
  18525. }
  18526. }
  18527. return null;
  18528. };
  18529. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18530. for (var index = 0; index < this.cameras.length; index++) {
  18531. if (this.cameras[index].uniqueId === uniqueId) {
  18532. return this.cameras[index];
  18533. }
  18534. }
  18535. return null;
  18536. };
  18537. /**
  18538. * get a camera using its name
  18539. * @param {string} the camera's name
  18540. * @return {BABYLON.Camera|null} the camera or null if none found.
  18541. */
  18542. Scene.prototype.getCameraByName = function (name) {
  18543. for (var index = 0; index < this.cameras.length; index++) {
  18544. if (this.cameras[index].name === name) {
  18545. return this.cameras[index];
  18546. }
  18547. }
  18548. return null;
  18549. };
  18550. /**
  18551. * get a bone using its id
  18552. * @param {string} the bone's id
  18553. * @return {BABYLON.Bone|null} the bone or null if not found
  18554. */
  18555. Scene.prototype.getBoneByID = function (id) {
  18556. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18557. var skeleton = this.skeletons[skeletonIndex];
  18558. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18559. if (skeleton.bones[boneIndex].id === id) {
  18560. return skeleton.bones[boneIndex];
  18561. }
  18562. }
  18563. }
  18564. return null;
  18565. };
  18566. /**
  18567. * get a bone using its id
  18568. * @param {string} the bone's name
  18569. * @return {BABYLON.Bone|null} the bone or null if not found
  18570. */
  18571. Scene.prototype.getBoneByName = function (name) {
  18572. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18573. var skeleton = this.skeletons[skeletonIndex];
  18574. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18575. if (skeleton.bones[boneIndex].name === name) {
  18576. return skeleton.bones[boneIndex];
  18577. }
  18578. }
  18579. }
  18580. return null;
  18581. };
  18582. /**
  18583. * get a light node using its name
  18584. * @param {string} the light's name
  18585. * @return {BABYLON.Light|null} the light or null if none found.
  18586. */
  18587. Scene.prototype.getLightByName = function (name) {
  18588. for (var index = 0; index < this.lights.length; index++) {
  18589. if (this.lights[index].name === name) {
  18590. return this.lights[index];
  18591. }
  18592. }
  18593. return null;
  18594. };
  18595. /**
  18596. * get a light node using its ID
  18597. * @param {string} the light's id
  18598. * @return {BABYLON.Light|null} the light or null if none found.
  18599. */
  18600. Scene.prototype.getLightByID = function (id) {
  18601. for (var index = 0; index < this.lights.length; index++) {
  18602. if (this.lights[index].id === id) {
  18603. return this.lights[index];
  18604. }
  18605. }
  18606. return null;
  18607. };
  18608. /**
  18609. * get a light node using its scene-generated unique ID
  18610. * @param {number} the light's unique id
  18611. * @return {BABYLON.Light|null} the light or null if none found.
  18612. */
  18613. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18614. for (var index = 0; index < this.lights.length; index++) {
  18615. if (this.lights[index].uniqueId === uniqueId) {
  18616. return this.lights[index];
  18617. }
  18618. }
  18619. return null;
  18620. };
  18621. /**
  18622. * get a particle system by id
  18623. * @param id {number} the particle system id
  18624. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  18625. */
  18626. Scene.prototype.getParticleSystemByID = function (id) {
  18627. for (var index = 0; index < this.particleSystems.length; index++) {
  18628. if (this.particleSystems[index].id === id) {
  18629. return this.particleSystems[index];
  18630. }
  18631. }
  18632. return null;
  18633. };
  18634. /**
  18635. * get a geometry using its ID
  18636. * @param {string} the geometry's id
  18637. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18638. */
  18639. Scene.prototype.getGeometryByID = function (id) {
  18640. for (var index = 0; index < this._geometries.length; index++) {
  18641. if (this._geometries[index].id === id) {
  18642. return this._geometries[index];
  18643. }
  18644. }
  18645. return null;
  18646. };
  18647. /**
  18648. * add a new geometry to this scene.
  18649. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18650. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18651. * @return {boolean} was the geometry added or not
  18652. */
  18653. Scene.prototype.pushGeometry = function (geometry, force) {
  18654. if (!force && this.getGeometryByID(geometry.id)) {
  18655. return false;
  18656. }
  18657. this._geometries.push(geometry);
  18658. //notify the collision coordinator
  18659. this.collisionCoordinator.onGeometryAdded(geometry);
  18660. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18661. return true;
  18662. };
  18663. /**
  18664. * Removes an existing geometry
  18665. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18666. * @return {boolean} was the geometry removed or not
  18667. */
  18668. Scene.prototype.removeGeometry = function (geometry) {
  18669. var index = this._geometries.indexOf(geometry);
  18670. if (index > -1) {
  18671. this._geometries.splice(index, 1);
  18672. //notify the collision coordinator
  18673. this.collisionCoordinator.onGeometryDeleted(geometry);
  18674. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18675. return true;
  18676. }
  18677. return false;
  18678. };
  18679. Scene.prototype.getGeometries = function () {
  18680. return this._geometries;
  18681. };
  18682. /**
  18683. * Get the first added mesh found of a given ID
  18684. * @param {string} id - the id to search for
  18685. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18686. */
  18687. Scene.prototype.getMeshByID = function (id) {
  18688. for (var index = 0; index < this.meshes.length; index++) {
  18689. if (this.meshes[index].id === id) {
  18690. return this.meshes[index];
  18691. }
  18692. }
  18693. return null;
  18694. };
  18695. Scene.prototype.getMeshesByID = function (id) {
  18696. return this.meshes.filter(function (m) {
  18697. return m.id === id;
  18698. });
  18699. };
  18700. /**
  18701. * Get a mesh with its auto-generated unique id
  18702. * @param {number} uniqueId - the unique id to search for
  18703. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18704. */
  18705. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18706. for (var index = 0; index < this.meshes.length; index++) {
  18707. if (this.meshes[index].uniqueId === uniqueId) {
  18708. return this.meshes[index];
  18709. }
  18710. }
  18711. return null;
  18712. };
  18713. /**
  18714. * Get a the last added mesh found of a given ID
  18715. * @param {string} id - the id to search for
  18716. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18717. */
  18718. Scene.prototype.getLastMeshByID = function (id) {
  18719. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18720. if (this.meshes[index].id === id) {
  18721. return this.meshes[index];
  18722. }
  18723. }
  18724. return null;
  18725. };
  18726. /**
  18727. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18728. * @param {string} id - the id to search for
  18729. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18730. */
  18731. Scene.prototype.getLastEntryByID = function (id) {
  18732. var index;
  18733. for (index = this.meshes.length - 1; index >= 0; index--) {
  18734. if (this.meshes[index].id === id) {
  18735. return this.meshes[index];
  18736. }
  18737. }
  18738. for (index = this.cameras.length - 1; index >= 0; index--) {
  18739. if (this.cameras[index].id === id) {
  18740. return this.cameras[index];
  18741. }
  18742. }
  18743. for (index = this.lights.length - 1; index >= 0; index--) {
  18744. if (this.lights[index].id === id) {
  18745. return this.lights[index];
  18746. }
  18747. }
  18748. return null;
  18749. };
  18750. Scene.prototype.getNodeByID = function (id) {
  18751. var mesh = this.getMeshByID(id);
  18752. if (mesh) {
  18753. return mesh;
  18754. }
  18755. var light = this.getLightByID(id);
  18756. if (light) {
  18757. return light;
  18758. }
  18759. var camera = this.getCameraByID(id);
  18760. if (camera) {
  18761. return camera;
  18762. }
  18763. var bone = this.getBoneByID(id);
  18764. return bone;
  18765. };
  18766. Scene.prototype.getNodeByName = function (name) {
  18767. var mesh = this.getMeshByName(name);
  18768. if (mesh) {
  18769. return mesh;
  18770. }
  18771. var light = this.getLightByName(name);
  18772. if (light) {
  18773. return light;
  18774. }
  18775. var camera = this.getCameraByName(name);
  18776. if (camera) {
  18777. return camera;
  18778. }
  18779. var bone = this.getBoneByName(name);
  18780. return bone;
  18781. };
  18782. Scene.prototype.getMeshByName = function (name) {
  18783. for (var index = 0; index < this.meshes.length; index++) {
  18784. if (this.meshes[index].name === name) {
  18785. return this.meshes[index];
  18786. }
  18787. }
  18788. return null;
  18789. };
  18790. Scene.prototype.getSoundByName = function (name) {
  18791. var index;
  18792. if (BABYLON.AudioEngine) {
  18793. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18794. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18795. return this.mainSoundTrack.soundCollection[index];
  18796. }
  18797. }
  18798. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18799. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18800. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18801. return this.soundTracks[sdIndex].soundCollection[index];
  18802. }
  18803. }
  18804. }
  18805. }
  18806. return null;
  18807. };
  18808. Scene.prototype.getLastSkeletonByID = function (id) {
  18809. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18810. if (this.skeletons[index].id === id) {
  18811. return this.skeletons[index];
  18812. }
  18813. }
  18814. return null;
  18815. };
  18816. Scene.prototype.getSkeletonById = function (id) {
  18817. for (var index = 0; index < this.skeletons.length; index++) {
  18818. if (this.skeletons[index].id === id) {
  18819. return this.skeletons[index];
  18820. }
  18821. }
  18822. return null;
  18823. };
  18824. Scene.prototype.getSkeletonByName = function (name) {
  18825. for (var index = 0; index < this.skeletons.length; index++) {
  18826. if (this.skeletons[index].name === name) {
  18827. return this.skeletons[index];
  18828. }
  18829. }
  18830. return null;
  18831. };
  18832. Scene.prototype.isActiveMesh = function (mesh) {
  18833. return (this._activeMeshes.indexOf(mesh) !== -1);
  18834. };
  18835. Object.defineProperty(Scene.prototype, "uid", {
  18836. /**
  18837. * Return a unique id as a string which can serve as an identifier for the scene
  18838. */
  18839. get: function () {
  18840. if (!this._uid) {
  18841. this._uid = BABYLON.Tools.RandomId();
  18842. }
  18843. return this._uid;
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. /**
  18849. * Add an externaly attached data from its key.
  18850. * This method call will fail and return false, if such key already exists.
  18851. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18852. * @param key the unique key that identifies the data
  18853. * @param data the data object to associate to the key for this Engine instance
  18854. * @return true if no such key were already present and the data was added successfully, false otherwise
  18855. */
  18856. Scene.prototype.addExternalData = function (key, data) {
  18857. return this._externalData.add(key, data);
  18858. };
  18859. /**
  18860. * Get an externaly attached data from its key
  18861. * @param key the unique key that identifies the data
  18862. * @return the associated data, if present (can be null), or undefined if not present
  18863. */
  18864. Scene.prototype.getExternalData = function (key) {
  18865. return this._externalData.get(key);
  18866. };
  18867. /**
  18868. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18869. * @param key the unique key that identifies the data
  18870. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18871. * @return the associated data, can be null if the factory returned null.
  18872. */
  18873. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18874. return this._externalData.getOrAddWithFactory(key, factory);
  18875. };
  18876. /**
  18877. * Remove an externaly attached data from the Engine instance
  18878. * @param key the unique key that identifies the data
  18879. * @return true if the data was successfully removed, false if it doesn't exist
  18880. */
  18881. Scene.prototype.removeExternalData = function (key) {
  18882. return this._externalData.remove(key);
  18883. };
  18884. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18885. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18886. var material = subMesh.getMaterial();
  18887. if (mesh.showSubMeshesBoundingBox) {
  18888. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18889. }
  18890. if (material) {
  18891. // Render targets
  18892. if (material.getRenderTargetTextures) {
  18893. if (this._processedMaterials.indexOf(material) === -1) {
  18894. this._processedMaterials.push(material);
  18895. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18896. }
  18897. }
  18898. // Dispatch
  18899. this._activeIndices.addCount(subMesh.indexCount, false);
  18900. this._renderingManager.dispatch(subMesh);
  18901. }
  18902. }
  18903. };
  18904. Scene.prototype._isInIntermediateRendering = function () {
  18905. return this._intermediateRendering;
  18906. };
  18907. Scene.prototype._evaluateActiveMeshes = function () {
  18908. this.activeCamera._activeMeshes.reset();
  18909. this._activeMeshes.reset();
  18910. this._renderingManager.reset();
  18911. this._processedMaterials.reset();
  18912. this._activeParticleSystems.reset();
  18913. this._activeSkeletons.reset();
  18914. this._softwareSkinnedMeshes.reset();
  18915. this._boundingBoxRenderer.reset();
  18916. this._edgesRenderers.reset();
  18917. // Meshes
  18918. var meshes;
  18919. var len;
  18920. if (this._selectionOctree) {
  18921. var selection = this._selectionOctree.select(this._frustumPlanes);
  18922. meshes = selection.data;
  18923. len = selection.length;
  18924. }
  18925. else {
  18926. len = this.meshes.length;
  18927. meshes = this.meshes;
  18928. }
  18929. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18930. var mesh = meshes[meshIndex];
  18931. if (mesh.isBlocked) {
  18932. continue;
  18933. }
  18934. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18935. if (!mesh.isReady() || !mesh.isEnabled()) {
  18936. continue;
  18937. }
  18938. mesh.computeWorldMatrix();
  18939. // Intersections
  18940. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18941. this._meshesForIntersections.pushNoDuplicate(mesh);
  18942. }
  18943. // Switch to current LOD
  18944. var meshLOD = mesh.getLOD(this.activeCamera);
  18945. if (!meshLOD) {
  18946. continue;
  18947. }
  18948. mesh._preActivate();
  18949. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18950. this._activeMeshes.push(mesh);
  18951. this.activeCamera._activeMeshes.push(mesh);
  18952. mesh._activate(this._renderId);
  18953. this._activeMesh(mesh, meshLOD);
  18954. }
  18955. }
  18956. // Particle systems
  18957. this._particlesDuration.beginMonitoring();
  18958. var beforeParticlesDate = BABYLON.Tools.Now;
  18959. if (this.particlesEnabled) {
  18960. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18961. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18962. var particleSystem = this.particleSystems[particleIndex];
  18963. if (!particleSystem.isStarted()) {
  18964. continue;
  18965. }
  18966. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18967. this._activeParticleSystems.push(particleSystem);
  18968. particleSystem.animate();
  18969. this._renderingManager.dispatchParticles(particleSystem);
  18970. }
  18971. }
  18972. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18973. }
  18974. this._particlesDuration.endMonitoring(false);
  18975. };
  18976. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18977. if (mesh.skeleton && this.skeletonsEnabled) {
  18978. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18979. mesh.skeleton.prepare();
  18980. }
  18981. if (!mesh.computeBonesUsingShaders) {
  18982. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18983. }
  18984. }
  18985. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18986. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18987. }
  18988. if (sourceMesh._edgesRenderer) {
  18989. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18990. }
  18991. if (mesh && mesh.subMeshes) {
  18992. // Submeshes Octrees
  18993. var len;
  18994. var subMeshes;
  18995. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18996. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18997. len = intersections.length;
  18998. subMeshes = intersections.data;
  18999. }
  19000. else {
  19001. subMeshes = mesh.subMeshes;
  19002. len = subMeshes.length;
  19003. }
  19004. for (var subIndex = 0; subIndex < len; subIndex++) {
  19005. var subMesh = subMeshes[subIndex];
  19006. this._evaluateSubMesh(subMesh, mesh);
  19007. }
  19008. }
  19009. };
  19010. Scene.prototype.updateTransformMatrix = function (force) {
  19011. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19012. };
  19013. Scene.prototype._renderForCamera = function (camera) {
  19014. var engine = this._engine;
  19015. var startTime = BABYLON.Tools.Now;
  19016. this.activeCamera = camera;
  19017. if (!this.activeCamera)
  19018. throw new Error("Active camera not set");
  19019. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19020. // Viewport
  19021. engine.setViewport(this.activeCamera.viewport);
  19022. // Camera
  19023. this.resetCachedMaterial();
  19024. this._renderId++;
  19025. this.updateTransformMatrix();
  19026. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19027. // Meshes
  19028. this._evaluateActiveMeshesDuration.beginMonitoring();
  19029. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19030. this._evaluateActiveMeshes();
  19031. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19032. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19033. // Software skinning
  19034. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19035. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19036. mesh.applySkeleton(mesh.skeleton);
  19037. }
  19038. // Render targets
  19039. this._renderTargetsDuration.beginMonitoring();
  19040. var needsRestoreFrameBuffer = false;
  19041. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19042. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19043. this._intermediateRendering = true;
  19044. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19045. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19046. var renderTarget = this._renderTargets.data[renderIndex];
  19047. if (renderTarget._shouldRender()) {
  19048. this._renderId++;
  19049. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19050. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19051. }
  19052. }
  19053. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19054. this._intermediateRendering = false;
  19055. this._renderId++;
  19056. needsRestoreFrameBuffer = true; // Restore back buffer
  19057. }
  19058. // Render HighlightLayer Texture
  19059. var stencilState = this._engine.getStencilBuffer();
  19060. var renderhighlights = false;
  19061. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19062. this._intermediateRendering = true;
  19063. for (var i = 0; i < this.highlightLayers.length; i++) {
  19064. var highlightLayer = this.highlightLayers[i];
  19065. if (highlightLayer.shouldRender() &&
  19066. (!highlightLayer.camera ||
  19067. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19068. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19069. renderhighlights = true;
  19070. var renderTarget = highlightLayer._mainTexture;
  19071. if (renderTarget._shouldRender()) {
  19072. this._renderId++;
  19073. renderTarget.render(false, false);
  19074. needsRestoreFrameBuffer = true;
  19075. }
  19076. }
  19077. }
  19078. this._intermediateRendering = false;
  19079. this._renderId++;
  19080. }
  19081. if (needsRestoreFrameBuffer) {
  19082. engine.restoreDefaultFramebuffer();
  19083. }
  19084. this._renderTargetsDuration.endMonitoring(false);
  19085. // Prepare Frame
  19086. this.postProcessManager._prepareFrame();
  19087. this._renderDuration.beginMonitoring();
  19088. // Backgrounds
  19089. var layerIndex;
  19090. var layer;
  19091. if (this.layers.length) {
  19092. engine.setDepthBuffer(false);
  19093. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19094. layer = this.layers[layerIndex];
  19095. if (layer.isBackground) {
  19096. layer.render();
  19097. }
  19098. }
  19099. engine.setDepthBuffer(true);
  19100. }
  19101. // Render
  19102. BABYLON.Tools.StartPerformanceCounter("Main render");
  19103. // Activate HighlightLayer stencil
  19104. if (renderhighlights) {
  19105. this._engine.setStencilBuffer(true);
  19106. }
  19107. this._renderingManager.render(null, null, true, true);
  19108. // Restore HighlightLayer stencil
  19109. if (renderhighlights) {
  19110. this._engine.setStencilBuffer(stencilState);
  19111. }
  19112. BABYLON.Tools.EndPerformanceCounter("Main render");
  19113. // Bounding boxes
  19114. this._boundingBoxRenderer.render();
  19115. // Edges
  19116. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19117. this._edgesRenderers.data[edgesRendererIndex].render();
  19118. }
  19119. // Lens flares
  19120. if (this.lensFlaresEnabled) {
  19121. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19122. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19123. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19124. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19125. lensFlareSystem.render();
  19126. }
  19127. }
  19128. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19129. }
  19130. // Foregrounds
  19131. if (this.layers.length) {
  19132. engine.setDepthBuffer(false);
  19133. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19134. layer = this.layers[layerIndex];
  19135. if (!layer.isBackground) {
  19136. layer.render();
  19137. }
  19138. }
  19139. engine.setDepthBuffer(true);
  19140. }
  19141. // Highlight Layer
  19142. if (renderhighlights) {
  19143. engine.setDepthBuffer(false);
  19144. for (var i = 0; i < this.highlightLayers.length; i++) {
  19145. if (this.highlightLayers[i].shouldRender()) {
  19146. this.highlightLayers[i].render();
  19147. }
  19148. }
  19149. engine.setDepthBuffer(true);
  19150. }
  19151. this._renderDuration.endMonitoring(false);
  19152. // Finalize frame
  19153. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19154. // Update camera
  19155. this.activeCamera._updateFromScene();
  19156. // Reset some special arrays
  19157. this._renderTargets.reset();
  19158. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19159. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19160. };
  19161. Scene.prototype._processSubCameras = function (camera) {
  19162. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19163. this._renderForCamera(camera);
  19164. return;
  19165. }
  19166. // rig cameras
  19167. for (var index = 0; index < camera._rigCameras.length; index++) {
  19168. this._renderForCamera(camera._rigCameras[index]);
  19169. }
  19170. this.activeCamera = camera;
  19171. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19172. // Update camera
  19173. this.activeCamera._updateFromScene();
  19174. };
  19175. Scene.prototype._checkIntersections = function () {
  19176. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19177. var sourceMesh = this._meshesForIntersections.data[index];
  19178. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19179. var action = sourceMesh.actionManager.actions[actionIndex];
  19180. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19181. var parameters = action.getTriggerParameter();
  19182. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19183. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19184. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19185. if (areIntersecting && currentIntersectionInProgress === -1) {
  19186. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19187. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19188. sourceMesh._intersectionsInProgress.push(otherMesh);
  19189. }
  19190. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19191. sourceMesh._intersectionsInProgress.push(otherMesh);
  19192. }
  19193. }
  19194. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19195. //They intersected, and now they don't.
  19196. //is this trigger an exit trigger? execute an event.
  19197. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19198. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19199. }
  19200. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19201. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19202. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19203. }
  19204. }
  19205. }
  19206. }
  19207. }
  19208. };
  19209. Scene.prototype.render = function () {
  19210. this._lastFrameDuration.beginMonitoring();
  19211. this._particlesDuration.fetchNewFrame();
  19212. this._spritesDuration.fetchNewFrame();
  19213. this._activeParticles.fetchNewFrame();
  19214. this._renderDuration.fetchNewFrame();
  19215. this._renderTargetsDuration.fetchNewFrame();
  19216. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19217. this._totalVertices.fetchNewFrame();
  19218. this._activeIndices.fetchNewFrame();
  19219. this._activeBones.fetchNewFrame();
  19220. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19221. this._meshesForIntersections.reset();
  19222. this.resetCachedMaterial();
  19223. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19224. // Actions
  19225. if (this.actionManager) {
  19226. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19227. }
  19228. //Simplification Queue
  19229. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19230. this.simplificationQueue.executeNext();
  19231. }
  19232. // Animations
  19233. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19234. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19235. this._animate();
  19236. // Physics
  19237. if (this._physicsEngine) {
  19238. BABYLON.Tools.StartPerformanceCounter("Physics");
  19239. this._physicsEngine._step(deltaTime / 1000.0);
  19240. BABYLON.Tools.EndPerformanceCounter("Physics");
  19241. }
  19242. // Before render
  19243. this.onBeforeRenderObservable.notifyObservers(this);
  19244. // Customs render targets
  19245. this._renderTargetsDuration.beginMonitoring();
  19246. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19247. var engine = this.getEngine();
  19248. var currentActiveCamera = this.activeCamera;
  19249. if (this.renderTargetsEnabled) {
  19250. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19251. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19252. var renderTarget = this.customRenderTargets[customIndex];
  19253. if (renderTarget._shouldRender()) {
  19254. this._renderId++;
  19255. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19256. if (!this.activeCamera)
  19257. throw new Error("Active camera not set");
  19258. // Viewport
  19259. engine.setViewport(this.activeCamera.viewport);
  19260. // Camera
  19261. this.updateTransformMatrix();
  19262. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19263. }
  19264. }
  19265. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19266. this._renderId++;
  19267. }
  19268. if (this.customRenderTargets.length > 0) {
  19269. engine.restoreDefaultFramebuffer();
  19270. }
  19271. this._renderTargetsDuration.endMonitoring();
  19272. this.activeCamera = currentActiveCamera;
  19273. // Procedural textures
  19274. if (this.proceduralTexturesEnabled) {
  19275. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19276. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19277. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19278. if (proceduralTexture._shouldRender()) {
  19279. proceduralTexture.render();
  19280. }
  19281. }
  19282. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19283. }
  19284. // Clear
  19285. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  19286. // Shadows
  19287. if (this.shadowsEnabled) {
  19288. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19289. var light = this.lights[lightIndex];
  19290. var shadowGenerator = light.getShadowGenerator();
  19291. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  19292. this._renderTargets.push(shadowGenerator.getShadowMap());
  19293. }
  19294. }
  19295. }
  19296. // Depth renderer
  19297. if (this._depthRenderer) {
  19298. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19299. }
  19300. // RenderPipeline
  19301. this.postProcessRenderPipelineManager.update();
  19302. // Multi-cameras?
  19303. if (this.activeCameras.length > 0) {
  19304. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19305. if (cameraIndex > 0) {
  19306. this._engine.clear(null, false, true, true);
  19307. }
  19308. this._processSubCameras(this.activeCameras[cameraIndex]);
  19309. }
  19310. }
  19311. else {
  19312. if (!this.activeCamera) {
  19313. throw new Error("No camera defined");
  19314. }
  19315. this._processSubCameras(this.activeCamera);
  19316. }
  19317. // Intersection checks
  19318. this._checkIntersections();
  19319. // Update the audio listener attached to the camera
  19320. if (BABYLON.AudioEngine) {
  19321. this._updateAudioParameters();
  19322. }
  19323. // After render
  19324. if (this.afterRender) {
  19325. this.afterRender();
  19326. }
  19327. this.onAfterRenderObservable.notifyObservers(this);
  19328. // Cleaning
  19329. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19330. this._toBeDisposed.data[index].dispose();
  19331. this._toBeDisposed[index] = null;
  19332. }
  19333. this._toBeDisposed.reset();
  19334. if (this.dumpNextRenderTargets) {
  19335. this.dumpNextRenderTargets = false;
  19336. }
  19337. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19338. this._lastFrameDuration.endMonitoring();
  19339. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19340. this._totalLightsCounter.addCount(this.lights.length, true);
  19341. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19342. this._totalTexturesCounter.addCount(this.textures.length, true);
  19343. this._activeBones.addCount(0, true);
  19344. this._activeIndices.addCount(0, true);
  19345. this._activeParticles.addCount(0, true);
  19346. };
  19347. Scene.prototype._updateAudioParameters = function () {
  19348. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19349. return;
  19350. }
  19351. var listeningCamera;
  19352. var audioEngine = BABYLON.Engine.audioEngine;
  19353. if (this.activeCameras.length > 0) {
  19354. listeningCamera = this.activeCameras[0];
  19355. }
  19356. else {
  19357. listeningCamera = this.activeCamera;
  19358. }
  19359. if (listeningCamera && audioEngine.canUseWebAudio) {
  19360. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19361. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19362. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19363. cameraDirection.normalize();
  19364. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19365. var i;
  19366. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19367. var sound = this.mainSoundTrack.soundCollection[i];
  19368. if (sound.useCustomAttenuation) {
  19369. sound.updateDistanceFromListener();
  19370. }
  19371. }
  19372. for (i = 0; i < this.soundTracks.length; i++) {
  19373. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19374. sound = this.soundTracks[i].soundCollection[j];
  19375. if (sound.useCustomAttenuation) {
  19376. sound.updateDistanceFromListener();
  19377. }
  19378. }
  19379. }
  19380. }
  19381. };
  19382. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19383. // Audio
  19384. get: function () {
  19385. return this._audioEnabled;
  19386. },
  19387. set: function (value) {
  19388. this._audioEnabled = value;
  19389. if (BABYLON.AudioEngine) {
  19390. if (this._audioEnabled) {
  19391. this._enableAudio();
  19392. }
  19393. else {
  19394. this._disableAudio();
  19395. }
  19396. }
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Scene.prototype._disableAudio = function () {
  19402. var i;
  19403. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19404. this.mainSoundTrack.soundCollection[i].pause();
  19405. }
  19406. for (i = 0; i < this.soundTracks.length; i++) {
  19407. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19408. this.soundTracks[i].soundCollection[j].pause();
  19409. }
  19410. }
  19411. };
  19412. Scene.prototype._enableAudio = function () {
  19413. var i;
  19414. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19415. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19416. this.mainSoundTrack.soundCollection[i].play();
  19417. }
  19418. }
  19419. for (i = 0; i < this.soundTracks.length; i++) {
  19420. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19421. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19422. this.soundTracks[i].soundCollection[j].play();
  19423. }
  19424. }
  19425. }
  19426. };
  19427. Object.defineProperty(Scene.prototype, "headphone", {
  19428. get: function () {
  19429. return this._headphone;
  19430. },
  19431. set: function (value) {
  19432. this._headphone = value;
  19433. if (BABYLON.AudioEngine) {
  19434. if (this._headphone) {
  19435. this._switchAudioModeForHeadphones();
  19436. }
  19437. else {
  19438. this._switchAudioModeForNormalSpeakers();
  19439. }
  19440. }
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Scene.prototype._switchAudioModeForHeadphones = function () {
  19446. this.mainSoundTrack.switchPanningModelToHRTF();
  19447. for (var i = 0; i < this.soundTracks.length; i++) {
  19448. this.soundTracks[i].switchPanningModelToHRTF();
  19449. }
  19450. };
  19451. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19452. this.mainSoundTrack.switchPanningModelToEqualPower();
  19453. for (var i = 0; i < this.soundTracks.length; i++) {
  19454. this.soundTracks[i].switchPanningModelToEqualPower();
  19455. }
  19456. };
  19457. Scene.prototype.enableDepthRenderer = function () {
  19458. if (this._depthRenderer) {
  19459. return this._depthRenderer;
  19460. }
  19461. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19462. return this._depthRenderer;
  19463. };
  19464. Scene.prototype.disableDepthRenderer = function () {
  19465. if (!this._depthRenderer) {
  19466. return;
  19467. }
  19468. this._depthRenderer.dispose();
  19469. this._depthRenderer = null;
  19470. };
  19471. Scene.prototype.freezeMaterials = function () {
  19472. for (var i = 0; i < this.materials.length; i++) {
  19473. this.materials[i].freeze();
  19474. }
  19475. };
  19476. Scene.prototype.unfreezeMaterials = function () {
  19477. for (var i = 0; i < this.materials.length; i++) {
  19478. this.materials[i].unfreeze();
  19479. }
  19480. };
  19481. Scene.prototype.dispose = function () {
  19482. this.beforeRender = null;
  19483. this.afterRender = null;
  19484. this.skeletons = [];
  19485. this._boundingBoxRenderer.dispose();
  19486. if (this._depthRenderer) {
  19487. this._depthRenderer.dispose();
  19488. }
  19489. // Debug layer
  19490. if (this._debugLayer) {
  19491. this._debugLayer.hide();
  19492. }
  19493. // Events
  19494. this.onDisposeObservable.notifyObservers(this);
  19495. this.onDisposeObservable.clear();
  19496. this.onBeforeRenderObservable.clear();
  19497. this.onAfterRenderObservable.clear();
  19498. this.detachControl();
  19499. // Release sounds & sounds tracks
  19500. if (BABYLON.AudioEngine) {
  19501. this.disposeSounds();
  19502. }
  19503. // Detach cameras
  19504. var canvas = this._engine.getRenderingCanvas();
  19505. var index;
  19506. for (index = 0; index < this.cameras.length; index++) {
  19507. this.cameras[index].detachControl(canvas);
  19508. }
  19509. // Release lights
  19510. while (this.lights.length) {
  19511. this.lights[0].dispose();
  19512. }
  19513. // Release meshes
  19514. while (this.meshes.length) {
  19515. this.meshes[0].dispose(true);
  19516. }
  19517. // Release cameras
  19518. while (this.cameras.length) {
  19519. this.cameras[0].dispose();
  19520. }
  19521. // Release materials
  19522. while (this.materials.length) {
  19523. this.materials[0].dispose();
  19524. }
  19525. // Release particles
  19526. while (this.particleSystems.length) {
  19527. this.particleSystems[0].dispose();
  19528. }
  19529. // Release sprites
  19530. while (this.spriteManagers.length) {
  19531. this.spriteManagers[0].dispose();
  19532. }
  19533. // Release layers
  19534. while (this.layers.length) {
  19535. this.layers[0].dispose();
  19536. }
  19537. while (this.highlightLayers.length) {
  19538. this.highlightLayers[0].dispose();
  19539. }
  19540. // Release textures
  19541. while (this.textures.length) {
  19542. this.textures[0].dispose();
  19543. }
  19544. // Post-processes
  19545. this.postProcessManager.dispose();
  19546. // Physics
  19547. if (this._physicsEngine) {
  19548. this.disablePhysicsEngine();
  19549. }
  19550. // Remove from engine
  19551. index = this._engine.scenes.indexOf(this);
  19552. if (index > -1) {
  19553. this._engine.scenes.splice(index, 1);
  19554. }
  19555. this._engine.wipeCaches();
  19556. };
  19557. // Release sounds & sounds tracks
  19558. Scene.prototype.disposeSounds = function () {
  19559. this.mainSoundTrack.dispose();
  19560. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19561. this.soundTracks[scIndex].dispose();
  19562. }
  19563. };
  19564. // Octrees
  19565. Scene.prototype.getWorldExtends = function () {
  19566. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19567. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19568. for (var index = 0; index < this.meshes.length; index++) {
  19569. var mesh = this.meshes[index];
  19570. mesh.computeWorldMatrix(true);
  19571. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19572. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19573. BABYLON.Tools.CheckExtends(minBox, min, max);
  19574. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19575. }
  19576. return {
  19577. min: min,
  19578. max: max
  19579. };
  19580. };
  19581. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19582. if (maxCapacity === void 0) { maxCapacity = 64; }
  19583. if (maxDepth === void 0) { maxDepth = 2; }
  19584. if (!this._selectionOctree) {
  19585. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19586. }
  19587. var worldExtends = this.getWorldExtends();
  19588. // Update octree
  19589. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19590. return this._selectionOctree;
  19591. };
  19592. // Picking
  19593. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19594. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19595. var engine = this._engine;
  19596. if (!camera) {
  19597. if (!this.activeCamera)
  19598. throw new Error("Active camera not set");
  19599. camera = this.activeCamera;
  19600. }
  19601. var cameraViewport = camera.viewport;
  19602. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19603. // Moving coordinates to local viewport world
  19604. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19605. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19606. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19607. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19608. };
  19609. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19610. var engine = this._engine;
  19611. if (!camera) {
  19612. if (!this.activeCamera)
  19613. throw new Error("Active camera not set");
  19614. camera = this.activeCamera;
  19615. }
  19616. var cameraViewport = camera.viewport;
  19617. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19618. var identity = BABYLON.Matrix.Identity();
  19619. // Moving coordinates to local viewport world
  19620. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19621. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19622. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19623. };
  19624. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19625. var pickingInfo = null;
  19626. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19627. var mesh = this.meshes[meshIndex];
  19628. if (predicate) {
  19629. if (!predicate(mesh)) {
  19630. continue;
  19631. }
  19632. }
  19633. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19634. continue;
  19635. }
  19636. var world = mesh.getWorldMatrix();
  19637. var ray = rayFunction(world);
  19638. var result = mesh.intersects(ray, fastCheck);
  19639. if (!result || !result.hit)
  19640. continue;
  19641. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19642. continue;
  19643. pickingInfo = result;
  19644. if (fastCheck) {
  19645. break;
  19646. }
  19647. }
  19648. return pickingInfo || new BABYLON.PickingInfo();
  19649. };
  19650. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19651. var pickingInfos = new Array();
  19652. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19653. var mesh = this.meshes[meshIndex];
  19654. if (predicate) {
  19655. if (!predicate(mesh)) {
  19656. continue;
  19657. }
  19658. }
  19659. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19660. continue;
  19661. }
  19662. var world = mesh.getWorldMatrix();
  19663. var ray = rayFunction(world);
  19664. var result = mesh.intersects(ray, false);
  19665. if (!result || !result.hit)
  19666. continue;
  19667. pickingInfos.push(result);
  19668. }
  19669. return pickingInfos;
  19670. };
  19671. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19672. var pickingInfo = null;
  19673. camera = camera || this.activeCamera;
  19674. if (this.spriteManagers.length > 0) {
  19675. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19676. var spriteManager = this.spriteManagers[spriteIndex];
  19677. if (!spriteManager.isPickable) {
  19678. continue;
  19679. }
  19680. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19681. if (!result || !result.hit)
  19682. continue;
  19683. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19684. continue;
  19685. pickingInfo = result;
  19686. if (fastCheck) {
  19687. break;
  19688. }
  19689. }
  19690. }
  19691. return pickingInfo || new BABYLON.PickingInfo();
  19692. };
  19693. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19694. /// <param name="x">X position on screen</param>
  19695. /// <param name="y">Y position on screen</param>
  19696. /// <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>
  19697. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19698. /// <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>
  19699. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19700. var _this = this;
  19701. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19702. };
  19703. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19704. /// <param name="x">X position on screen</param>
  19705. /// <param name="y">Y position on screen</param>
  19706. /// <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>
  19707. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19708. /// <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>
  19709. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19710. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19711. };
  19712. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19713. var _this = this;
  19714. return this._internalPick(function (world) {
  19715. if (!_this._pickWithRayInverseMatrix) {
  19716. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19717. }
  19718. world.invertToRef(_this._pickWithRayInverseMatrix);
  19719. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19720. }, predicate, fastCheck);
  19721. };
  19722. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19723. /// <param name="x">X position on screen</param>
  19724. /// <param name="y">Y position on screen</param>
  19725. /// <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>
  19726. /// <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>
  19727. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19728. var _this = this;
  19729. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19730. };
  19731. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19732. /// <param name="ray">Ray to use</param>
  19733. /// <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>
  19734. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19735. var _this = this;
  19736. return this._internalMultiPick(function (world) {
  19737. if (!_this._pickWithRayInverseMatrix) {
  19738. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19739. }
  19740. world.invertToRef(_this._pickWithRayInverseMatrix);
  19741. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19742. }, predicate);
  19743. };
  19744. Scene.prototype.setPointerOverMesh = function (mesh) {
  19745. if (this._pointerOverMesh === mesh) {
  19746. return;
  19747. }
  19748. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19749. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19750. }
  19751. this._pointerOverMesh = mesh;
  19752. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19753. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19754. }
  19755. };
  19756. Scene.prototype.getPointerOverMesh = function () {
  19757. return this._pointerOverMesh;
  19758. };
  19759. Scene.prototype.setPointerOverSprite = function (sprite) {
  19760. if (this._pointerOverSprite === sprite) {
  19761. return;
  19762. }
  19763. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19764. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19765. }
  19766. this._pointerOverSprite = sprite;
  19767. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19768. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19769. }
  19770. };
  19771. Scene.prototype.getPointerOverSprite = function () {
  19772. return this._pointerOverSprite;
  19773. };
  19774. // Physics
  19775. Scene.prototype.getPhysicsEngine = function () {
  19776. return this._physicsEngine;
  19777. };
  19778. /**
  19779. * Enables physics to the current scene
  19780. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19781. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19782. * @return {boolean} was the physics engine initialized
  19783. */
  19784. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19785. if (this._physicsEngine) {
  19786. return true;
  19787. }
  19788. try {
  19789. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19790. return true;
  19791. }
  19792. catch (e) {
  19793. BABYLON.Tools.Error(e.message);
  19794. return false;
  19795. }
  19796. };
  19797. Scene.prototype.disablePhysicsEngine = function () {
  19798. if (!this._physicsEngine) {
  19799. return;
  19800. }
  19801. this._physicsEngine.dispose();
  19802. this._physicsEngine = undefined;
  19803. };
  19804. Scene.prototype.isPhysicsEnabled = function () {
  19805. return this._physicsEngine !== undefined;
  19806. };
  19807. /**
  19808. *
  19809. * Sets the gravity of the physics engine (and NOT of the scene)
  19810. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19811. */
  19812. Scene.prototype.setGravity = function (gravity) {
  19813. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19814. if (!this._physicsEngine) {
  19815. return;
  19816. }
  19817. this._physicsEngine.setGravity(gravity);
  19818. };
  19819. /**
  19820. * Legacy support, using the new API
  19821. * @Deprecated
  19822. */
  19823. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19824. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19825. if (parts.parts) {
  19826. options = parts;
  19827. parts = parts.parts;
  19828. }
  19829. var mainMesh = parts[0].mesh;
  19830. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19831. for (var index = 1; index < parts.length; index++) {
  19832. var mesh = parts[index].mesh;
  19833. if (mesh.parent !== mainMesh) {
  19834. mesh.position = mesh.position.subtract(mainMesh.position);
  19835. mesh.parent = mainMesh;
  19836. }
  19837. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19838. }
  19839. mainMesh.physicsImpostor.forceUpdate();
  19840. };
  19841. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19842. var mesh = compound.parts[0].mesh;
  19843. mesh.physicsImpostor.dispose();
  19844. mesh.physicsImpostor = null;
  19845. };
  19846. // Misc.
  19847. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19848. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19849. // Light
  19850. if (this.lights.length === 0) {
  19851. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19852. }
  19853. // Camera
  19854. if (!this.activeCamera) {
  19855. // Compute position
  19856. var worldExtends = this.getWorldExtends();
  19857. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19858. var camera;
  19859. if (createArcRotateCamera) {
  19860. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19861. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19862. camera.setTarget(worldCenter);
  19863. }
  19864. else {
  19865. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19866. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19867. camera.setTarget(worldCenter);
  19868. }
  19869. this.activeCamera = camera;
  19870. }
  19871. };
  19872. // Tags
  19873. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19874. if (tagsQuery === undefined) {
  19875. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19876. return list;
  19877. }
  19878. var listByTags = [];
  19879. forEach = forEach || (function (item) { return; });
  19880. for (var i in list) {
  19881. var item = list[i];
  19882. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19883. listByTags.push(item);
  19884. forEach(item);
  19885. }
  19886. }
  19887. return listByTags;
  19888. };
  19889. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19890. return this._getByTags(this.meshes, tagsQuery, forEach);
  19891. };
  19892. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19893. return this._getByTags(this.cameras, tagsQuery, forEach);
  19894. };
  19895. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19896. return this._getByTags(this.lights, tagsQuery, forEach);
  19897. };
  19898. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19899. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19900. };
  19901. /**
  19902. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19903. * This allowed control for front to back rendering or reversly depending of the special needs.
  19904. *
  19905. * @param renderingGroupId The rendering group id corresponding to its index
  19906. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19907. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19908. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19909. */
  19910. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19911. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19912. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19913. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19914. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19915. };
  19916. /**
  19917. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19918. *
  19919. * @param renderingGroupId The rendering group id corresponding to its index
  19920. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19921. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19922. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19923. */
  19924. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19925. if (depth === void 0) { depth = true; }
  19926. if (stencil === void 0) { stencil = true; }
  19927. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19928. };
  19929. return Scene;
  19930. }());
  19931. // Statics
  19932. Scene._FOGMODE_NONE = 0;
  19933. Scene._FOGMODE_EXP = 1;
  19934. Scene._FOGMODE_EXP2 = 2;
  19935. Scene._FOGMODE_LINEAR = 3;
  19936. Scene.MinDeltaTime = 1.0;
  19937. Scene.MaxDeltaTime = 1000.0;
  19938. BABYLON.Scene = Scene;
  19939. })(BABYLON || (BABYLON = {}));
  19940. //# sourceMappingURL=babylon.scene.js.map
  19941. var BABYLON;
  19942. (function (BABYLON) {
  19943. var Buffer = (function () {
  19944. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19945. if (engine instanceof BABYLON.Mesh) {
  19946. this._engine = engine.getScene().getEngine();
  19947. }
  19948. else {
  19949. this._engine = engine;
  19950. }
  19951. this._updatable = updatable;
  19952. this._data = data;
  19953. this._strideSize = stride;
  19954. if (!postponeInternalCreation) {
  19955. this.create();
  19956. }
  19957. this._instanced = instanced;
  19958. }
  19959. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19960. // a lot of these parameters are ignored as they are overriden by the buffer
  19961. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19962. };
  19963. // Properties
  19964. Buffer.prototype.isUpdatable = function () {
  19965. return this._updatable;
  19966. };
  19967. Buffer.prototype.getData = function () {
  19968. return this._data;
  19969. };
  19970. Buffer.prototype.getBuffer = function () {
  19971. return this._buffer;
  19972. };
  19973. Buffer.prototype.getStrideSize = function () {
  19974. return this._strideSize;
  19975. };
  19976. Buffer.prototype.getIsInstanced = function () {
  19977. return this._instanced;
  19978. };
  19979. // Methods
  19980. Buffer.prototype.create = function (data) {
  19981. if (!data && this._buffer) {
  19982. return; // nothing to do
  19983. }
  19984. data = data || this._data;
  19985. if (!this._buffer) {
  19986. if (this._updatable) {
  19987. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19988. this._data = data;
  19989. }
  19990. else {
  19991. this._buffer = this._engine.createVertexBuffer(data);
  19992. }
  19993. }
  19994. else if (this._updatable) {
  19995. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19996. this._data = data;
  19997. }
  19998. };
  19999. Buffer.prototype.update = function (data) {
  20000. this.create(data);
  20001. };
  20002. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20003. if (!this._buffer) {
  20004. return;
  20005. }
  20006. if (this._updatable) {
  20007. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20008. this._data = null;
  20009. }
  20010. };
  20011. Buffer.prototype.dispose = function () {
  20012. if (!this._buffer) {
  20013. return;
  20014. }
  20015. if (this._engine._releaseBuffer(this._buffer)) {
  20016. this._buffer = null;
  20017. }
  20018. };
  20019. return Buffer;
  20020. }());
  20021. BABYLON.Buffer = Buffer;
  20022. })(BABYLON || (BABYLON = {}));
  20023. //# sourceMappingURL=babylon.buffer.js.map
  20024. var BABYLON;
  20025. (function (BABYLON) {
  20026. var VertexBuffer = (function () {
  20027. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20028. if (!stride) {
  20029. // Deduce stride from kind
  20030. switch (kind) {
  20031. case VertexBuffer.PositionKind:
  20032. stride = 3;
  20033. break;
  20034. case VertexBuffer.NormalKind:
  20035. stride = 3;
  20036. break;
  20037. case VertexBuffer.UVKind:
  20038. case VertexBuffer.UV2Kind:
  20039. case VertexBuffer.UV3Kind:
  20040. case VertexBuffer.UV4Kind:
  20041. case VertexBuffer.UV5Kind:
  20042. case VertexBuffer.UV6Kind:
  20043. stride = 2;
  20044. break;
  20045. case VertexBuffer.ColorKind:
  20046. stride = 4;
  20047. break;
  20048. case VertexBuffer.MatricesIndicesKind:
  20049. case VertexBuffer.MatricesIndicesExtraKind:
  20050. stride = 4;
  20051. break;
  20052. case VertexBuffer.MatricesWeightsKind:
  20053. case VertexBuffer.MatricesWeightsExtraKind:
  20054. stride = 4;
  20055. break;
  20056. }
  20057. }
  20058. if (data instanceof BABYLON.Buffer) {
  20059. if (!stride) {
  20060. stride = data.getStrideSize();
  20061. }
  20062. this._buffer = data;
  20063. this._ownsBuffer = false;
  20064. }
  20065. else {
  20066. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20067. this._ownsBuffer = true;
  20068. }
  20069. this._stride = stride;
  20070. this._offset = offset ? offset : 0;
  20071. this._size = size ? size : stride;
  20072. this._kind = kind;
  20073. }
  20074. VertexBuffer.prototype.getKind = function () {
  20075. return this._kind;
  20076. };
  20077. // Properties
  20078. VertexBuffer.prototype.isUpdatable = function () {
  20079. return this._buffer.isUpdatable();
  20080. };
  20081. VertexBuffer.prototype.getData = function () {
  20082. return this._buffer.getData();
  20083. };
  20084. VertexBuffer.prototype.getBuffer = function () {
  20085. return this._buffer.getBuffer();
  20086. };
  20087. VertexBuffer.prototype.getStrideSize = function () {
  20088. return this._stride;
  20089. };
  20090. VertexBuffer.prototype.getOffset = function () {
  20091. return this._offset;
  20092. };
  20093. VertexBuffer.prototype.getSize = function () {
  20094. return this._size;
  20095. };
  20096. VertexBuffer.prototype.getIsInstanced = function () {
  20097. return this._buffer.getIsInstanced();
  20098. };
  20099. // Methods
  20100. VertexBuffer.prototype.create = function (data) {
  20101. return this._buffer.create(data);
  20102. };
  20103. VertexBuffer.prototype.update = function (data) {
  20104. return this._buffer.update(data);
  20105. };
  20106. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20107. return this._buffer.updateDirectly(data, offset);
  20108. };
  20109. VertexBuffer.prototype.dispose = function () {
  20110. if (this._ownsBuffer) {
  20111. this._buffer.dispose();
  20112. }
  20113. };
  20114. Object.defineProperty(VertexBuffer, "PositionKind", {
  20115. get: function () {
  20116. return VertexBuffer._PositionKind;
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(VertexBuffer, "NormalKind", {
  20122. get: function () {
  20123. return VertexBuffer._NormalKind;
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. Object.defineProperty(VertexBuffer, "UVKind", {
  20129. get: function () {
  20130. return VertexBuffer._UVKind;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20136. get: function () {
  20137. return VertexBuffer._UV2Kind;
  20138. },
  20139. enumerable: true,
  20140. configurable: true
  20141. });
  20142. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20143. get: function () {
  20144. return VertexBuffer._UV3Kind;
  20145. },
  20146. enumerable: true,
  20147. configurable: true
  20148. });
  20149. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20150. get: function () {
  20151. return VertexBuffer._UV4Kind;
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20157. get: function () {
  20158. return VertexBuffer._UV5Kind;
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20164. get: function () {
  20165. return VertexBuffer._UV6Kind;
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(VertexBuffer, "ColorKind", {
  20171. get: function () {
  20172. return VertexBuffer._ColorKind;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20178. get: function () {
  20179. return VertexBuffer._MatricesIndicesKind;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20185. get: function () {
  20186. return VertexBuffer._MatricesWeightsKind;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20192. get: function () {
  20193. return VertexBuffer._MatricesIndicesExtraKind;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20199. get: function () {
  20200. return VertexBuffer._MatricesWeightsExtraKind;
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. return VertexBuffer;
  20206. }());
  20207. // Enums
  20208. VertexBuffer._PositionKind = "position";
  20209. VertexBuffer._NormalKind = "normal";
  20210. VertexBuffer._UVKind = "uv";
  20211. VertexBuffer._UV2Kind = "uv2";
  20212. VertexBuffer._UV3Kind = "uv3";
  20213. VertexBuffer._UV4Kind = "uv4";
  20214. VertexBuffer._UV5Kind = "uv5";
  20215. VertexBuffer._UV6Kind = "uv6";
  20216. VertexBuffer._ColorKind = "color";
  20217. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20218. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20219. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20220. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20221. BABYLON.VertexBuffer = VertexBuffer;
  20222. })(BABYLON || (BABYLON = {}));
  20223. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20224. var BABYLON;
  20225. (function (BABYLON) {
  20226. /**
  20227. * Creates an instance based on a source mesh.
  20228. */
  20229. var InstancedMesh = (function (_super) {
  20230. __extends(InstancedMesh, _super);
  20231. function InstancedMesh(name, source) {
  20232. var _this = _super.call(this, name, source.getScene()) || this;
  20233. source.instances.push(_this);
  20234. _this._sourceMesh = source;
  20235. _this.position.copyFrom(source.position);
  20236. _this.rotation.copyFrom(source.rotation);
  20237. _this.scaling.copyFrom(source.scaling);
  20238. if (source.rotationQuaternion) {
  20239. _this.rotationQuaternion = source.rotationQuaternion.clone();
  20240. }
  20241. _this.infiniteDistance = source.infiniteDistance;
  20242. _this.setPivotMatrix(source.getPivotMatrix());
  20243. _this.refreshBoundingInfo();
  20244. _this._syncSubMeshes();
  20245. return _this;
  20246. }
  20247. InstancedMesh.prototype.getClassName = function () {
  20248. return "InstancedMesh";
  20249. };
  20250. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  20251. // Methods
  20252. get: function () {
  20253. return this._sourceMesh.receiveShadows;
  20254. },
  20255. enumerable: true,
  20256. configurable: true
  20257. });
  20258. Object.defineProperty(InstancedMesh.prototype, "material", {
  20259. get: function () {
  20260. return this._sourceMesh.material;
  20261. },
  20262. enumerable: true,
  20263. configurable: true
  20264. });
  20265. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  20266. get: function () {
  20267. return this._sourceMesh.visibility;
  20268. },
  20269. enumerable: true,
  20270. configurable: true
  20271. });
  20272. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  20273. get: function () {
  20274. return this._sourceMesh.skeleton;
  20275. },
  20276. enumerable: true,
  20277. configurable: true
  20278. });
  20279. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  20280. get: function () {
  20281. return this._sourceMesh.renderingGroupId;
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. InstancedMesh.prototype.getTotalVertices = function () {
  20287. return this._sourceMesh.getTotalVertices();
  20288. };
  20289. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  20290. get: function () {
  20291. return this._sourceMesh;
  20292. },
  20293. enumerable: true,
  20294. configurable: true
  20295. });
  20296. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20297. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  20298. };
  20299. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  20300. return this._sourceMesh.isVerticesDataPresent(kind);
  20301. };
  20302. InstancedMesh.prototype.getIndices = function () {
  20303. return this._sourceMesh.getIndices();
  20304. };
  20305. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  20306. get: function () {
  20307. return this._sourceMesh._positions;
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. InstancedMesh.prototype.refreshBoundingInfo = function () {
  20313. var meshBB = this._sourceMesh.getBoundingInfo();
  20314. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  20315. this._updateBoundingInfo();
  20316. };
  20317. InstancedMesh.prototype._preActivate = function () {
  20318. if (this._currentLOD) {
  20319. this._currentLOD._preActivate();
  20320. }
  20321. };
  20322. InstancedMesh.prototype._activate = function (renderId) {
  20323. if (this._currentLOD) {
  20324. this._currentLOD._registerInstanceForRenderId(this, renderId);
  20325. }
  20326. };
  20327. InstancedMesh.prototype.getLOD = function (camera) {
  20328. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  20329. if (this._currentLOD === this.sourceMesh) {
  20330. return this;
  20331. }
  20332. return this._currentLOD;
  20333. };
  20334. InstancedMesh.prototype._syncSubMeshes = function () {
  20335. this.releaseSubMeshes();
  20336. if (this._sourceMesh.subMeshes) {
  20337. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  20338. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  20339. }
  20340. }
  20341. };
  20342. InstancedMesh.prototype._generatePointsArray = function () {
  20343. return this._sourceMesh._generatePointsArray();
  20344. };
  20345. // Clone
  20346. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20347. var result = this._sourceMesh.createInstance(name);
  20348. // Deep copy
  20349. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  20350. // Bounding info
  20351. this.refreshBoundingInfo();
  20352. // Parent
  20353. if (newParent) {
  20354. result.parent = newParent;
  20355. }
  20356. if (!doNotCloneChildren) {
  20357. // Children
  20358. for (var index = 0; index < this.getScene().meshes.length; index++) {
  20359. var mesh = this.getScene().meshes[index];
  20360. if (mesh.parent === this) {
  20361. mesh.clone(mesh.name, result);
  20362. }
  20363. }
  20364. }
  20365. result.computeWorldMatrix(true);
  20366. return result;
  20367. };
  20368. // Dispose
  20369. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  20370. // Remove from mesh
  20371. var index = this._sourceMesh.instances.indexOf(this);
  20372. this._sourceMesh.instances.splice(index, 1);
  20373. _super.prototype.dispose.call(this, doNotRecurse);
  20374. };
  20375. return InstancedMesh;
  20376. }(BABYLON.AbstractMesh));
  20377. BABYLON.InstancedMesh = InstancedMesh;
  20378. })(BABYLON || (BABYLON = {}));
  20379. //# sourceMappingURL=babylon.instancedMesh.js.map
  20380. var BABYLON;
  20381. (function (BABYLON) {
  20382. var _InstancesBatch = (function () {
  20383. function _InstancesBatch() {
  20384. this.mustReturn = false;
  20385. this.visibleInstances = new Array();
  20386. this.renderSelf = new Array();
  20387. }
  20388. return _InstancesBatch;
  20389. }());
  20390. BABYLON._InstancesBatch = _InstancesBatch;
  20391. var Mesh = (function (_super) {
  20392. __extends(Mesh, _super);
  20393. /**
  20394. * @constructor
  20395. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20396. * @param {Scene} scene The scene to add this mesh to.
  20397. * @param {Node} parent The parent of this mesh, if it has one
  20398. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20399. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20400. * When false, achieved by calling a clone(), also passing False.
  20401. * This will make creation of children, recursive.
  20402. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20403. */
  20404. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20405. if (parent === void 0) { parent = null; }
  20406. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20407. var _this = _super.call(this, name, scene) || this;
  20408. // Events
  20409. /**
  20410. * An event triggered before rendering the mesh
  20411. * @type {BABYLON.Observable}
  20412. */
  20413. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20414. /**
  20415. * An event triggered after rendering the mesh
  20416. * @type {BABYLON.Observable}
  20417. */
  20418. _this.onAfterRenderObservable = new BABYLON.Observable();
  20419. /**
  20420. * An event triggered before drawing the mesh
  20421. * @type {BABYLON.Observable}
  20422. */
  20423. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20424. // Members
  20425. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20426. _this.instances = new Array();
  20427. _this._LODLevels = new Array();
  20428. _this._visibleInstances = {};
  20429. _this._renderIdForInstances = new Array();
  20430. _this._batchCache = new _InstancesBatch();
  20431. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20432. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20433. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20434. // Will be used to save a source mesh reference, If any
  20435. _this._source = null;
  20436. if (source) {
  20437. // Source mesh
  20438. _this._source = source;
  20439. // Geometry
  20440. if (source._geometry) {
  20441. source._geometry.applyToMesh(_this);
  20442. }
  20443. // Deep copy
  20444. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  20445. // Parent
  20446. _this.parent = source.parent;
  20447. // Pivot
  20448. _this.setPivotMatrix(source.getPivotMatrix());
  20449. _this.id = name + "." + source.id;
  20450. // Material
  20451. _this.material = source.material;
  20452. var index;
  20453. if (!doNotCloneChildren) {
  20454. // Children
  20455. for (index = 0; index < scene.meshes.length; index++) {
  20456. var mesh = scene.meshes[index];
  20457. if (mesh.parent === source) {
  20458. // doNotCloneChildren is always going to be False
  20459. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20460. }
  20461. }
  20462. }
  20463. // Physics clone
  20464. var physicsEngine = _this.getScene().getPhysicsEngine();
  20465. if (clonePhysicsImpostor && physicsEngine) {
  20466. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20467. if (impostor) {
  20468. _this.physicsImpostor = impostor.clone(_this);
  20469. }
  20470. }
  20471. // Particles
  20472. for (index = 0; index < scene.particleSystems.length; index++) {
  20473. var system = scene.particleSystems[index];
  20474. if (system.emitter === source) {
  20475. system.clone(system.name, _this);
  20476. }
  20477. }
  20478. _this.computeWorldMatrix(true);
  20479. }
  20480. // Parent
  20481. if (parent !== null) {
  20482. _this.parent = parent;
  20483. }
  20484. return _this;
  20485. }
  20486. Object.defineProperty(Mesh, "FRONTSIDE", {
  20487. /**
  20488. * Mesh side orientation : usually the external or front surface
  20489. */
  20490. get: function () {
  20491. return Mesh._FRONTSIDE;
  20492. },
  20493. enumerable: true,
  20494. configurable: true
  20495. });
  20496. Object.defineProperty(Mesh, "BACKSIDE", {
  20497. /**
  20498. * Mesh side orientation : usually the internal or back surface
  20499. */
  20500. get: function () {
  20501. return Mesh._BACKSIDE;
  20502. },
  20503. enumerable: true,
  20504. configurable: true
  20505. });
  20506. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20507. /**
  20508. * Mesh side orientation : both internal and external or front and back surfaces
  20509. */
  20510. get: function () {
  20511. return Mesh._DOUBLESIDE;
  20512. },
  20513. enumerable: true,
  20514. configurable: true
  20515. });
  20516. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20517. /**
  20518. * Mesh side orientation : by default, `FRONTSIDE`
  20519. */
  20520. get: function () {
  20521. return Mesh._DEFAULTSIDE;
  20522. },
  20523. enumerable: true,
  20524. configurable: true
  20525. });
  20526. Object.defineProperty(Mesh, "NO_CAP", {
  20527. /**
  20528. * Mesh cap setting : no cap
  20529. */
  20530. get: function () {
  20531. return Mesh._NO_CAP;
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. Object.defineProperty(Mesh, "CAP_START", {
  20537. /**
  20538. * Mesh cap setting : one cap at the beginning of the mesh
  20539. */
  20540. get: function () {
  20541. return Mesh._CAP_START;
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Object.defineProperty(Mesh, "CAP_END", {
  20547. /**
  20548. * Mesh cap setting : one cap at the end of the mesh
  20549. */
  20550. get: function () {
  20551. return Mesh._CAP_END;
  20552. },
  20553. enumerable: true,
  20554. configurable: true
  20555. });
  20556. Object.defineProperty(Mesh, "CAP_ALL", {
  20557. /**
  20558. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20559. */
  20560. get: function () {
  20561. return Mesh._CAP_ALL;
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20567. set: function (callback) {
  20568. if (this._onBeforeDrawObserver) {
  20569. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20570. }
  20571. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20572. },
  20573. enumerable: true,
  20574. configurable: true
  20575. });
  20576. Object.defineProperty(Mesh.prototype, "source", {
  20577. get: function () {
  20578. return this._source;
  20579. },
  20580. enumerable: true,
  20581. configurable: true
  20582. });
  20583. // Methods
  20584. Mesh.prototype.getClassName = function () {
  20585. return "Mesh";
  20586. };
  20587. /**
  20588. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20589. */
  20590. Mesh.prototype.toString = function (fullDetails) {
  20591. var ret = _super.prototype.toString.call(this, fullDetails);
  20592. ret += ", n vertices: " + this.getTotalVertices();
  20593. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20594. if (this.animations) {
  20595. for (var i = 0; i < this.animations.length; i++) {
  20596. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20597. }
  20598. }
  20599. if (fullDetails) {
  20600. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20601. }
  20602. return ret;
  20603. };
  20604. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20605. get: function () {
  20606. return this._LODLevels.length > 0;
  20607. },
  20608. enumerable: true,
  20609. configurable: true
  20610. });
  20611. Mesh.prototype._sortLODLevels = function () {
  20612. this._LODLevels.sort(function (a, b) {
  20613. if (a.distance < b.distance) {
  20614. return 1;
  20615. }
  20616. if (a.distance > b.distance) {
  20617. return -1;
  20618. }
  20619. return 0;
  20620. });
  20621. };
  20622. /**
  20623. * Add a mesh as LOD level triggered at the given distance.
  20624. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20625. * @param {number} distance The distance from the center of the object to show this level
  20626. * @param {Mesh} mesh The mesh to be added as LOD level
  20627. * @return {Mesh} This mesh (for chaining)
  20628. */
  20629. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20630. if (mesh && mesh._masterMesh) {
  20631. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20632. return this;
  20633. }
  20634. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20635. this._LODLevels.push(level);
  20636. if (mesh) {
  20637. mesh._masterMesh = this;
  20638. }
  20639. this._sortLODLevels();
  20640. return this;
  20641. };
  20642. /**
  20643. * Returns the LOD level mesh at the passed distance or null if not found.
  20644. * It is related to the method `addLODLevel(distance, mesh)`.
  20645. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20646. */
  20647. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20648. for (var index = 0; index < this._LODLevels.length; index++) {
  20649. var level = this._LODLevels[index];
  20650. if (level.distance === distance) {
  20651. return level.mesh;
  20652. }
  20653. }
  20654. return null;
  20655. };
  20656. /**
  20657. * Remove a mesh from the LOD array
  20658. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20659. * @param {Mesh} mesh The mesh to be removed.
  20660. * @return {Mesh} This mesh (for chaining)
  20661. */
  20662. Mesh.prototype.removeLODLevel = function (mesh) {
  20663. for (var index = 0; index < this._LODLevels.length; index++) {
  20664. if (this._LODLevels[index].mesh === mesh) {
  20665. this._LODLevels.splice(index, 1);
  20666. if (mesh) {
  20667. mesh._masterMesh = null;
  20668. }
  20669. }
  20670. }
  20671. this._sortLODLevels();
  20672. return this;
  20673. };
  20674. /**
  20675. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20676. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20677. */
  20678. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20679. if (!this._LODLevels || this._LODLevels.length === 0) {
  20680. return this;
  20681. }
  20682. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20683. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20684. if (this.onLODLevelSelection) {
  20685. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20686. }
  20687. return this;
  20688. }
  20689. for (var index = 0; index < this._LODLevels.length; index++) {
  20690. var level = this._LODLevels[index];
  20691. if (level.distance < distanceToCamera) {
  20692. if (level.mesh) {
  20693. level.mesh._preActivate();
  20694. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20695. }
  20696. if (this.onLODLevelSelection) {
  20697. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20698. }
  20699. return level.mesh;
  20700. }
  20701. }
  20702. if (this.onLODLevelSelection) {
  20703. this.onLODLevelSelection(distanceToCamera, this, this);
  20704. }
  20705. return this;
  20706. };
  20707. Object.defineProperty(Mesh.prototype, "geometry", {
  20708. /**
  20709. * Returns the mesh internal Geometry object.
  20710. */
  20711. get: function () {
  20712. return this._geometry;
  20713. },
  20714. enumerable: true,
  20715. configurable: true
  20716. });
  20717. /**
  20718. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20719. */
  20720. Mesh.prototype.getTotalVertices = function () {
  20721. if (!this._geometry) {
  20722. return 0;
  20723. }
  20724. return this._geometry.getTotalVertices();
  20725. };
  20726. /**
  20727. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20728. * 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.
  20729. * Returns null if the mesh has no geometry or no vertex buffer.
  20730. * Possible `kind` values :
  20731. * - BABYLON.VertexBuffer.PositionKind
  20732. * - BABYLON.VertexBuffer.UVKind
  20733. * - BABYLON.VertexBuffer.UV2Kind
  20734. * - BABYLON.VertexBuffer.UV3Kind
  20735. * - BABYLON.VertexBuffer.UV4Kind
  20736. * - BABYLON.VertexBuffer.UV5Kind
  20737. * - BABYLON.VertexBuffer.UV6Kind
  20738. * - BABYLON.VertexBuffer.ColorKind
  20739. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20740. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20741. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20742. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20743. */
  20744. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20745. if (!this._geometry) {
  20746. return null;
  20747. }
  20748. return this._geometry.getVerticesData(kind, copyWhenShared);
  20749. };
  20750. /**
  20751. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20752. * Returns `undefined` if the mesh has no geometry.
  20753. * Possible `kind` values :
  20754. * - BABYLON.VertexBuffer.PositionKind
  20755. * - BABYLON.VertexBuffer.UVKind
  20756. * - BABYLON.VertexBuffer.UV2Kind
  20757. * - BABYLON.VertexBuffer.UV3Kind
  20758. * - BABYLON.VertexBuffer.UV4Kind
  20759. * - BABYLON.VertexBuffer.UV5Kind
  20760. * - BABYLON.VertexBuffer.UV6Kind
  20761. * - BABYLON.VertexBuffer.ColorKind
  20762. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20763. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20764. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20765. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20766. */
  20767. Mesh.prototype.getVertexBuffer = function (kind) {
  20768. if (!this._geometry) {
  20769. return undefined;
  20770. }
  20771. return this._geometry.getVertexBuffer(kind);
  20772. };
  20773. /**
  20774. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20775. * Possible `kind` values :
  20776. * - BABYLON.VertexBuffer.PositionKind
  20777. * - BABYLON.VertexBuffer.UVKind
  20778. * - BABYLON.VertexBuffer.UV2Kind
  20779. * - BABYLON.VertexBuffer.UV3Kind
  20780. * - BABYLON.VertexBuffer.UV4Kind
  20781. * - BABYLON.VertexBuffer.UV5Kind
  20782. * - BABYLON.VertexBuffer.UV6Kind
  20783. * - BABYLON.VertexBuffer.ColorKind
  20784. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20785. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20786. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20787. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20788. */
  20789. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20790. if (!this._geometry) {
  20791. if (this._delayInfo) {
  20792. return this._delayInfo.indexOf(kind) !== -1;
  20793. }
  20794. return false;
  20795. }
  20796. return this._geometry.isVerticesDataPresent(kind);
  20797. };
  20798. /**
  20799. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20800. * Possible `kind` values :
  20801. * - BABYLON.VertexBuffer.PositionKind
  20802. * - BABYLON.VertexBuffer.UVKind
  20803. * - BABYLON.VertexBuffer.UV2Kind
  20804. * - BABYLON.VertexBuffer.UV3Kind
  20805. * - BABYLON.VertexBuffer.UV4Kind
  20806. * - BABYLON.VertexBuffer.UV5Kind
  20807. * - BABYLON.VertexBuffer.UV6Kind
  20808. * - BABYLON.VertexBuffer.ColorKind
  20809. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20810. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20811. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20812. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20813. */
  20814. Mesh.prototype.getVerticesDataKinds = function () {
  20815. if (!this._geometry) {
  20816. var result = [];
  20817. if (this._delayInfo) {
  20818. this._delayInfo.forEach(function (kind, index, array) {
  20819. result.push(kind);
  20820. });
  20821. }
  20822. return result;
  20823. }
  20824. return this._geometry.getVerticesDataKinds();
  20825. };
  20826. /**
  20827. * Returns a positive integer : the total number of indices in this mesh geometry.
  20828. * Returns zero if the mesh has no geometry.
  20829. */
  20830. Mesh.prototype.getTotalIndices = function () {
  20831. if (!this._geometry) {
  20832. return 0;
  20833. }
  20834. return this._geometry.getTotalIndices();
  20835. };
  20836. /**
  20837. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20838. * 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.
  20839. * Returns an empty array if the mesh has no geometry.
  20840. */
  20841. Mesh.prototype.getIndices = function (copyWhenShared) {
  20842. if (!this._geometry) {
  20843. return [];
  20844. }
  20845. return this._geometry.getIndices(copyWhenShared);
  20846. };
  20847. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20848. get: function () {
  20849. return this._masterMesh !== null && this._masterMesh !== undefined;
  20850. },
  20851. enumerable: true,
  20852. configurable: true
  20853. });
  20854. /**
  20855. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20856. */
  20857. Mesh.prototype.isReady = function () {
  20858. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20859. return false;
  20860. }
  20861. return _super.prototype.isReady.call(this);
  20862. };
  20863. /**
  20864. * Boolean : true if the mesh has been disposed.
  20865. */
  20866. Mesh.prototype.isDisposed = function () {
  20867. return this._isDisposed;
  20868. };
  20869. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20870. get: function () {
  20871. return this._sideOrientation;
  20872. },
  20873. /**
  20874. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20875. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20876. */
  20877. set: function (sideO) {
  20878. this._sideOrientation = sideO;
  20879. },
  20880. enumerable: true,
  20881. configurable: true
  20882. });
  20883. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20884. /**
  20885. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20886. * This property is pertinent only for updatable parametric shapes.
  20887. */
  20888. get: function () {
  20889. return this._areNormalsFrozen;
  20890. },
  20891. enumerable: true,
  20892. configurable: true
  20893. });
  20894. /**
  20895. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20896. * It has no effect at all on other shapes.
  20897. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20898. */
  20899. Mesh.prototype.freezeNormals = function () {
  20900. this._areNormalsFrozen = true;
  20901. };
  20902. /**
  20903. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20904. * It has no effect at all on other shapes.
  20905. * It reactivates the mesh normals computation if it was previously frozen.
  20906. */
  20907. Mesh.prototype.unfreezeNormals = function () {
  20908. this._areNormalsFrozen = false;
  20909. };
  20910. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20911. /**
  20912. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20913. */
  20914. set: function (count) {
  20915. this._overridenInstanceCount = count;
  20916. },
  20917. enumerable: true,
  20918. configurable: true
  20919. });
  20920. // Methods
  20921. Mesh.prototype._preActivate = function () {
  20922. var sceneRenderId = this.getScene().getRenderId();
  20923. if (this._preActivateId === sceneRenderId) {
  20924. return;
  20925. }
  20926. this._preActivateId = sceneRenderId;
  20927. this._visibleInstances = null;
  20928. };
  20929. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20930. if (this._visibleInstances) {
  20931. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20932. }
  20933. };
  20934. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20935. if (!this._visibleInstances) {
  20936. this._visibleInstances = {};
  20937. this._visibleInstances.defaultRenderId = renderId;
  20938. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20939. }
  20940. if (!this._visibleInstances[renderId]) {
  20941. this._visibleInstances[renderId] = new Array();
  20942. }
  20943. this._visibleInstances[renderId].push(instance);
  20944. };
  20945. /**
  20946. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20947. * This means the mesh underlying bounding box and sphere are recomputed.
  20948. */
  20949. Mesh.prototype.refreshBoundingInfo = function () {
  20950. if (this._boundingInfo.isLocked) {
  20951. return;
  20952. }
  20953. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20954. if (data) {
  20955. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20956. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20957. }
  20958. if (this.subMeshes) {
  20959. for (var index = 0; index < this.subMeshes.length; index++) {
  20960. this.subMeshes[index].refreshBoundingInfo();
  20961. }
  20962. }
  20963. this._updateBoundingInfo();
  20964. };
  20965. Mesh.prototype._createGlobalSubMesh = function () {
  20966. var totalVertices = this.getTotalVertices();
  20967. if (!totalVertices || !this.getIndices()) {
  20968. return null;
  20969. }
  20970. this.releaseSubMeshes();
  20971. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20972. };
  20973. Mesh.prototype.subdivide = function (count) {
  20974. if (count < 1) {
  20975. return;
  20976. }
  20977. var totalIndices = this.getTotalIndices();
  20978. var subdivisionSize = (totalIndices / count) | 0;
  20979. var offset = 0;
  20980. // Ensure that subdivisionSize is a multiple of 3
  20981. while (subdivisionSize % 3 !== 0) {
  20982. subdivisionSize++;
  20983. }
  20984. this.releaseSubMeshes();
  20985. for (var index = 0; index < count; index++) {
  20986. if (offset >= totalIndices) {
  20987. break;
  20988. }
  20989. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20990. offset += subdivisionSize;
  20991. }
  20992. this.synchronizeInstances();
  20993. };
  20994. /**
  20995. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20996. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20997. * The `data` are either a numeric array either a Float32Array.
  20998. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20999. * 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).
  21000. * Note that a new underlying VertexBuffer object is created each call.
  21001. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21002. *
  21003. * Possible `kind` values :
  21004. * - BABYLON.VertexBuffer.PositionKind
  21005. * - BABYLON.VertexBuffer.UVKind
  21006. * - BABYLON.VertexBuffer.UV2Kind
  21007. * - BABYLON.VertexBuffer.UV3Kind
  21008. * - BABYLON.VertexBuffer.UV4Kind
  21009. * - BABYLON.VertexBuffer.UV5Kind
  21010. * - BABYLON.VertexBuffer.UV6Kind
  21011. * - BABYLON.VertexBuffer.ColorKind
  21012. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21013. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21014. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21015. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21016. */
  21017. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21018. if (!this._geometry) {
  21019. var vertexData = new BABYLON.VertexData();
  21020. vertexData.set(data, kind);
  21021. var scene = this.getScene();
  21022. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21023. }
  21024. else {
  21025. this._geometry.setVerticesData(kind, data, updatable, stride);
  21026. }
  21027. };
  21028. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21029. if (!this._geometry) {
  21030. var scene = this.getScene();
  21031. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21032. }
  21033. this._geometry.setVerticesBuffer(buffer);
  21034. };
  21035. /**
  21036. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21037. * If the mesh has no geometry, it is simply returned as it is.
  21038. * The `data` are either a numeric array either a Float32Array.
  21039. * No new underlying VertexBuffer object is created.
  21040. * 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.
  21041. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21042. *
  21043. * Possible `kind` values :
  21044. * - BABYLON.VertexBuffer.PositionKind
  21045. * - BABYLON.VertexBuffer.UVKind
  21046. * - BABYLON.VertexBuffer.UV2Kind
  21047. * - BABYLON.VertexBuffer.UV3Kind
  21048. * - BABYLON.VertexBuffer.UV4Kind
  21049. * - BABYLON.VertexBuffer.UV5Kind
  21050. * - BABYLON.VertexBuffer.UV6Kind
  21051. * - BABYLON.VertexBuffer.ColorKind
  21052. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21053. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21054. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21055. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21056. */
  21057. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21058. if (!this._geometry) {
  21059. return;
  21060. }
  21061. if (!makeItUnique) {
  21062. this._geometry.updateVerticesData(kind, data, updateExtends);
  21063. }
  21064. else {
  21065. this.makeGeometryUnique();
  21066. this.updateVerticesData(kind, data, updateExtends, false);
  21067. }
  21068. };
  21069. /**
  21070. * Deprecated since BabylonJS v2.3
  21071. */
  21072. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  21073. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  21074. if (!this._geometry) {
  21075. return;
  21076. }
  21077. if (!makeItUnique) {
  21078. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  21079. }
  21080. else {
  21081. this.makeGeometryUnique();
  21082. this.updateVerticesDataDirectly(kind, data, offset, false);
  21083. }
  21084. };
  21085. /**
  21086. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21087. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21088. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21089. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21090. */
  21091. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21092. if (computeNormals === void 0) { computeNormals = true; }
  21093. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21094. positionFunction(positions);
  21095. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21096. if (computeNormals) {
  21097. var indices = this.getIndices();
  21098. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21099. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21100. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21101. }
  21102. };
  21103. Mesh.prototype.makeGeometryUnique = function () {
  21104. if (!this._geometry) {
  21105. return;
  21106. }
  21107. var oldGeometry = this._geometry;
  21108. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21109. oldGeometry.releaseForMesh(this, true);
  21110. geometry.applyToMesh(this);
  21111. };
  21112. /**
  21113. * Sets the mesh indices.
  21114. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21115. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21116. * This method creates a new index buffer each call.
  21117. */
  21118. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21119. if (!this._geometry) {
  21120. var vertexData = new BABYLON.VertexData();
  21121. vertexData.indices = indices;
  21122. var scene = this.getScene();
  21123. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21124. }
  21125. else {
  21126. this._geometry.setIndices(indices, totalVertices);
  21127. }
  21128. };
  21129. /**
  21130. * Invert the geometry to move from a right handed system to a left handed one.
  21131. */
  21132. Mesh.prototype.toLeftHanded = function () {
  21133. if (!this._geometry) {
  21134. return;
  21135. }
  21136. this._geometry.toLeftHanded();
  21137. };
  21138. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21139. var engine = this.getScene().getEngine();
  21140. // Wireframe
  21141. var indexToBind;
  21142. if (this._unIndexed) {
  21143. indexToBind = null;
  21144. }
  21145. else {
  21146. switch (fillMode) {
  21147. case BABYLON.Material.PointFillMode:
  21148. indexToBind = null;
  21149. break;
  21150. case BABYLON.Material.WireFrameFillMode:
  21151. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21152. break;
  21153. default:
  21154. case BABYLON.Material.TriangleFillMode:
  21155. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21156. break;
  21157. }
  21158. }
  21159. // VBOs
  21160. this._geometry._bind(effect, indexToBind);
  21161. };
  21162. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21163. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21164. return;
  21165. }
  21166. this.onBeforeDrawObservable.notifyObservers(this);
  21167. var engine = this.getScene().getEngine();
  21168. // Draw order
  21169. switch (fillMode) {
  21170. case BABYLON.Material.PointFillMode:
  21171. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21172. break;
  21173. case BABYLON.Material.WireFrameFillMode:
  21174. if (this._unIndexed) {
  21175. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21176. }
  21177. else {
  21178. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21179. }
  21180. break;
  21181. default:
  21182. if (this._unIndexed) {
  21183. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21184. }
  21185. else {
  21186. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21187. }
  21188. }
  21189. };
  21190. /**
  21191. * Registers for this mesh a javascript function called just before the rendering process.
  21192. * This function is passed the current mesh and doesn't return anything.
  21193. */
  21194. Mesh.prototype.registerBeforeRender = function (func) {
  21195. this.onBeforeRenderObservable.add(func);
  21196. };
  21197. /**
  21198. * Disposes a previously registered javascript function called before the rendering.
  21199. * This function is passed the current mesh and doesn't return anything.
  21200. */
  21201. Mesh.prototype.unregisterBeforeRender = function (func) {
  21202. this.onBeforeRenderObservable.removeCallback(func);
  21203. };
  21204. /**
  21205. * Registers for this mesh a javascript function called just after the rendering is complete.
  21206. * This function is passed the current mesh and doesn't return anything.
  21207. */
  21208. Mesh.prototype.registerAfterRender = function (func) {
  21209. this.onAfterRenderObservable.add(func);
  21210. };
  21211. /**
  21212. * Disposes a previously registered javascript function called after the rendering.
  21213. * This function is passed the current mesh and doesn't return anything.
  21214. */
  21215. Mesh.prototype.unregisterAfterRender = function (func) {
  21216. this.onAfterRenderObservable.removeCallback(func);
  21217. };
  21218. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21219. var scene = this.getScene();
  21220. this._batchCache.mustReturn = false;
  21221. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21222. this._batchCache.visibleInstances[subMeshId] = null;
  21223. if (this._visibleInstances) {
  21224. var currentRenderId = scene.getRenderId();
  21225. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21226. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21227. var selfRenderId = this._renderId;
  21228. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21229. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21230. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21231. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21232. }
  21233. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21234. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21235. this._batchCache.mustReturn = true;
  21236. return this._batchCache;
  21237. }
  21238. if (currentRenderId !== selfRenderId) {
  21239. this._batchCache.renderSelf[subMeshId] = false;
  21240. }
  21241. }
  21242. this._renderIdForInstances[subMeshId] = currentRenderId;
  21243. }
  21244. return this._batchCache;
  21245. };
  21246. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21247. var visibleInstances = batch.visibleInstances[subMesh._id];
  21248. var matricesCount = visibleInstances.length + 1;
  21249. var bufferSize = matricesCount * 16 * 4;
  21250. var currentInstancesBufferSize = this._instancesBufferSize;
  21251. var instancesBuffer = this._instancesBuffer;
  21252. while (this._instancesBufferSize < bufferSize) {
  21253. this._instancesBufferSize *= 2;
  21254. }
  21255. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21256. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21257. }
  21258. var offset = 0;
  21259. var instancesCount = 0;
  21260. var world = this.getWorldMatrix();
  21261. if (batch.renderSelf[subMesh._id]) {
  21262. world.copyToArray(this._instancesData, offset);
  21263. offset += 16;
  21264. instancesCount++;
  21265. }
  21266. if (visibleInstances) {
  21267. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21268. var instance = visibleInstances[instanceIndex];
  21269. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21270. offset += 16;
  21271. instancesCount++;
  21272. }
  21273. }
  21274. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21275. if (instancesBuffer) {
  21276. instancesBuffer.dispose();
  21277. }
  21278. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21279. this._instancesBuffer = instancesBuffer;
  21280. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21283. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21284. }
  21285. else {
  21286. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21287. }
  21288. this.geometry._bind(effect);
  21289. this._draw(subMesh, fillMode, instancesCount);
  21290. engine.unbindInstanceAttributes();
  21291. };
  21292. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21293. var scene = this.getScene();
  21294. var engine = scene.getEngine();
  21295. if (hardwareInstancedRendering) {
  21296. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21297. }
  21298. else {
  21299. if (batch.renderSelf[subMesh._id]) {
  21300. // Draw
  21301. if (onBeforeDraw) {
  21302. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21303. }
  21304. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21305. }
  21306. if (batch.visibleInstances[subMesh._id]) {
  21307. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21308. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21309. // World
  21310. var world = instance.getWorldMatrix();
  21311. if (onBeforeDraw) {
  21312. onBeforeDraw(true, world, effectiveMaterial);
  21313. }
  21314. // Draw
  21315. this._draw(subMesh, fillMode);
  21316. }
  21317. }
  21318. }
  21319. };
  21320. /**
  21321. * Triggers the draw call for the mesh.
  21322. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21323. */
  21324. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21325. var scene = this.getScene();
  21326. // Managing instances
  21327. var batch = this._getInstancesRenderList(subMesh._id);
  21328. if (batch.mustReturn) {
  21329. return;
  21330. }
  21331. // Checking geometry state
  21332. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21333. return;
  21334. }
  21335. var callbackIndex;
  21336. this.onBeforeRenderObservable.notifyObservers(this);
  21337. var engine = scene.getEngine();
  21338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21339. // Material
  21340. var effectiveMaterial = subMesh.getMaterial();
  21341. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21342. return;
  21343. }
  21344. // Outline - step 1
  21345. var savedDepthWrite = engine.getDepthWrite();
  21346. if (this.renderOutline) {
  21347. engine.setDepthWrite(false);
  21348. scene.getOutlineRenderer().render(subMesh, batch);
  21349. engine.setDepthWrite(savedDepthWrite);
  21350. }
  21351. effectiveMaterial._preBind();
  21352. var effect = effectiveMaterial.getEffect();
  21353. // Bind
  21354. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21355. this._bind(subMesh, effect, fillMode);
  21356. var world = this.getWorldMatrix();
  21357. effectiveMaterial.bind(world, this);
  21358. // Alpha mode
  21359. if (enableAlphaMode) {
  21360. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21361. }
  21362. // Draw
  21363. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21364. // Unbind
  21365. effectiveMaterial.unbind();
  21366. // Outline - step 2
  21367. if (this.renderOutline && savedDepthWrite) {
  21368. engine.setDepthWrite(true);
  21369. engine.setColorWrite(false);
  21370. scene.getOutlineRenderer().render(subMesh, batch);
  21371. engine.setColorWrite(true);
  21372. }
  21373. // Overlay
  21374. if (this.renderOverlay) {
  21375. var currentMode = engine.getAlphaMode();
  21376. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21377. scene.getOutlineRenderer().render(subMesh, batch, true);
  21378. engine.setAlphaMode(currentMode);
  21379. }
  21380. this.onAfterRenderObservable.notifyObservers(this);
  21381. };
  21382. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21383. if (isInstance) {
  21384. effectiveMaterial.bindOnlyWorldMatrix(world);
  21385. }
  21386. };
  21387. /**
  21388. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21389. */
  21390. Mesh.prototype.getEmittedParticleSystems = function () {
  21391. var results = new Array();
  21392. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21393. var particleSystem = this.getScene().particleSystems[index];
  21394. if (particleSystem.emitter === this) {
  21395. results.push(particleSystem);
  21396. }
  21397. }
  21398. return results;
  21399. };
  21400. /**
  21401. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21402. */
  21403. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21404. var results = new Array();
  21405. var descendants = this.getDescendants();
  21406. descendants.push(this);
  21407. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21408. var particleSystem = this.getScene().particleSystems[index];
  21409. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  21410. results.push(particleSystem);
  21411. }
  21412. }
  21413. return results;
  21414. };
  21415. Mesh.prototype._checkDelayState = function () {
  21416. var scene = this.getScene();
  21417. if (this._geometry) {
  21418. this._geometry.load(scene);
  21419. }
  21420. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21421. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21422. this._queueLoad(this, scene);
  21423. }
  21424. };
  21425. Mesh.prototype._queueLoad = function (mesh, scene) {
  21426. var _this = this;
  21427. scene._addPendingData(mesh);
  21428. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21429. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21430. if (data instanceof ArrayBuffer) {
  21431. _this._delayLoadingFunction(data, _this);
  21432. }
  21433. else {
  21434. _this._delayLoadingFunction(JSON.parse(data), _this);
  21435. }
  21436. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21437. scene._removePendingData(_this);
  21438. }, function () { }, scene.database, getBinaryData);
  21439. };
  21440. /**
  21441. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21442. */
  21443. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21444. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21445. return false;
  21446. }
  21447. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21448. return false;
  21449. }
  21450. this._checkDelayState();
  21451. return true;
  21452. };
  21453. /**
  21454. * Sets the mesh material by the material or multiMaterial `id` property.
  21455. * The material `id` is a string identifying the material or the multiMaterial.
  21456. * This method returns nothing.
  21457. */
  21458. Mesh.prototype.setMaterialByID = function (id) {
  21459. var materials = this.getScene().materials;
  21460. var index;
  21461. for (index = 0; index < materials.length; index++) {
  21462. if (materials[index].id === id) {
  21463. this.material = materials[index];
  21464. return;
  21465. }
  21466. }
  21467. // Multi
  21468. var multiMaterials = this.getScene().multiMaterials;
  21469. for (index = 0; index < multiMaterials.length; index++) {
  21470. if (multiMaterials[index].id === id) {
  21471. this.material = multiMaterials[index];
  21472. return;
  21473. }
  21474. }
  21475. };
  21476. /**
  21477. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21478. */
  21479. Mesh.prototype.getAnimatables = function () {
  21480. var results = [];
  21481. if (this.material) {
  21482. results.push(this.material);
  21483. }
  21484. if (this.skeleton) {
  21485. results.push(this.skeleton);
  21486. }
  21487. return results;
  21488. };
  21489. /**
  21490. * Modifies the mesh geometry according to the passed transformation matrix.
  21491. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21492. * The mesh normals are modified accordingly the same transformation.
  21493. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21494. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21495. */
  21496. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21497. // Position
  21498. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21499. return;
  21500. }
  21501. var submeshes = this.subMeshes.splice(0);
  21502. this._resetPointsArrayCache();
  21503. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21504. var temp = [];
  21505. var index;
  21506. for (index = 0; index < data.length; index += 3) {
  21507. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21508. }
  21509. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21510. // Normals
  21511. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21512. return;
  21513. }
  21514. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21515. temp = [];
  21516. for (index = 0; index < data.length; index += 3) {
  21517. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21518. }
  21519. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21520. // flip faces?
  21521. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21522. this.flipFaces();
  21523. }
  21524. // Restore submeshes
  21525. this.releaseSubMeshes();
  21526. this.subMeshes = submeshes;
  21527. };
  21528. /**
  21529. * Modifies the mesh geometry according to its own current World Matrix.
  21530. * The mesh World Matrix is then reset.
  21531. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21532. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21533. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21534. */
  21535. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21536. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21537. this.scaling.copyFromFloats(1, 1, 1);
  21538. this.position.copyFromFloats(0, 0, 0);
  21539. this.rotation.copyFromFloats(0, 0, 0);
  21540. //only if quaternion is already set
  21541. if (this.rotationQuaternion) {
  21542. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21543. }
  21544. this._worldMatrix = BABYLON.Matrix.Identity();
  21545. };
  21546. // Cache
  21547. Mesh.prototype._resetPointsArrayCache = function () {
  21548. this._positions = null;
  21549. };
  21550. Mesh.prototype._generatePointsArray = function () {
  21551. if (this._positions)
  21552. return true;
  21553. this._positions = [];
  21554. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21555. if (!data) {
  21556. return false;
  21557. }
  21558. for (var index = 0; index < data.length; index += 3) {
  21559. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  21560. }
  21561. return true;
  21562. };
  21563. /**
  21564. * Returns a new Mesh object generated from the current mesh properties.
  21565. * This method must not get confused with createInstance().
  21566. * The parameter `name` is a string, the name given to the new mesh.
  21567. * The optional parameter `newParent` can be any Node object (default `null`).
  21568. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21569. * 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.
  21570. */
  21571. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21572. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21573. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21574. };
  21575. /**
  21576. * Disposes the mesh.
  21577. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21578. */
  21579. Mesh.prototype.dispose = function (doNotRecurse) {
  21580. var _this = this;
  21581. if (this._geometry) {
  21582. this._geometry.releaseForMesh(this, true);
  21583. }
  21584. // Sources
  21585. var meshes = this.getScene().meshes;
  21586. meshes.forEach(function (mesh) {
  21587. if (mesh._source && mesh._source === _this) {
  21588. mesh._source = null;
  21589. }
  21590. });
  21591. this._source = null;
  21592. // Instances
  21593. if (this._instancesBuffer) {
  21594. this._instancesBuffer.dispose();
  21595. this._instancesBuffer = null;
  21596. }
  21597. while (this.instances.length) {
  21598. this.instances[0].dispose();
  21599. }
  21600. // Highlight layers.
  21601. var highlightLayers = this.getScene().highlightLayers;
  21602. for (var i = 0; i < highlightLayers.length; i++) {
  21603. var highlightLayer = highlightLayers[i];
  21604. if (highlightLayer) {
  21605. highlightLayer.removeMesh(this);
  21606. highlightLayer.removeExcludedMesh(this);
  21607. }
  21608. }
  21609. _super.prototype.dispose.call(this, doNotRecurse);
  21610. };
  21611. /**
  21612. * Modifies the mesh geometry according to a displacement map.
  21613. * 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.
  21614. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21615. * This method returns nothing.
  21616. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21617. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21618. * 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.
  21619. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21620. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21621. */
  21622. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21623. var _this = this;
  21624. var scene = this.getScene();
  21625. var onload = function (img) {
  21626. // Getting height map data
  21627. var canvas = document.createElement("canvas");
  21628. var context = canvas.getContext("2d");
  21629. var heightMapWidth = img.width;
  21630. var heightMapHeight = img.height;
  21631. canvas.width = heightMapWidth;
  21632. canvas.height = heightMapHeight;
  21633. context.drawImage(img, 0, 0);
  21634. // Create VertexData from map data
  21635. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21636. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21637. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21638. //execute success callback, if set
  21639. if (onSuccess) {
  21640. onSuccess(_this);
  21641. }
  21642. };
  21643. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21644. };
  21645. /**
  21646. * Modifies the mesh geometry according to a displacementMap buffer.
  21647. * 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.
  21648. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21649. * This method returns nothing.
  21650. * 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.
  21651. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21652. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21653. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21654. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21655. */
  21656. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21658. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21659. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21660. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21661. return;
  21662. }
  21663. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21664. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21665. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21666. var position = BABYLON.Vector3.Zero();
  21667. var normal = BABYLON.Vector3.Zero();
  21668. var uv = BABYLON.Vector2.Zero();
  21669. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21670. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21671. for (var index = 0; index < positions.length; index += 3) {
  21672. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21673. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21674. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21675. // Compute height
  21676. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21677. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21678. var pos = (u + v * heightMapWidth) * 4;
  21679. var r = buffer[pos] / 255.0;
  21680. var g = buffer[pos + 1] / 255.0;
  21681. var b = buffer[pos + 2] / 255.0;
  21682. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21683. normal.normalize();
  21684. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21685. position = position.add(normal);
  21686. position.toArray(positions, index);
  21687. }
  21688. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21689. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21690. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21691. };
  21692. /**
  21693. * Modify the mesh to get a flat shading rendering.
  21694. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21695. * This method returns nothing.
  21696. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21697. */
  21698. Mesh.prototype.convertToFlatShadedMesh = function () {
  21699. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21700. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21701. var kinds = this.getVerticesDataKinds();
  21702. var vbs = [];
  21703. var data = [];
  21704. var newdata = [];
  21705. var updatableNormals = false;
  21706. var kindIndex;
  21707. var kind;
  21708. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21709. kind = kinds[kindIndex];
  21710. var vertexBuffer = this.getVertexBuffer(kind);
  21711. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21712. updatableNormals = vertexBuffer.isUpdatable();
  21713. kinds.splice(kindIndex, 1);
  21714. kindIndex--;
  21715. continue;
  21716. }
  21717. vbs[kind] = vertexBuffer;
  21718. data[kind] = vbs[kind].getData();
  21719. newdata[kind] = [];
  21720. }
  21721. // Save previous submeshes
  21722. var previousSubmeshes = this.subMeshes.slice(0);
  21723. var indices = this.getIndices();
  21724. var totalIndices = this.getTotalIndices();
  21725. // Generating unique vertices per face
  21726. var index;
  21727. for (index = 0; index < totalIndices; index++) {
  21728. var vertexIndex = indices[index];
  21729. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21730. kind = kinds[kindIndex];
  21731. var stride = vbs[kind].getStrideSize();
  21732. for (var offset = 0; offset < stride; offset++) {
  21733. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21734. }
  21735. }
  21736. }
  21737. // Updating faces & normal
  21738. var normals = [];
  21739. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21740. for (index = 0; index < totalIndices; index += 3) {
  21741. indices[index] = index;
  21742. indices[index + 1] = index + 1;
  21743. indices[index + 2] = index + 2;
  21744. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21745. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21746. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21747. var p1p2 = p1.subtract(p2);
  21748. var p3p2 = p3.subtract(p2);
  21749. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21750. // Store same normals for every vertex
  21751. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21752. normals.push(normal.x);
  21753. normals.push(normal.y);
  21754. normals.push(normal.z);
  21755. }
  21756. }
  21757. this.setIndices(indices);
  21758. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21759. // Updating vertex buffers
  21760. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21761. kind = kinds[kindIndex];
  21762. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21763. }
  21764. // Updating submeshes
  21765. this.releaseSubMeshes();
  21766. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21767. var previousOne = previousSubmeshes[submeshIndex];
  21768. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21769. }
  21770. this.synchronizeInstances();
  21771. };
  21772. /**
  21773. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21774. * In other words, more vertices, no more indices and a single bigger VBO.
  21775. * This method returns nothing.
  21776. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21777. *
  21778. */
  21779. Mesh.prototype.convertToUnIndexedMesh = function () {
  21780. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21781. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21782. var kinds = this.getVerticesDataKinds();
  21783. var vbs = [];
  21784. var data = [];
  21785. var newdata = [];
  21786. var updatableNormals = false;
  21787. var kindIndex;
  21788. var kind;
  21789. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21790. kind = kinds[kindIndex];
  21791. var vertexBuffer = this.getVertexBuffer(kind);
  21792. vbs[kind] = vertexBuffer;
  21793. data[kind] = vbs[kind].getData();
  21794. newdata[kind] = [];
  21795. }
  21796. // Save previous submeshes
  21797. var previousSubmeshes = this.subMeshes.slice(0);
  21798. var indices = this.getIndices();
  21799. var totalIndices = this.getTotalIndices();
  21800. // Generating unique vertices per face
  21801. var index;
  21802. for (index = 0; index < totalIndices; index++) {
  21803. var vertexIndex = indices[index];
  21804. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21805. kind = kinds[kindIndex];
  21806. var stride = vbs[kind].getStrideSize();
  21807. for (var offset = 0; offset < stride; offset++) {
  21808. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21809. }
  21810. }
  21811. }
  21812. // Updating indices
  21813. for (index = 0; index < totalIndices; index += 3) {
  21814. indices[index] = index;
  21815. indices[index + 1] = index + 1;
  21816. indices[index + 2] = index + 2;
  21817. }
  21818. this.setIndices(indices);
  21819. // Updating vertex buffers
  21820. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21821. kind = kinds[kindIndex];
  21822. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21823. }
  21824. // Updating submeshes
  21825. this.releaseSubMeshes();
  21826. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21827. var previousOne = previousSubmeshes[submeshIndex];
  21828. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21829. }
  21830. this._unIndexed = true;
  21831. this.synchronizeInstances();
  21832. };
  21833. /**
  21834. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21835. * This method returns nothing.
  21836. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21837. */
  21838. Mesh.prototype.flipFaces = function (flipNormals) {
  21839. if (flipNormals === void 0) { flipNormals = false; }
  21840. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21841. var i;
  21842. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21843. for (i = 0; i < vertex_data.normals.length; i++) {
  21844. vertex_data.normals[i] *= -1;
  21845. }
  21846. }
  21847. var temp;
  21848. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21849. // reassign indices
  21850. temp = vertex_data.indices[i + 1];
  21851. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21852. vertex_data.indices[i + 2] = temp;
  21853. }
  21854. vertex_data.applyToMesh(this);
  21855. };
  21856. // Instances
  21857. /**
  21858. * Creates a new InstancedMesh object from the mesh model.
  21859. * An instance shares the same properties and the same material than its model.
  21860. * Only these properties of each instance can then be set individually :
  21861. * - position
  21862. * - rotation
  21863. * - rotationQuaternion
  21864. * - setPivotMatrix
  21865. * - scaling
  21866. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21867. * Warning : this method is not supported for Line mesh and LineSystem
  21868. */
  21869. Mesh.prototype.createInstance = function (name) {
  21870. return new BABYLON.InstancedMesh(name, this);
  21871. };
  21872. /**
  21873. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21874. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21875. * This method returns nothing.
  21876. */
  21877. Mesh.prototype.synchronizeInstances = function () {
  21878. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21879. var instance = this.instances[instanceIndex];
  21880. instance._syncSubMeshes();
  21881. }
  21882. };
  21883. /**
  21884. * Simplify the mesh according to the given array of settings.
  21885. * Function will return immediately and will simplify async. It returns nothing.
  21886. * @param settings a collection of simplification settings.
  21887. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21888. * @param type the type of simplification to run.
  21889. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21890. */
  21891. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21892. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21893. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21894. this.getScene().simplificationQueue.addTask({
  21895. settings: settings,
  21896. parallelProcessing: parallelProcessing,
  21897. mesh: this,
  21898. simplificationType: simplificationType,
  21899. successCallback: successCallback
  21900. });
  21901. };
  21902. /**
  21903. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21904. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21905. * This should be used together with the simplification to avoid disappearing triangles.
  21906. * @param successCallback an optional success callback to be called after the optimization finished.
  21907. */
  21908. Mesh.prototype.optimizeIndices = function (successCallback) {
  21909. var _this = this;
  21910. var indices = this.getIndices();
  21911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21912. var vectorPositions = [];
  21913. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21914. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21915. }
  21916. var dupes = [];
  21917. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21918. var realPos = vectorPositions.length - 1 - iteration;
  21919. var testedPosition = vectorPositions[realPos];
  21920. for (var j = 0; j < realPos; ++j) {
  21921. var againstPosition = vectorPositions[j];
  21922. if (testedPosition.equals(againstPosition)) {
  21923. dupes[realPos] = j;
  21924. break;
  21925. }
  21926. }
  21927. }, function () {
  21928. for (var i = 0; i < indices.length; ++i) {
  21929. indices[i] = dupes[indices[i]] || indices[i];
  21930. }
  21931. //indices are now reordered
  21932. var originalSubMeshes = _this.subMeshes.slice(0);
  21933. _this.setIndices(indices);
  21934. _this.subMeshes = originalSubMeshes;
  21935. if (successCallback) {
  21936. successCallback(_this);
  21937. }
  21938. });
  21939. };
  21940. // Statics
  21941. /**
  21942. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21943. * The parameter `parsedMesh` is the mesh to be copied.
  21944. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21945. */
  21946. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21947. var mesh = new Mesh(parsedMesh.name, scene);
  21948. mesh.id = parsedMesh.id;
  21949. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21950. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21951. if (parsedMesh.metadata !== undefined) {
  21952. mesh.metadata = parsedMesh.metadata;
  21953. }
  21954. if (parsedMesh.rotationQuaternion) {
  21955. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21956. }
  21957. else if (parsedMesh.rotation) {
  21958. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21959. }
  21960. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21961. if (parsedMesh.localMatrix) {
  21962. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21963. }
  21964. else if (parsedMesh.pivotMatrix) {
  21965. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21966. }
  21967. mesh.setEnabled(parsedMesh.isEnabled);
  21968. mesh.isVisible = parsedMesh.isVisible;
  21969. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21970. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21971. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21972. if (parsedMesh.applyFog !== undefined) {
  21973. mesh.applyFog = parsedMesh.applyFog;
  21974. }
  21975. if (parsedMesh.pickable !== undefined) {
  21976. mesh.isPickable = parsedMesh.pickable;
  21977. }
  21978. if (parsedMesh.alphaIndex !== undefined) {
  21979. mesh.alphaIndex = parsedMesh.alphaIndex;
  21980. }
  21981. mesh.receiveShadows = parsedMesh.receiveShadows;
  21982. mesh.billboardMode = parsedMesh.billboardMode;
  21983. if (parsedMesh.visibility !== undefined) {
  21984. mesh.visibility = parsedMesh.visibility;
  21985. }
  21986. mesh.checkCollisions = parsedMesh.checkCollisions;
  21987. if (parsedMesh.isBlocker !== undefined) {
  21988. mesh.isBlocker = parsedMesh.isBlocker;
  21989. }
  21990. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21991. // freezeWorldMatrix
  21992. if (parsedMesh.freezeWorldMatrix) {
  21993. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21994. }
  21995. // Parent
  21996. if (parsedMesh.parentId) {
  21997. mesh._waitingParentId = parsedMesh.parentId;
  21998. }
  21999. // Actions
  22000. if (parsedMesh.actions !== undefined) {
  22001. mesh._waitingActions = parsedMesh.actions;
  22002. }
  22003. // Overlay
  22004. if (parsedMesh.overlayAlpha !== undefined) {
  22005. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22006. }
  22007. if (parsedMesh.overlayColor !== undefined) {
  22008. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22009. }
  22010. if (parsedMesh.renderOverlay !== undefined) {
  22011. mesh.renderOverlay = parsedMesh.renderOverlay;
  22012. }
  22013. // Geometry
  22014. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22015. if (parsedMesh.delayLoadingFile) {
  22016. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22017. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22018. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22019. if (parsedMesh._binaryInfo) {
  22020. mesh._binaryInfo = parsedMesh._binaryInfo;
  22021. }
  22022. mesh._delayInfo = [];
  22023. if (parsedMesh.hasUVs) {
  22024. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22025. }
  22026. if (parsedMesh.hasUVs2) {
  22027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22028. }
  22029. if (parsedMesh.hasUVs3) {
  22030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22031. }
  22032. if (parsedMesh.hasUVs4) {
  22033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22034. }
  22035. if (parsedMesh.hasUVs5) {
  22036. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22037. }
  22038. if (parsedMesh.hasUVs6) {
  22039. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22040. }
  22041. if (parsedMesh.hasColors) {
  22042. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22043. }
  22044. if (parsedMesh.hasMatricesIndices) {
  22045. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22046. }
  22047. if (parsedMesh.hasMatricesWeights) {
  22048. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22049. }
  22050. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22051. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22052. mesh._checkDelayState();
  22053. }
  22054. }
  22055. else {
  22056. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22057. }
  22058. // Material
  22059. if (parsedMesh.materialId) {
  22060. mesh.setMaterialByID(parsedMesh.materialId);
  22061. }
  22062. else {
  22063. mesh.material = null;
  22064. }
  22065. // Skeleton
  22066. if (parsedMesh.skeletonId > -1) {
  22067. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22068. if (parsedMesh.numBoneInfluencers) {
  22069. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22070. }
  22071. }
  22072. // Animations
  22073. if (parsedMesh.animations) {
  22074. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22075. var parsedAnimation = parsedMesh.animations[animationIndex];
  22076. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22077. }
  22078. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22079. }
  22080. if (parsedMesh.autoAnimate) {
  22081. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22082. }
  22083. // Layer Mask
  22084. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22085. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22086. }
  22087. else {
  22088. mesh.layerMask = 0x0FFFFFFF;
  22089. }
  22090. //(Deprecated) physics
  22091. if (parsedMesh.physicsImpostor) {
  22092. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22093. mass: parsedMesh.physicsMass,
  22094. friction: parsedMesh.physicsFriction,
  22095. restitution: parsedMesh.physicsRestitution
  22096. }, scene);
  22097. }
  22098. // Instances
  22099. if (parsedMesh.instances) {
  22100. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22101. var parsedInstance = parsedMesh.instances[index];
  22102. var instance = mesh.createInstance(parsedInstance.name);
  22103. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22104. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22105. if (parsedInstance.parentId) {
  22106. instance._waitingParentId = parsedInstance.parentId;
  22107. }
  22108. if (parsedInstance.rotationQuaternion) {
  22109. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22110. }
  22111. else if (parsedInstance.rotation) {
  22112. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22113. }
  22114. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22115. instance.checkCollisions = mesh.checkCollisions;
  22116. if (parsedMesh.animations) {
  22117. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22118. parsedAnimation = parsedMesh.animations[animationIndex];
  22119. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22120. }
  22121. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22122. }
  22123. }
  22124. }
  22125. return mesh;
  22126. };
  22127. /**
  22128. * Creates a ribbon mesh.
  22129. * Please consider using the same method from the MeshBuilder class instead.
  22130. * 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.
  22131. *
  22132. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22133. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22134. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22135. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22136. * 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.
  22137. * 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.
  22138. * 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
  22139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22140. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22142. */
  22143. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22144. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22145. pathArray: pathArray,
  22146. closeArray: closeArray,
  22147. closePath: closePath,
  22148. offset: offset,
  22149. updatable: updatable,
  22150. sideOrientation: sideOrientation,
  22151. instance: instance
  22152. }, scene);
  22153. };
  22154. /**
  22155. * Creates a plane polygonal mesh. By default, this is a disc.
  22156. * Please consider using the same method from the MeshBuilder class instead.
  22157. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22158. * 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.
  22159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22162. */
  22163. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22164. var options = {
  22165. radius: radius,
  22166. tessellation: tessellation,
  22167. sideOrientation: sideOrientation,
  22168. updatable: updatable
  22169. };
  22170. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22171. };
  22172. /**
  22173. * Creates a box mesh.
  22174. * Please consider using the same method from the MeshBuilder class instead.
  22175. * The parameter `size` sets the size (float) of each box side (default 1).
  22176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22179. */
  22180. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22181. var options = {
  22182. size: size,
  22183. sideOrientation: sideOrientation,
  22184. updatable: updatable
  22185. };
  22186. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22187. };
  22188. /**
  22189. * Creates a sphere mesh.
  22190. * Please consider using the same method from the MeshBuilder class instead.
  22191. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22192. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22196. */
  22197. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22198. var options = {
  22199. segments: segments,
  22200. diameterX: diameter,
  22201. diameterY: diameter,
  22202. diameterZ: diameter,
  22203. sideOrientation: sideOrientation,
  22204. updatable: updatable
  22205. };
  22206. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22207. };
  22208. /**
  22209. * Creates a cylinder or a cone mesh.
  22210. * Please consider using the same method from the MeshBuilder class instead.
  22211. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22212. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22213. * 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.
  22214. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22215. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22219. */
  22220. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22221. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22222. if (scene !== undefined) {
  22223. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22224. updatable = scene;
  22225. }
  22226. scene = subdivisions;
  22227. subdivisions = 1;
  22228. }
  22229. var options = {
  22230. height: height,
  22231. diameterTop: diameterTop,
  22232. diameterBottom: diameterBottom,
  22233. tessellation: tessellation,
  22234. subdivisions: subdivisions,
  22235. sideOrientation: sideOrientation,
  22236. updatable: updatable
  22237. };
  22238. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22239. };
  22240. // Torus (Code from SharpDX.org)
  22241. /**
  22242. * Creates a torus mesh.
  22243. * Please consider using the same method from the MeshBuilder class instead.
  22244. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22245. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22246. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22250. */
  22251. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22252. var options = {
  22253. diameter: diameter,
  22254. thickness: thickness,
  22255. tessellation: tessellation,
  22256. sideOrientation: sideOrientation,
  22257. updatable: updatable
  22258. };
  22259. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22260. };
  22261. /**
  22262. * Creates a torus knot mesh.
  22263. * Please consider using the same method from the MeshBuilder class instead.
  22264. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22265. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22266. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22267. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22268. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22271. */
  22272. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22273. var options = {
  22274. radius: radius,
  22275. tube: tube,
  22276. radialSegments: radialSegments,
  22277. tubularSegments: tubularSegments,
  22278. p: p,
  22279. q: q,
  22280. sideOrientation: sideOrientation,
  22281. updatable: updatable
  22282. };
  22283. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22284. };
  22285. /**
  22286. * Creates a line mesh.
  22287. * Please consider using the same method from the MeshBuilder class instead.
  22288. * 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.
  22289. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22290. * The parameter `points` is an array successive Vector3.
  22291. * 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
  22292. * When updating an instance, remember that only point positions can change, not the number of points.
  22293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22294. */
  22295. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22296. var options = {
  22297. points: points,
  22298. updatable: updatable,
  22299. instance: instance
  22300. };
  22301. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22302. };
  22303. /**
  22304. * Creates a dashed line mesh.
  22305. * Please consider using the same method from the MeshBuilder class instead.
  22306. * 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.
  22307. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22308. * The parameter `points` is an array successive Vector3.
  22309. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22310. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22311. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22312. * 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
  22313. * When updating an instance, remember that only point positions can change, not the number of points.
  22314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22315. */
  22316. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22317. var options = {
  22318. points: points,
  22319. dashSize: dashSize,
  22320. gapSize: gapSize,
  22321. dashNb: dashNb,
  22322. updatable: updatable,
  22323. instance: instance
  22324. };
  22325. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22326. };
  22327. /**
  22328. * Creates an extruded shape mesh.
  22329. * 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.
  22330. * Please consider using the same method from the MeshBuilder class instead.
  22331. *
  22332. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22333. * 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
  22334. * extruded along the Z axis.
  22335. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22336. * 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.
  22337. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22338. * 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
  22339. * 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
  22340. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22344. */
  22345. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22346. var options = {
  22347. shape: shape,
  22348. path: path,
  22349. scale: scale,
  22350. rotation: rotation,
  22351. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22352. sideOrientation: sideOrientation,
  22353. instance: instance,
  22354. updatable: updatable
  22355. };
  22356. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22357. };
  22358. /**
  22359. * Creates an custom extruded shape mesh.
  22360. * 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.
  22361. * Please consider using the same method from the MeshBuilder class instead.
  22362. *
  22363. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22364. * 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
  22365. * extruded along the Z axis.
  22366. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22367. * 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
  22368. * and the distance of this point from the begining of the path :
  22369. * ```javascript
  22370. * var rotationFunction = function(i, distance) {
  22371. * // do things
  22372. * return rotationValue; }
  22373. * ```
  22374. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22375. * 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
  22376. * and the distance of this point from the begining of the path :
  22377. * ```javascript
  22378. * var scaleFunction = function(i, distance) {
  22379. * // do things
  22380. * return scaleValue;}
  22381. * ```
  22382. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22383. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22384. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22385. * 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
  22386. * 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
  22387. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22391. */
  22392. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22393. var options = {
  22394. shape: shape,
  22395. path: path,
  22396. scaleFunction: scaleFunction,
  22397. rotationFunction: rotationFunction,
  22398. ribbonCloseArray: ribbonCloseArray,
  22399. ribbonClosePath: ribbonClosePath,
  22400. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22401. sideOrientation: sideOrientation,
  22402. instance: instance,
  22403. updatable: updatable
  22404. };
  22405. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22406. };
  22407. /**
  22408. * Creates lathe mesh.
  22409. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22410. * Please consider using the same method from the MeshBuilder class instead.
  22411. * 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
  22412. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22413. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22414. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22418. */
  22419. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22420. var options = {
  22421. shape: shape,
  22422. radius: radius,
  22423. tessellation: tessellation,
  22424. sideOrientation: sideOrientation,
  22425. updatable: updatable
  22426. };
  22427. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22428. };
  22429. /**
  22430. * Creates a plane mesh.
  22431. * Please consider using the same method from the MeshBuilder class instead.
  22432. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22436. */
  22437. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22438. var options = {
  22439. size: size,
  22440. width: size,
  22441. height: size,
  22442. sideOrientation: sideOrientation,
  22443. updatable: updatable
  22444. };
  22445. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22446. };
  22447. /**
  22448. * Creates a ground mesh.
  22449. * Please consider using the same method from the MeshBuilder class instead.
  22450. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22451. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22453. */
  22454. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22455. var options = {
  22456. width: width,
  22457. height: height,
  22458. subdivisions: subdivisions,
  22459. updatable: updatable
  22460. };
  22461. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22462. };
  22463. /**
  22464. * Creates a tiled ground mesh.
  22465. * Please consider using the same method from the MeshBuilder class instead.
  22466. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22467. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22468. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22469. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22470. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22471. * numbers of subdivisions on the ground width and height of each tile.
  22472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22473. */
  22474. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22475. var options = {
  22476. xmin: xmin,
  22477. zmin: zmin,
  22478. xmax: xmax,
  22479. zmax: zmax,
  22480. subdivisions: subdivisions,
  22481. precision: precision,
  22482. updatable: updatable
  22483. };
  22484. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22485. };
  22486. /**
  22487. * Creates a ground mesh from a height map.
  22488. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22489. * Please consider using the same method from the MeshBuilder class instead.
  22490. * The parameter `url` sets the URL of the height map image resource.
  22491. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22492. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22493. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22494. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22495. * 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).
  22496. * This function is passed the newly built mesh :
  22497. * ```javascript
  22498. * function(mesh) { // do things
  22499. * return; }
  22500. * ```
  22501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22502. */
  22503. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22504. var options = {
  22505. width: width,
  22506. height: height,
  22507. subdivisions: subdivisions,
  22508. minHeight: minHeight,
  22509. maxHeight: maxHeight,
  22510. updatable: updatable,
  22511. onReady: onReady
  22512. };
  22513. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22514. };
  22515. /**
  22516. * Creates a tube mesh.
  22517. * 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.
  22518. * Please consider using the same method from the MeshBuilder class instead.
  22519. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22520. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22521. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22522. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22523. * 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.
  22524. * It must return a radius value (positive float) :
  22525. * ```javascript
  22526. * var radiusFunction = function(i, distance) {
  22527. * // do things
  22528. * return radius; }
  22529. * ```
  22530. * 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
  22531. * 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
  22532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22535. */
  22536. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22537. var options = {
  22538. path: path,
  22539. radius: radius,
  22540. tessellation: tessellation,
  22541. radiusFunction: radiusFunction,
  22542. arc: 1,
  22543. cap: cap,
  22544. updatable: updatable,
  22545. sideOrientation: sideOrientation,
  22546. instance: instance
  22547. };
  22548. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22549. };
  22550. /**
  22551. * Creates a polyhedron mesh.
  22552. * Please consider using the same method from the MeshBuilder class instead.
  22553. * 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
  22554. * to choose the wanted type.
  22555. * The parameter `size` (positive float, default 1) sets the polygon size.
  22556. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22557. * 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`.
  22558. * 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
  22559. * 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)`).
  22560. * 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
  22561. * 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.
  22562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22565. */
  22566. Mesh.CreatePolyhedron = function (name, options, scene) {
  22567. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22568. };
  22569. /**
  22570. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22571. * Please consider using the same method from the MeshBuilder class instead.
  22572. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22573. * 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`).
  22574. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22575. * 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.
  22576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22579. */
  22580. Mesh.CreateIcoSphere = function (name, options, scene) {
  22581. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22582. };
  22583. /**
  22584. * Creates a decal mesh.
  22585. * Please consider using the same method from the MeshBuilder class instead.
  22586. * 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.
  22587. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22588. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22589. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22590. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22591. */
  22592. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22593. var options = {
  22594. position: position,
  22595. normal: normal,
  22596. size: size,
  22597. angle: angle
  22598. };
  22599. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22600. };
  22601. // Skeletons
  22602. /**
  22603. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22604. */
  22605. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22606. var source;
  22607. if (!this._sourcePositions) {
  22608. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22609. this._sourcePositions = new Float32Array(source);
  22610. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22611. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22612. }
  22613. }
  22614. return this._sourcePositions;
  22615. };
  22616. /**
  22617. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22618. */
  22619. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22620. var source;
  22621. if (!this._sourceNormals) {
  22622. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22623. this._sourceNormals = new Float32Array(source);
  22624. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22625. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22626. }
  22627. }
  22628. return this._sourceNormals;
  22629. };
  22630. /**
  22631. * Update the vertex buffers by applying transformation from the bones
  22632. * @param {skeleton} skeleton to apply
  22633. */
  22634. Mesh.prototype.applySkeleton = function (skeleton) {
  22635. if (!this.geometry) {
  22636. return;
  22637. }
  22638. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22639. return;
  22640. }
  22641. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22643. return this;
  22644. }
  22645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22646. return this;
  22647. }
  22648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22649. return this;
  22650. }
  22651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22652. return this;
  22653. }
  22654. if (!this._sourcePositions) {
  22655. var submeshes = this.subMeshes.slice();
  22656. this.setPositionsForCPUSkinning();
  22657. this.subMeshes = submeshes;
  22658. }
  22659. if (!this._sourceNormals) {
  22660. this.setNormalsForCPUSkinning();
  22661. }
  22662. // positionsData checks for not being Float32Array will only pass at most once
  22663. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22664. if (!(positionsData instanceof Float32Array)) {
  22665. positionsData = new Float32Array(positionsData);
  22666. }
  22667. // normalsData checks for not being Float32Array will only pass at most once
  22668. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22669. if (!(normalsData instanceof Float32Array)) {
  22670. normalsData = new Float32Array(normalsData);
  22671. }
  22672. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22673. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22674. var needExtras = this.numBoneInfluencers > 4;
  22675. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22676. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22677. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22678. var tempVector3 = BABYLON.Vector3.Zero();
  22679. var finalMatrix = new BABYLON.Matrix();
  22680. var tempMatrix = new BABYLON.Matrix();
  22681. var matWeightIdx = 0;
  22682. var inf;
  22683. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22684. var weight;
  22685. for (inf = 0; inf < 4; inf++) {
  22686. weight = matricesWeightsData[matWeightIdx + inf];
  22687. if (weight > 0) {
  22688. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22689. finalMatrix.addToSelf(tempMatrix);
  22690. }
  22691. else
  22692. break;
  22693. }
  22694. if (needExtras) {
  22695. for (inf = 0; inf < 4; inf++) {
  22696. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22697. if (weight > 0) {
  22698. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22699. finalMatrix.addToSelf(tempMatrix);
  22700. }
  22701. else
  22702. break;
  22703. }
  22704. }
  22705. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22706. tempVector3.toArray(positionsData, index);
  22707. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22708. tempVector3.toArray(normalsData, index);
  22709. finalMatrix.reset();
  22710. }
  22711. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22712. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22713. return this;
  22714. };
  22715. // Tools
  22716. /**
  22717. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22718. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22719. */
  22720. Mesh.MinMax = function (meshes) {
  22721. var minVector = null;
  22722. var maxVector = null;
  22723. meshes.forEach(function (mesh, index, array) {
  22724. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22725. if (!minVector) {
  22726. minVector = boundingBox.minimumWorld;
  22727. maxVector = boundingBox.maximumWorld;
  22728. }
  22729. else {
  22730. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22731. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22732. }
  22733. });
  22734. return {
  22735. min: minVector,
  22736. max: maxVector
  22737. };
  22738. };
  22739. /**
  22740. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22741. */
  22742. Mesh.Center = function (meshesOrMinMaxVector) {
  22743. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22744. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22745. };
  22746. /**
  22747. * Merge the array of meshes into a single mesh for performance reasons.
  22748. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22749. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22750. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22751. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22752. */
  22753. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22754. if (disposeSource === void 0) { disposeSource = true; }
  22755. var index;
  22756. if (!allow32BitsIndices) {
  22757. var totalVertices = 0;
  22758. // Counting vertices
  22759. for (index = 0; index < meshes.length; index++) {
  22760. if (meshes[index]) {
  22761. totalVertices += meshes[index].getTotalVertices();
  22762. if (totalVertices > 65536) {
  22763. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22764. return null;
  22765. }
  22766. }
  22767. }
  22768. }
  22769. // Merge
  22770. var vertexData;
  22771. var otherVertexData;
  22772. var source;
  22773. for (index = 0; index < meshes.length; index++) {
  22774. if (meshes[index]) {
  22775. meshes[index].computeWorldMatrix(true);
  22776. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22777. otherVertexData.transform(meshes[index].getWorldMatrix());
  22778. if (vertexData) {
  22779. vertexData.merge(otherVertexData);
  22780. }
  22781. else {
  22782. vertexData = otherVertexData;
  22783. source = meshes[index];
  22784. }
  22785. }
  22786. }
  22787. if (!meshSubclass) {
  22788. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22789. }
  22790. vertexData.applyToMesh(meshSubclass);
  22791. // Setting properties
  22792. meshSubclass.material = source.material;
  22793. meshSubclass.checkCollisions = source.checkCollisions;
  22794. // Cleaning
  22795. if (disposeSource) {
  22796. for (index = 0; index < meshes.length; index++) {
  22797. if (meshes[index]) {
  22798. meshes[index].dispose();
  22799. }
  22800. }
  22801. }
  22802. return meshSubclass;
  22803. };
  22804. return Mesh;
  22805. }(BABYLON.AbstractMesh));
  22806. // Consts
  22807. Mesh._FRONTSIDE = 0;
  22808. Mesh._BACKSIDE = 1;
  22809. Mesh._DOUBLESIDE = 2;
  22810. Mesh._DEFAULTSIDE = 0;
  22811. Mesh._NO_CAP = 0;
  22812. Mesh._CAP_START = 1;
  22813. Mesh._CAP_END = 2;
  22814. Mesh._CAP_ALL = 3;
  22815. BABYLON.Mesh = Mesh;
  22816. })(BABYLON || (BABYLON = {}));
  22817. //# sourceMappingURL=babylon.mesh.js.map
  22818. var BABYLON;
  22819. (function (BABYLON) {
  22820. var SubMesh = (function () {
  22821. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22822. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22823. this.materialIndex = materialIndex;
  22824. this.verticesStart = verticesStart;
  22825. this.verticesCount = verticesCount;
  22826. this.indexStart = indexStart;
  22827. this.indexCount = indexCount;
  22828. this._renderId = 0;
  22829. this._mesh = mesh;
  22830. this._renderingMesh = renderingMesh || mesh;
  22831. mesh.subMeshes.push(this);
  22832. this._trianglePlanes = [];
  22833. this._id = mesh.subMeshes.length - 1;
  22834. if (createBoundingBox) {
  22835. this.refreshBoundingInfo();
  22836. mesh.computeWorldMatrix(true);
  22837. }
  22838. }
  22839. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22840. get: function () {
  22841. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22842. },
  22843. enumerable: true,
  22844. configurable: true
  22845. });
  22846. SubMesh.prototype.getBoundingInfo = function () {
  22847. if (this.IsGlobal) {
  22848. return this._mesh.getBoundingInfo();
  22849. }
  22850. return this._boundingInfo;
  22851. };
  22852. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22853. this._boundingInfo = boundingInfo;
  22854. };
  22855. SubMesh.prototype.getMesh = function () {
  22856. return this._mesh;
  22857. };
  22858. SubMesh.prototype.getRenderingMesh = function () {
  22859. return this._renderingMesh;
  22860. };
  22861. SubMesh.prototype.getMaterial = function () {
  22862. var rootMaterial = this._renderingMesh.material;
  22863. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22864. var multiMaterial = rootMaterial;
  22865. return multiMaterial.getSubMaterial(this.materialIndex);
  22866. }
  22867. if (!rootMaterial) {
  22868. return this._mesh.getScene().defaultMaterial;
  22869. }
  22870. return rootMaterial;
  22871. };
  22872. // Methods
  22873. SubMesh.prototype.refreshBoundingInfo = function () {
  22874. this._lastColliderWorldVertices = null;
  22875. if (this.IsGlobal) {
  22876. return;
  22877. }
  22878. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22879. if (!data) {
  22880. this._boundingInfo = this._mesh._boundingInfo;
  22881. return;
  22882. }
  22883. var indices = this._renderingMesh.getIndices();
  22884. var extend;
  22885. //is this the only submesh?
  22886. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22887. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22888. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22889. }
  22890. else {
  22891. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22892. }
  22893. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22894. };
  22895. SubMesh.prototype._checkCollision = function (collider) {
  22896. return this.getBoundingInfo()._checkCollision(collider);
  22897. };
  22898. SubMesh.prototype.updateBoundingInfo = function (world) {
  22899. if (!this.getBoundingInfo()) {
  22900. this.refreshBoundingInfo();
  22901. }
  22902. this.getBoundingInfo().update(world);
  22903. };
  22904. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22905. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22906. };
  22907. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22908. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22909. };
  22910. SubMesh.prototype.render = function (enableAlphaMode) {
  22911. this._renderingMesh.render(this, enableAlphaMode);
  22912. };
  22913. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22914. if (!this._linesIndexBuffer) {
  22915. var linesIndices = [];
  22916. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22917. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22918. }
  22919. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22920. this.linesIndexCount = linesIndices.length;
  22921. }
  22922. return this._linesIndexBuffer;
  22923. };
  22924. SubMesh.prototype.canIntersects = function (ray) {
  22925. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22926. };
  22927. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22928. var intersectInfo = null;
  22929. // LineMesh first as it's also a Mesh...
  22930. if (this._mesh instanceof BABYLON.LinesMesh) {
  22931. var lineMesh = this._mesh;
  22932. // Line test
  22933. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22934. var p0 = positions[indices[index]];
  22935. var p1 = positions[indices[index + 1]];
  22936. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22937. if (length < 0) {
  22938. continue;
  22939. }
  22940. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22941. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22942. if (fastCheck) {
  22943. break;
  22944. }
  22945. }
  22946. }
  22947. }
  22948. else {
  22949. // Triangles test
  22950. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22951. var p0 = positions[indices[index]];
  22952. var p1 = positions[indices[index + 1]];
  22953. var p2 = positions[indices[index + 2]];
  22954. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22955. if (currentIntersectInfo) {
  22956. if (currentIntersectInfo.distance < 0) {
  22957. continue;
  22958. }
  22959. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22960. intersectInfo = currentIntersectInfo;
  22961. intersectInfo.faceId = index / 3;
  22962. if (fastCheck) {
  22963. break;
  22964. }
  22965. }
  22966. }
  22967. }
  22968. }
  22969. return intersectInfo;
  22970. };
  22971. // Clone
  22972. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22973. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22974. if (!this.IsGlobal) {
  22975. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22976. }
  22977. return result;
  22978. };
  22979. // Dispose
  22980. SubMesh.prototype.dispose = function () {
  22981. if (this._linesIndexBuffer) {
  22982. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22983. this._linesIndexBuffer = null;
  22984. }
  22985. // Remove from mesh
  22986. var index = this._mesh.subMeshes.indexOf(this);
  22987. this._mesh.subMeshes.splice(index, 1);
  22988. };
  22989. // Statics
  22990. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22991. var minVertexIndex = Number.MAX_VALUE;
  22992. var maxVertexIndex = -Number.MAX_VALUE;
  22993. renderingMesh = renderingMesh || mesh;
  22994. var indices = renderingMesh.getIndices();
  22995. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22996. var vertexIndex = indices[index];
  22997. if (vertexIndex < minVertexIndex)
  22998. minVertexIndex = vertexIndex;
  22999. if (vertexIndex > maxVertexIndex)
  23000. maxVertexIndex = vertexIndex;
  23001. }
  23002. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23003. };
  23004. return SubMesh;
  23005. }());
  23006. BABYLON.SubMesh = SubMesh;
  23007. })(BABYLON || (BABYLON = {}));
  23008. //# sourceMappingURL=babylon.subMesh.js.map
  23009. var BABYLON;
  23010. (function (BABYLON) {
  23011. var MeshBuilder = (function () {
  23012. function MeshBuilder() {
  23013. }
  23014. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  23015. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  23016. return BABYLON.Mesh.DOUBLESIDE;
  23017. }
  23018. if (orientation === undefined || orientation === null) {
  23019. return BABYLON.Mesh.FRONTSIDE;
  23020. }
  23021. return orientation;
  23022. };
  23023. /**
  23024. * Creates a box mesh.
  23025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  23026. * The parameter `size` sets the size (float) of each box side (default 1).
  23027. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  23028. * 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).
  23029. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  23030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23033. */
  23034. MeshBuilder.CreateBox = function (name, options, scene) {
  23035. var box = new BABYLON.Mesh(name, scene);
  23036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23037. box.sideOrientation = options.sideOrientation;
  23038. var vertexData = BABYLON.VertexData.CreateBox(options);
  23039. vertexData.applyToMesh(box, options.updatable);
  23040. return box;
  23041. };
  23042. /**
  23043. * Creates a sphere mesh.
  23044. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  23045. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23046. * 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`).
  23047. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23048. * 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
  23049. * 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).
  23050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23053. */
  23054. MeshBuilder.CreateSphere = function (name, options, scene) {
  23055. var sphere = new BABYLON.Mesh(name, scene);
  23056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23057. sphere.sideOrientation = options.sideOrientation;
  23058. var vertexData = BABYLON.VertexData.CreateSphere(options);
  23059. vertexData.applyToMesh(sphere, options.updatable);
  23060. return sphere;
  23061. };
  23062. /**
  23063. * Creates a plane polygonal mesh. By default, this is a disc.
  23064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  23065. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23066. * 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.
  23067. * 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
  23068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23071. */
  23072. MeshBuilder.CreateDisc = function (name, options, scene) {
  23073. var disc = new BABYLON.Mesh(name, scene);
  23074. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23075. disc.sideOrientation = options.sideOrientation;
  23076. var vertexData = BABYLON.VertexData.CreateDisc(options);
  23077. vertexData.applyToMesh(disc, options.updatable);
  23078. return disc;
  23079. };
  23080. /**
  23081. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23082. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  23083. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23084. * 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`).
  23085. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23086. * 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.
  23087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23090. */
  23091. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  23092. var sphere = new BABYLON.Mesh(name, scene);
  23093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23094. sphere.sideOrientation = options.sideOrientation;
  23095. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  23096. vertexData.applyToMesh(sphere, options.updatable);
  23097. return sphere;
  23098. };
  23099. ;
  23100. /**
  23101. * Creates a ribbon mesh.
  23102. * 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.
  23103. *
  23104. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23105. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23106. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23107. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23108. * 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.
  23109. * 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.
  23110. * 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
  23111. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23113. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23115. */
  23116. MeshBuilder.CreateRibbon = function (name, options, scene) {
  23117. var pathArray = options.pathArray;
  23118. var closeArray = options.closeArray;
  23119. var closePath = options.closePath;
  23120. var offset = options.offset;
  23121. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23122. var instance = options.instance;
  23123. var updatable = options.updatable;
  23124. if (instance) {
  23125. // positionFunction : ribbon case
  23126. // only pathArray and sideOrientation parameters are taken into account for positions update
  23127. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  23128. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  23129. var positionFunction = function (positions) {
  23130. var minlg = pathArray[0].length;
  23131. var i = 0;
  23132. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  23133. for (var si = 1; si <= ns; si++) {
  23134. for (var p = 0; p < pathArray.length; p++) {
  23135. var path = pathArray[p];
  23136. var l = path.length;
  23137. minlg = (minlg < l) ? minlg : l;
  23138. var j = 0;
  23139. while (j < minlg) {
  23140. positions[i] = path[j].x;
  23141. positions[i + 1] = path[j].y;
  23142. positions[i + 2] = path[j].z;
  23143. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  23144. BABYLON.Tmp.Vector3[0].x = path[j].x;
  23145. }
  23146. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  23147. BABYLON.Tmp.Vector3[1].x = path[j].x;
  23148. }
  23149. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  23150. BABYLON.Tmp.Vector3[0].y = path[j].y;
  23151. }
  23152. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  23153. BABYLON.Tmp.Vector3[1].y = path[j].y;
  23154. }
  23155. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  23156. BABYLON.Tmp.Vector3[0].z = path[j].z;
  23157. }
  23158. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  23159. BABYLON.Tmp.Vector3[1].z = path[j].z;
  23160. }
  23161. j++;
  23162. i += 3;
  23163. }
  23164. if (instance._closePath) {
  23165. positions[i] = path[0].x;
  23166. positions[i + 1] = path[0].y;
  23167. positions[i + 2] = path[0].z;
  23168. i += 3;
  23169. }
  23170. }
  23171. }
  23172. };
  23173. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23174. positionFunction(positions);
  23175. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  23176. instance._boundingInfo.update(instance._worldMatrix);
  23177. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23178. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  23179. var indices = instance.getIndices();
  23180. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23181. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  23182. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  23183. if (instance._closePath) {
  23184. var indexFirst = 0;
  23185. var indexLast = 0;
  23186. for (var p = 0; p < pathArray.length; p++) {
  23187. indexFirst = instance._idx[p] * 3;
  23188. if (p + 1 < pathArray.length) {
  23189. indexLast = (instance._idx[p + 1] - 1) * 3;
  23190. }
  23191. else {
  23192. indexLast = normals.length - 3;
  23193. }
  23194. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23195. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23196. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23197. normals[indexLast] = normals[indexFirst];
  23198. normals[indexLast + 1] = normals[indexFirst + 1];
  23199. normals[indexLast + 2] = normals[indexFirst + 2];
  23200. }
  23201. }
  23202. if (!(instance.areNormalsFrozen)) {
  23203. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23204. }
  23205. }
  23206. return instance;
  23207. }
  23208. else {
  23209. var ribbon = new BABYLON.Mesh(name, scene);
  23210. ribbon.sideOrientation = sideOrientation;
  23211. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  23212. if (closePath) {
  23213. ribbon._idx = vertexData._idx;
  23214. }
  23215. ribbon._closePath = closePath;
  23216. ribbon._closeArray = closeArray;
  23217. vertexData.applyToMesh(ribbon, updatable);
  23218. return ribbon;
  23219. }
  23220. };
  23221. /**
  23222. * Creates a cylinder or a cone mesh.
  23223. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  23224. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23225. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23226. * 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.
  23227. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23228. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23229. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  23230. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  23231. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  23232. * 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).
  23233. * 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
  23234. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  23235. * 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
  23236. * 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.
  23237. * If `enclose` is false, a ring surface is one element.
  23238. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  23239. * 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
  23240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23241. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23243. */
  23244. MeshBuilder.CreateCylinder = function (name, options, scene) {
  23245. var cylinder = new BABYLON.Mesh(name, scene);
  23246. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23247. cylinder.sideOrientation = options.sideOrientation;
  23248. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  23249. vertexData.applyToMesh(cylinder, options.updatable);
  23250. return cylinder;
  23251. };
  23252. /**
  23253. * Creates a torus mesh.
  23254. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  23255. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23256. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23257. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23258. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23259. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23261. */
  23262. MeshBuilder.CreateTorus = function (name, options, scene) {
  23263. var torus = new BABYLON.Mesh(name, scene);
  23264. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23265. torus.sideOrientation = options.sideOrientation;
  23266. var vertexData = BABYLON.VertexData.CreateTorus(options);
  23267. vertexData.applyToMesh(torus, options.updatable);
  23268. return torus;
  23269. };
  23270. /**
  23271. * Creates a torus knot mesh.
  23272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  23273. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23274. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23275. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23276. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23277. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23278. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23280. */
  23281. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  23282. var torusKnot = new BABYLON.Mesh(name, scene);
  23283. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23284. torusKnot.sideOrientation = options.sideOrientation;
  23285. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  23286. vertexData.applyToMesh(torusKnot, options.updatable);
  23287. return torusKnot;
  23288. };
  23289. /**
  23290. * Creates a line system mesh.
  23291. * A line system is a pool of many lines gathered in a single mesh.
  23292. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  23293. * 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.
  23294. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  23295. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  23296. * 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
  23297. * 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
  23298. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  23299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23300. */
  23301. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  23302. var instance = options.instance;
  23303. var lines = options.lines;
  23304. if (instance) {
  23305. var positionFunction = function (positions) {
  23306. var i = 0;
  23307. for (var l = 0; l < lines.length; l++) {
  23308. var points = lines[l];
  23309. for (var p = 0; p < points.length; p++) {
  23310. positions[i] = points[p].x;
  23311. positions[i + 1] = points[p].y;
  23312. positions[i + 2] = points[p].z;
  23313. i += 3;
  23314. }
  23315. }
  23316. };
  23317. instance.updateMeshPositions(positionFunction, false);
  23318. return instance;
  23319. }
  23320. // line system creation
  23321. var lineSystem = new BABYLON.LinesMesh(name, scene);
  23322. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  23323. vertexData.applyToMesh(lineSystem, options.updatable);
  23324. return lineSystem;
  23325. };
  23326. /**
  23327. * Creates a line mesh.
  23328. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  23329. * 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.
  23330. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23331. * The parameter `points` is an array successive Vector3.
  23332. * 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
  23333. * When updating an instance, remember that only point positions can change, not the number of points.
  23334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23335. */
  23336. MeshBuilder.CreateLines = function (name, options, scene) {
  23337. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  23338. return lines;
  23339. };
  23340. /**
  23341. * Creates a dashed line mesh.
  23342. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  23343. * 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.
  23344. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23345. * The parameter `points` is an array successive Vector3.
  23346. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23347. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23348. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23349. * 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
  23350. * When updating an instance, remember that only point positions can change, not the number of points.
  23351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23352. */
  23353. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  23354. var points = options.points;
  23355. var instance = options.instance;
  23356. var gapSize = options.gapSize;
  23357. var dashNb = options.dashNb;
  23358. var dashSize = options.dashSize;
  23359. if (instance) {
  23360. var positionFunction = function (positions) {
  23361. var curvect = BABYLON.Vector3.Zero();
  23362. var nbSeg = positions.length / 6;
  23363. var lg = 0;
  23364. var nb = 0;
  23365. var shft = 0;
  23366. var dashshft = 0;
  23367. var curshft = 0;
  23368. var p = 0;
  23369. var i = 0;
  23370. var j = 0;
  23371. for (i = 0; i < points.length - 1; i++) {
  23372. points[i + 1].subtractToRef(points[i], curvect);
  23373. lg += curvect.length();
  23374. }
  23375. shft = lg / nbSeg;
  23376. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  23377. for (i = 0; i < points.length - 1; i++) {
  23378. points[i + 1].subtractToRef(points[i], curvect);
  23379. nb = Math.floor(curvect.length() / shft);
  23380. curvect.normalize();
  23381. j = 0;
  23382. while (j < nb && p < positions.length) {
  23383. curshft = shft * j;
  23384. positions[p] = points[i].x + curshft * curvect.x;
  23385. positions[p + 1] = points[i].y + curshft * curvect.y;
  23386. positions[p + 2] = points[i].z + curshft * curvect.z;
  23387. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  23388. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  23389. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  23390. p += 6;
  23391. j++;
  23392. }
  23393. }
  23394. while (p < positions.length) {
  23395. positions[p] = points[i].x;
  23396. positions[p + 1] = points[i].y;
  23397. positions[p + 2] = points[i].z;
  23398. p += 3;
  23399. }
  23400. };
  23401. instance.updateMeshPositions(positionFunction, false);
  23402. return instance;
  23403. }
  23404. // dashed lines creation
  23405. var dashedLines = new BABYLON.LinesMesh(name, scene);
  23406. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  23407. vertexData.applyToMesh(dashedLines, options.updatable);
  23408. dashedLines.dashSize = dashSize;
  23409. dashedLines.gapSize = gapSize;
  23410. return dashedLines;
  23411. };
  23412. /**
  23413. * Creates an extruded shape mesh.
  23414. * 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.
  23415. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  23416. *
  23417. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23418. * 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
  23419. * extruded along the Z axis.
  23420. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23421. * 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.
  23422. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23423. * 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
  23424. * 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
  23425. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23426. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23428. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23430. */
  23431. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  23432. var path = options.path;
  23433. var shape = options.shape;
  23434. var scale = options.scale || 1;
  23435. var rotation = options.rotation || 0;
  23436. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23437. var updatable = options.updatable;
  23438. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23439. var instance = options.instance;
  23440. var invertUV = options.invertUV || false;
  23441. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  23442. };
  23443. /**
  23444. * Creates an custom extruded shape mesh.
  23445. * 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.
  23446. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  23447. *
  23448. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23449. * 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
  23450. * extruded along the Z axis.
  23451. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23452. * 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
  23453. * and the distance of this point from the begining of the path :
  23454. * ```javascript
  23455. * var rotationFunction = function(i, distance) {
  23456. * // do things
  23457. * return rotationValue; }
  23458. * ```
  23459. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23460. * 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
  23461. * and the distance of this point from the begining of the path :
  23462. * ```javascript
  23463. * var scaleFunction = function(i, distance) {
  23464. * // do things
  23465. * return scaleValue;}
  23466. * ```
  23467. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23468. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23469. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23470. * 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
  23471. * 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
  23472. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23475. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23477. */
  23478. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  23479. var path = options.path;
  23480. var shape = options.shape;
  23481. var scaleFunction = options.scaleFunction || (function () { return 1; });
  23482. var rotationFunction = options.rotationFunction || (function () { return 0; });
  23483. var ribbonCloseArray = options.ribbonCloseArray || false;
  23484. var ribbonClosePath = options.ribbonClosePath || false;
  23485. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23486. var updatable = options.updatable;
  23487. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23488. var instance = options.instance;
  23489. var invertUV = options.invertUV || false;
  23490. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  23491. };
  23492. /**
  23493. * Creates lathe mesh.
  23494. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23495. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  23496. *
  23497. * 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
  23498. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23499. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23500. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23501. * 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.
  23502. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  23503. * 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
  23504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23506. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23508. */
  23509. MeshBuilder.CreateLathe = function (name, options, scene) {
  23510. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  23511. var closed = (options.closed === undefined) ? true : options.closed;
  23512. var shape = options.shape;
  23513. var radius = options.radius || 1;
  23514. var tessellation = options.tessellation || 64;
  23515. var updatable = options.updatable;
  23516. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23517. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23518. var pi2 = Math.PI * 2;
  23519. var paths = new Array();
  23520. var invertUV = options.invertUV || false;
  23521. var i = 0;
  23522. var p = 0;
  23523. var step = pi2 / tessellation * arc;
  23524. var rotated;
  23525. var path = new Array();
  23526. ;
  23527. for (i = 0; i <= tessellation; i++) {
  23528. var path = [];
  23529. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  23530. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  23531. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  23532. }
  23533. for (p = 0; p < shape.length; p++) {
  23534. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  23535. path.push(rotated);
  23536. }
  23537. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  23538. 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));
  23539. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  23540. }
  23541. paths.push(path);
  23542. }
  23543. // lathe ribbon
  23544. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  23545. return lathe;
  23546. };
  23547. /**
  23548. * Creates a plane mesh.
  23549. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23550. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23551. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  23552. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  23553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23556. */
  23557. MeshBuilder.CreatePlane = function (name, options, scene) {
  23558. var plane = new BABYLON.Mesh(name, scene);
  23559. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23560. plane.sideOrientation = options.sideOrientation;
  23561. var vertexData = BABYLON.VertexData.CreatePlane(options);
  23562. vertexData.applyToMesh(plane, options.updatable);
  23563. if (options.sourcePlane) {
  23564. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  23565. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  23566. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  23567. plane.rotate(vectorProduct, product);
  23568. }
  23569. return plane;
  23570. };
  23571. /**
  23572. * Creates a ground mesh.
  23573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23574. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23575. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23577. */
  23578. MeshBuilder.CreateGround = function (name, options, scene) {
  23579. var ground = new BABYLON.GroundMesh(name, scene);
  23580. ground._setReady(false);
  23581. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  23582. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  23583. ground._width = options.width || 1;
  23584. ground._height = options.height || 1;
  23585. ground._maxX = ground._width / 2;
  23586. ground._maxZ = ground._height / 2;
  23587. ground._minX = -ground._maxX;
  23588. ground._minZ = -ground._maxZ;
  23589. var vertexData = BABYLON.VertexData.CreateGround(options);
  23590. vertexData.applyToMesh(ground, options.updatable);
  23591. ground._setReady(true);
  23592. return ground;
  23593. };
  23594. /**
  23595. * Creates a tiled ground mesh.
  23596. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  23597. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23598. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23599. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23600. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23601. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23602. * numbers of subdivisions on the ground width and height of each tile.
  23603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23604. */
  23605. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  23606. var tiledGround = new BABYLON.Mesh(name, scene);
  23607. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  23608. vertexData.applyToMesh(tiledGround, options.updatable);
  23609. return tiledGround;
  23610. };
  23611. /**
  23612. * Creates a ground mesh from a height map.
  23613. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23614. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  23615. * The parameter `url` sets the URL of the height map image resource.
  23616. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23617. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23618. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23619. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23620. * 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).
  23621. * This function is passed the newly built mesh :
  23622. * ```javascript
  23623. * function(mesh) { // do things
  23624. * return; }
  23625. * ```
  23626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23627. */
  23628. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  23629. var width = options.width || 10.0;
  23630. var height = options.height || 10.0;
  23631. var subdivisions = options.subdivisions || 1 | 0;
  23632. var minHeight = options.minHeight || 0.0;
  23633. var maxHeight = options.maxHeight || 10.0;
  23634. var updatable = options.updatable;
  23635. var onReady = options.onReady;
  23636. var ground = new BABYLON.GroundMesh(name, scene);
  23637. ground._subdivisionsX = subdivisions;
  23638. ground._subdivisionsY = subdivisions;
  23639. ground._width = width;
  23640. ground._height = height;
  23641. ground._maxX = ground._width / 2.0;
  23642. ground._maxZ = ground._height / 2.0;
  23643. ground._minX = -ground._maxX;
  23644. ground._minZ = -ground._maxZ;
  23645. ground._setReady(false);
  23646. var onload = function (img) {
  23647. // Getting height map data
  23648. var canvas = document.createElement("canvas");
  23649. var context = canvas.getContext("2d");
  23650. var bufferWidth = img.width;
  23651. var bufferHeight = img.height;
  23652. canvas.width = bufferWidth;
  23653. canvas.height = bufferHeight;
  23654. context.drawImage(img, 0, 0);
  23655. // Create VertexData from map data
  23656. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23657. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  23658. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  23659. width: width, height: height,
  23660. subdivisions: subdivisions,
  23661. minHeight: minHeight, maxHeight: maxHeight,
  23662. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  23663. });
  23664. vertexData.applyToMesh(ground, updatable);
  23665. ground._setReady(true);
  23666. //execute ready callback, if set
  23667. if (onReady) {
  23668. onReady(ground);
  23669. }
  23670. };
  23671. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23672. return ground;
  23673. };
  23674. /**
  23675. * Creates a tube mesh.
  23676. * 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.
  23677. *
  23678. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  23679. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23680. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23681. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23682. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23683. * 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.
  23684. * It must return a radius value (positive float) :
  23685. * ```javascript
  23686. * var radiusFunction = function(i, distance) {
  23687. * // do things
  23688. * return radius; }
  23689. * ```
  23690. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  23691. * 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
  23692. * 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
  23693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23695. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23697. */
  23698. MeshBuilder.CreateTube = function (name, options, scene) {
  23699. var path = options.path;
  23700. var radius = options.radius || 1.0;
  23701. var tessellation = options.tessellation || 64 | 0;
  23702. var radiusFunction = options.radiusFunction;
  23703. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23704. var invertUV = options.invertUV || false;
  23705. var updatable = options.updatable;
  23706. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23707. var instance = options.instance;
  23708. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  23709. // tube geometry
  23710. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  23711. var tangents = path3D.getTangents();
  23712. var normals = path3D.getNormals();
  23713. var distances = path3D.getDistances();
  23714. var pi2 = Math.PI * 2;
  23715. var step = pi2 / tessellation * arc;
  23716. var returnRadius = function () { return radius; };
  23717. var radiusFunctionFinal = radiusFunction || returnRadius;
  23718. var circlePath;
  23719. var rad;
  23720. var normal;
  23721. var rotated;
  23722. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23723. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23724. for (var i = 0; i < path.length; i++) {
  23725. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23726. circlePath = Array(); // current circle array
  23727. normal = normals[i]; // current normal
  23728. for (var t = 0; t < tessellation; t++) {
  23729. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23730. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23731. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23732. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23733. circlePath[t] = rotated;
  23734. }
  23735. circlePaths[index] = circlePath;
  23736. index++;
  23737. }
  23738. // cap
  23739. var capPath = function (nbPoints, pathIndex) {
  23740. var pointCap = Array();
  23741. for (var i = 0; i < nbPoints; i++) {
  23742. pointCap.push(path[pathIndex]);
  23743. }
  23744. return pointCap;
  23745. };
  23746. switch (cap) {
  23747. case BABYLON.Mesh.NO_CAP:
  23748. break;
  23749. case BABYLON.Mesh.CAP_START:
  23750. circlePaths[0] = capPath(tessellation, 0);
  23751. circlePaths[1] = circlePaths[2].slice(0);
  23752. break;
  23753. case BABYLON.Mesh.CAP_END:
  23754. circlePaths[index] = circlePaths[index - 1].slice(0);
  23755. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23756. break;
  23757. case BABYLON.Mesh.CAP_ALL:
  23758. circlePaths[0] = capPath(tessellation, 0);
  23759. circlePaths[1] = circlePaths[2].slice(0);
  23760. circlePaths[index] = circlePaths[index - 1].slice(0);
  23761. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23762. break;
  23763. default:
  23764. break;
  23765. }
  23766. return circlePaths;
  23767. };
  23768. var path3D;
  23769. var pathArray;
  23770. if (instance) {
  23771. var arc = options.arc || instance.arc;
  23772. path3D = (instance.path3D).update(path);
  23773. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23774. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23775. instance.path3D = path3D;
  23776. instance.pathArray = pathArray;
  23777. instance.arc = arc;
  23778. return instance;
  23779. }
  23780. // tube creation
  23781. path3D = new BABYLON.Path3D(path);
  23782. var newPathArray = new Array();
  23783. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23784. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23785. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23786. tube.pathArray = pathArray;
  23787. tube.path3D = path3D;
  23788. tube.tessellation = tessellation;
  23789. tube.cap = cap;
  23790. tube.arc = options.arc;
  23791. return tube;
  23792. };
  23793. /**
  23794. * Creates a polyhedron mesh.
  23795. *
  23796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23797. * 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
  23798. * to choose the wanted type.
  23799. * The parameter `size` (positive float, default 1) sets the polygon size.
  23800. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23801. * 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`.
  23802. * 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
  23803. * 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)`).
  23804. * 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
  23805. * 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.
  23806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23809. */
  23810. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23811. var polyhedron = new BABYLON.Mesh(name, scene);
  23812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23813. polyhedron.sideOrientation = options.sideOrientation;
  23814. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23815. vertexData.applyToMesh(polyhedron, options.updatable);
  23816. return polyhedron;
  23817. };
  23818. /**
  23819. * Creates a decal mesh.
  23820. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23821. * 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.
  23822. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23823. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23824. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23825. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23826. */
  23827. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23828. var indices = sourceMesh.getIndices();
  23829. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23830. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23831. var position = options.position || BABYLON.Vector3.Zero();
  23832. var normal = options.normal || BABYLON.Vector3.Up();
  23833. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23834. var angle = options.angle || 0;
  23835. // Getting correct rotation
  23836. if (!normal) {
  23837. var target = new BABYLON.Vector3(0, 0, 1);
  23838. var camera = sourceMesh.getScene().activeCamera;
  23839. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23840. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23841. }
  23842. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23843. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23844. var pitch = Math.atan2(normal.y, len);
  23845. // Matrix
  23846. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23847. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23848. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23849. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23850. var vertexData = new BABYLON.VertexData();
  23851. vertexData.indices = [];
  23852. vertexData.positions = [];
  23853. vertexData.normals = [];
  23854. vertexData.uvs = [];
  23855. var currentVertexDataIndex = 0;
  23856. var extractDecalVector3 = function (indexId) {
  23857. var vertexId = indices[indexId];
  23858. var result = new BABYLON.PositionNormalVertex();
  23859. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23860. // Send vector to decal local world
  23861. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23862. // Get normal
  23863. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23864. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  23865. return result;
  23866. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23867. var clip = function (vertices, axis) {
  23868. if (vertices.length === 0) {
  23869. return vertices;
  23870. }
  23871. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23872. var clipVertices = function (v0, v1) {
  23873. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23874. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23875. };
  23876. var result = new Array();
  23877. for (var index = 0; index < vertices.length; index += 3) {
  23878. var v1Out;
  23879. var v2Out;
  23880. var v3Out;
  23881. var total = 0;
  23882. var nV1, nV2, nV3, nV4;
  23883. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23884. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23885. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23886. v1Out = d1 > 0;
  23887. v2Out = d2 > 0;
  23888. v3Out = d3 > 0;
  23889. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23890. switch (total) {
  23891. case 0:
  23892. result.push(vertices[index]);
  23893. result.push(vertices[index + 1]);
  23894. result.push(vertices[index + 2]);
  23895. break;
  23896. case 1:
  23897. if (v1Out) {
  23898. nV1 = vertices[index + 1];
  23899. nV2 = vertices[index + 2];
  23900. nV3 = clipVertices(vertices[index], nV1);
  23901. nV4 = clipVertices(vertices[index], nV2);
  23902. }
  23903. if (v2Out) {
  23904. nV1 = vertices[index];
  23905. nV2 = vertices[index + 2];
  23906. nV3 = clipVertices(vertices[index + 1], nV1);
  23907. nV4 = clipVertices(vertices[index + 1], nV2);
  23908. result.push(nV3);
  23909. result.push(nV2.clone());
  23910. result.push(nV1.clone());
  23911. result.push(nV2.clone());
  23912. result.push(nV3.clone());
  23913. result.push(nV4);
  23914. break;
  23915. }
  23916. if (v3Out) {
  23917. nV1 = vertices[index];
  23918. nV2 = vertices[index + 1];
  23919. nV3 = clipVertices(vertices[index + 2], nV1);
  23920. nV4 = clipVertices(vertices[index + 2], nV2);
  23921. }
  23922. result.push(nV1.clone());
  23923. result.push(nV2.clone());
  23924. result.push(nV3);
  23925. result.push(nV4);
  23926. result.push(nV3.clone());
  23927. result.push(nV2.clone());
  23928. break;
  23929. case 2:
  23930. if (!v1Out) {
  23931. nV1 = vertices[index].clone();
  23932. nV2 = clipVertices(nV1, vertices[index + 1]);
  23933. nV3 = clipVertices(nV1, vertices[index + 2]);
  23934. result.push(nV1);
  23935. result.push(nV2);
  23936. result.push(nV3);
  23937. }
  23938. if (!v2Out) {
  23939. nV1 = vertices[index + 1].clone();
  23940. nV2 = clipVertices(nV1, vertices[index + 2]);
  23941. nV3 = clipVertices(nV1, vertices[index]);
  23942. result.push(nV1);
  23943. result.push(nV2);
  23944. result.push(nV3);
  23945. }
  23946. if (!v3Out) {
  23947. nV1 = vertices[index + 2].clone();
  23948. nV2 = clipVertices(nV1, vertices[index]);
  23949. nV3 = clipVertices(nV1, vertices[index + 1]);
  23950. result.push(nV1);
  23951. result.push(nV2);
  23952. result.push(nV3);
  23953. }
  23954. break;
  23955. case 3:
  23956. break;
  23957. }
  23958. }
  23959. return result;
  23960. };
  23961. for (var index = 0; index < indices.length; index += 3) {
  23962. var faceVertices = new Array();
  23963. faceVertices.push(extractDecalVector3(index));
  23964. faceVertices.push(extractDecalVector3(index + 1));
  23965. faceVertices.push(extractDecalVector3(index + 2));
  23966. // Clip
  23967. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23968. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23969. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23970. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23971. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23972. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23973. if (faceVertices.length === 0) {
  23974. continue;
  23975. }
  23976. // Add UVs and get back to world
  23977. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23978. var vertex = faceVertices[vIndex];
  23979. //TODO check for Int32Array | Uint32Array | Uint16Array
  23980. vertexData.indices.push(currentVertexDataIndex);
  23981. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23982. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23983. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23984. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23985. currentVertexDataIndex++;
  23986. }
  23987. }
  23988. // Return mesh
  23989. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23990. vertexData.applyToMesh(decal);
  23991. decal.position = position.clone();
  23992. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23993. return decal;
  23994. };
  23995. // Privates
  23996. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23997. // extrusion geometry
  23998. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23999. var tangents = path3D.getTangents();
  24000. var normals = path3D.getNormals();
  24001. var binormals = path3D.getBinormals();
  24002. var distances = path3D.getDistances();
  24003. var angle = 0;
  24004. var returnScale = function () { return scale; };
  24005. var returnRotation = function () { return rotation; };
  24006. var rotate = custom ? rotateFunction : returnRotation;
  24007. var scl = custom ? scaleFunction : returnScale;
  24008. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  24009. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  24010. for (var i = 0; i < curve.length; i++) {
  24011. var shapePath = new Array();
  24012. var angleStep = rotate(i, distances[i]);
  24013. var scaleRatio = scl(i, distances[i]);
  24014. for (var p = 0; p < shape.length; p++) {
  24015. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  24016. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  24017. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  24018. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  24019. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  24020. shapePath[p] = rotated;
  24021. }
  24022. shapePaths[index] = shapePath;
  24023. angle += angleStep;
  24024. index++;
  24025. }
  24026. // cap
  24027. var capPath = function (shapePath) {
  24028. var pointCap = Array();
  24029. var barycenter = BABYLON.Vector3.Zero();
  24030. var i;
  24031. for (i = 0; i < shapePath.length; i++) {
  24032. barycenter.addInPlace(shapePath[i]);
  24033. }
  24034. barycenter.scaleInPlace(1.0 / shapePath.length);
  24035. for (i = 0; i < shapePath.length; i++) {
  24036. pointCap.push(barycenter);
  24037. }
  24038. return pointCap;
  24039. };
  24040. switch (cap) {
  24041. case BABYLON.Mesh.NO_CAP:
  24042. break;
  24043. case BABYLON.Mesh.CAP_START:
  24044. shapePaths[0] = capPath(shapePaths[2]);
  24045. shapePaths[1] = shapePaths[2];
  24046. break;
  24047. case BABYLON.Mesh.CAP_END:
  24048. shapePaths[index] = shapePaths[index - 1];
  24049. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  24050. break;
  24051. case BABYLON.Mesh.CAP_ALL:
  24052. shapePaths[0] = capPath(shapePaths[2]);
  24053. shapePaths[1] = shapePaths[2];
  24054. shapePaths[index] = shapePaths[index - 1];
  24055. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  24056. break;
  24057. default:
  24058. break;
  24059. }
  24060. return shapePaths;
  24061. };
  24062. var path3D;
  24063. var pathArray;
  24064. if (instance) {
  24065. path3D = (instance.path3D).update(curve);
  24066. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  24067. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  24068. return instance;
  24069. }
  24070. // extruded shape creation
  24071. path3D = new BABYLON.Path3D(curve);
  24072. var newShapePaths = new Array();
  24073. cap = (cap < 0 || cap > 3) ? 0 : cap;
  24074. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  24075. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  24076. extrudedGeneric.pathArray = pathArray;
  24077. extrudedGeneric.path3D = path3D;
  24078. extrudedGeneric.cap = cap;
  24079. return extrudedGeneric;
  24080. };
  24081. return MeshBuilder;
  24082. }());
  24083. BABYLON.MeshBuilder = MeshBuilder;
  24084. })(BABYLON || (BABYLON = {}));
  24085. //# sourceMappingURL=babylon.meshBuilder.js.map
  24086. var BABYLON;
  24087. (function (BABYLON) {
  24088. var BaseTexture = (function () {
  24089. function BaseTexture(scene) {
  24090. this.hasAlpha = false;
  24091. this.getAlphaFromRGB = false;
  24092. this.level = 1;
  24093. this.coordinatesIndex = 0;
  24094. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24095. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24096. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24097. this.anisotropicFilteringLevel = 4;
  24098. this.isCube = false;
  24099. this.isRenderTarget = false;
  24100. this.animations = new Array();
  24101. /**
  24102. * An event triggered when the texture is disposed.
  24103. * @type {BABYLON.Observable}
  24104. */
  24105. this.onDisposeObservable = new BABYLON.Observable();
  24106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24107. this._scene = scene;
  24108. this._scene.textures.push(this);
  24109. this._uid = null;
  24110. }
  24111. Object.defineProperty(BaseTexture.prototype, "uid", {
  24112. get: function () {
  24113. if (!this._uid) {
  24114. this._uid = BABYLON.Tools.RandomId();
  24115. }
  24116. return this._uid;
  24117. },
  24118. enumerable: true,
  24119. configurable: true
  24120. });
  24121. BaseTexture.prototype.toString = function () {
  24122. return this.name;
  24123. };
  24124. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24125. set: function (callback) {
  24126. if (this._onDisposeObserver) {
  24127. this.onDisposeObservable.remove(this._onDisposeObserver);
  24128. }
  24129. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24130. },
  24131. enumerable: true,
  24132. configurable: true
  24133. });
  24134. BaseTexture.prototype.getScene = function () {
  24135. return this._scene;
  24136. };
  24137. BaseTexture.prototype.getTextureMatrix = function () {
  24138. return null;
  24139. };
  24140. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24141. return null;
  24142. };
  24143. BaseTexture.prototype.getInternalTexture = function () {
  24144. return this._texture;
  24145. };
  24146. BaseTexture.prototype.isReady = function () {
  24147. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24148. return true;
  24149. }
  24150. if (this._texture) {
  24151. return this._texture.isReady;
  24152. }
  24153. return false;
  24154. };
  24155. BaseTexture.prototype.getSize = function () {
  24156. if (this._texture._width) {
  24157. return new BABYLON.Size(this._texture._width, this._texture._height);
  24158. }
  24159. if (this._texture._size) {
  24160. return new BABYLON.Size(this._texture._size, this._texture._size);
  24161. }
  24162. return BABYLON.Size.Zero();
  24163. };
  24164. BaseTexture.prototype.getBaseSize = function () {
  24165. if (!this.isReady() || !this._texture)
  24166. return BABYLON.Size.Zero();
  24167. if (this._texture._size) {
  24168. return new BABYLON.Size(this._texture._size, this._texture._size);
  24169. }
  24170. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  24171. };
  24172. BaseTexture.prototype.scale = function (ratio) {
  24173. };
  24174. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24175. get: function () {
  24176. return false;
  24177. },
  24178. enumerable: true,
  24179. configurable: true
  24180. });
  24181. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  24182. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24183. for (var index = 0; index < texturesCache.length; index++) {
  24184. var texturesCacheEntry = texturesCache[index];
  24185. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24186. texturesCache.splice(index, 1);
  24187. return;
  24188. }
  24189. }
  24190. };
  24191. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24192. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24193. for (var index = 0; index < texturesCache.length; index++) {
  24194. var texturesCacheEntry = texturesCache[index];
  24195. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24196. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24197. texturesCacheEntry.references++;
  24198. return texturesCacheEntry;
  24199. }
  24200. }
  24201. }
  24202. return null;
  24203. };
  24204. BaseTexture.prototype.delayLoad = function () {
  24205. };
  24206. BaseTexture.prototype.clone = function () {
  24207. return null;
  24208. };
  24209. BaseTexture.prototype.releaseInternalTexture = function () {
  24210. if (this._texture) {
  24211. this._scene.getEngine().releaseInternalTexture(this._texture);
  24212. delete this._texture;
  24213. }
  24214. };
  24215. BaseTexture.prototype.dispose = function () {
  24216. // Animations
  24217. this.getScene().stopAnimation(this);
  24218. // Remove from scene
  24219. var index = this._scene.textures.indexOf(this);
  24220. if (index >= 0) {
  24221. this._scene.textures.splice(index, 1);
  24222. }
  24223. if (this._texture === undefined) {
  24224. return;
  24225. }
  24226. // Release
  24227. this.releaseInternalTexture();
  24228. // Callback
  24229. this.onDisposeObservable.notifyObservers(this);
  24230. this.onDisposeObservable.clear();
  24231. };
  24232. BaseTexture.prototype.serialize = function () {
  24233. if (!this.name) {
  24234. return null;
  24235. }
  24236. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24237. // Animations
  24238. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24239. return serializationObject;
  24240. };
  24241. return BaseTexture;
  24242. }());
  24243. __decorate([
  24244. BABYLON.serialize()
  24245. ], BaseTexture.prototype, "name", void 0);
  24246. __decorate([
  24247. BABYLON.serialize()
  24248. ], BaseTexture.prototype, "hasAlpha", void 0);
  24249. __decorate([
  24250. BABYLON.serialize()
  24251. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24252. __decorate([
  24253. BABYLON.serialize()
  24254. ], BaseTexture.prototype, "level", void 0);
  24255. __decorate([
  24256. BABYLON.serialize()
  24257. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24258. __decorate([
  24259. BABYLON.serialize()
  24260. ], BaseTexture.prototype, "coordinatesMode", void 0);
  24261. __decorate([
  24262. BABYLON.serialize()
  24263. ], BaseTexture.prototype, "wrapU", void 0);
  24264. __decorate([
  24265. BABYLON.serialize()
  24266. ], BaseTexture.prototype, "wrapV", void 0);
  24267. __decorate([
  24268. BABYLON.serialize()
  24269. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24270. __decorate([
  24271. BABYLON.serialize()
  24272. ], BaseTexture.prototype, "isCube", void 0);
  24273. __decorate([
  24274. BABYLON.serialize()
  24275. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24276. BABYLON.BaseTexture = BaseTexture;
  24277. })(BABYLON || (BABYLON = {}));
  24278. //# sourceMappingURL=babylon.baseTexture.js.map
  24279. var BABYLON;
  24280. (function (BABYLON) {
  24281. var Texture = (function (_super) {
  24282. __extends(Texture, _super);
  24283. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  24284. if (noMipmap === void 0) { noMipmap = false; }
  24285. if (invertY === void 0) { invertY = true; }
  24286. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24287. if (onLoad === void 0) { onLoad = null; }
  24288. if (onError === void 0) { onError = null; }
  24289. if (buffer === void 0) { buffer = null; }
  24290. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24291. var _this = _super.call(this, scene) || this;
  24292. _this.uOffset = 0;
  24293. _this.vOffset = 0;
  24294. _this.uScale = 1.0;
  24295. _this.vScale = 1.0;
  24296. _this.uAng = 0;
  24297. _this.vAng = 0;
  24298. _this.wAng = 0;
  24299. _this.name = url;
  24300. _this.url = url;
  24301. _this._noMipmap = noMipmap;
  24302. _this._invertY = invertY;
  24303. _this._samplingMode = samplingMode;
  24304. _this._buffer = buffer;
  24305. _this._deleteBuffer = deleteBuffer;
  24306. if (!url) {
  24307. return _this;
  24308. }
  24309. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  24310. var load = function () {
  24311. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  24312. _this.onLoadObservable.notifyObservers(true);
  24313. }
  24314. if (onLoad) {
  24315. onLoad();
  24316. }
  24317. };
  24318. if (!_this._texture) {
  24319. if (!scene.useDelayedTextureLoading) {
  24320. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  24321. if (deleteBuffer) {
  24322. delete _this._buffer;
  24323. }
  24324. }
  24325. else {
  24326. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24327. _this._delayedOnLoad = load;
  24328. _this._delayedOnError = onError;
  24329. }
  24330. }
  24331. else {
  24332. if (_this._texture.isReady) {
  24333. BABYLON.Tools.SetImmediate(function () { return load(); });
  24334. }
  24335. else {
  24336. _this._texture.onLoadedCallbacks.push(load);
  24337. }
  24338. }
  24339. return _this;
  24340. }
  24341. Object.defineProperty(Texture.prototype, "noMipmap", {
  24342. get: function () {
  24343. return this._noMipmap;
  24344. },
  24345. enumerable: true,
  24346. configurable: true
  24347. });
  24348. Texture.prototype.delayLoad = function () {
  24349. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24350. return;
  24351. }
  24352. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24353. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24354. if (!this._texture) {
  24355. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  24356. if (this._deleteBuffer) {
  24357. delete this._buffer;
  24358. }
  24359. }
  24360. };
  24361. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24362. if (!this._texture) {
  24363. return;
  24364. }
  24365. this._samplingMode = samplingMode;
  24366. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24367. };
  24368. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24369. x *= this.uScale;
  24370. y *= this.vScale;
  24371. x -= 0.5 * this.uScale;
  24372. y -= 0.5 * this.vScale;
  24373. z -= 0.5;
  24374. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24375. t.x += 0.5 * this.uScale + this.uOffset;
  24376. t.y += 0.5 * this.vScale + this.vOffset;
  24377. t.z += 0.5;
  24378. };
  24379. Texture.prototype.getTextureMatrix = function () {
  24380. if (this.uOffset === this._cachedUOffset &&
  24381. this.vOffset === this._cachedVOffset &&
  24382. this.uScale === this._cachedUScale &&
  24383. this.vScale === this._cachedVScale &&
  24384. this.uAng === this._cachedUAng &&
  24385. this.vAng === this._cachedVAng &&
  24386. this.wAng === this._cachedWAng) {
  24387. return this._cachedTextureMatrix;
  24388. }
  24389. this._cachedUOffset = this.uOffset;
  24390. this._cachedVOffset = this.vOffset;
  24391. this._cachedUScale = this.uScale;
  24392. this._cachedVScale = this.vScale;
  24393. this._cachedUAng = this.uAng;
  24394. this._cachedVAng = this.vAng;
  24395. this._cachedWAng = this.wAng;
  24396. if (!this._cachedTextureMatrix) {
  24397. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24398. this._rowGenerationMatrix = new BABYLON.Matrix();
  24399. this._t0 = BABYLON.Vector3.Zero();
  24400. this._t1 = BABYLON.Vector3.Zero();
  24401. this._t2 = BABYLON.Vector3.Zero();
  24402. }
  24403. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24404. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24405. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24406. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24407. this._t1.subtractInPlace(this._t0);
  24408. this._t2.subtractInPlace(this._t0);
  24409. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24410. this._cachedTextureMatrix.m[0] = this._t1.x;
  24411. this._cachedTextureMatrix.m[1] = this._t1.y;
  24412. this._cachedTextureMatrix.m[2] = this._t1.z;
  24413. this._cachedTextureMatrix.m[4] = this._t2.x;
  24414. this._cachedTextureMatrix.m[5] = this._t2.y;
  24415. this._cachedTextureMatrix.m[6] = this._t2.z;
  24416. this._cachedTextureMatrix.m[8] = this._t0.x;
  24417. this._cachedTextureMatrix.m[9] = this._t0.y;
  24418. this._cachedTextureMatrix.m[10] = this._t0.z;
  24419. return this._cachedTextureMatrix;
  24420. };
  24421. Texture.prototype.getReflectionTextureMatrix = function () {
  24422. if (this.uOffset === this._cachedUOffset &&
  24423. this.vOffset === this._cachedVOffset &&
  24424. this.uScale === this._cachedUScale &&
  24425. this.vScale === this._cachedVScale &&
  24426. this.coordinatesMode === this._cachedCoordinatesMode) {
  24427. return this._cachedTextureMatrix;
  24428. }
  24429. if (!this._cachedTextureMatrix) {
  24430. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24431. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24432. }
  24433. this._cachedCoordinatesMode = this.coordinatesMode;
  24434. switch (this.coordinatesMode) {
  24435. case Texture.PLANAR_MODE:
  24436. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24437. this._cachedTextureMatrix[0] = this.uScale;
  24438. this._cachedTextureMatrix[5] = this.vScale;
  24439. this._cachedTextureMatrix[12] = this.uOffset;
  24440. this._cachedTextureMatrix[13] = this.vOffset;
  24441. break;
  24442. case Texture.PROJECTION_MODE:
  24443. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24444. this._projectionModeMatrix.m[0] = 0.5;
  24445. this._projectionModeMatrix.m[5] = -0.5;
  24446. this._projectionModeMatrix.m[10] = 0.0;
  24447. this._projectionModeMatrix.m[12] = 0.5;
  24448. this._projectionModeMatrix.m[13] = 0.5;
  24449. this._projectionModeMatrix.m[14] = 1.0;
  24450. this._projectionModeMatrix.m[15] = 1.0;
  24451. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24452. break;
  24453. default:
  24454. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24455. break;
  24456. }
  24457. return this._cachedTextureMatrix;
  24458. };
  24459. Texture.prototype.clone = function () {
  24460. var _this = this;
  24461. return BABYLON.SerializationHelper.Clone(function () {
  24462. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24463. }, this);
  24464. };
  24465. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24466. get: function () {
  24467. if (!this._onLoadObservarble) {
  24468. this._onLoadObservarble = new BABYLON.Observable();
  24469. }
  24470. return this._onLoadObservarble;
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. // Statics
  24476. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  24477. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24478. if (onLoad === void 0) { onLoad = null; }
  24479. if (onError === void 0) { onError = null; }
  24480. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  24481. };
  24482. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24483. if (parsedTexture.customType) {
  24484. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24485. return customTexture.Parse(parsedTexture, scene, rootUrl);
  24486. }
  24487. if (parsedTexture.isCube) {
  24488. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24489. }
  24490. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24491. return null;
  24492. }
  24493. var texture = BABYLON.SerializationHelper.Parse(function () {
  24494. if (parsedTexture.mirrorPlane) {
  24495. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24496. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24497. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24498. return mirrorTexture;
  24499. }
  24500. else if (parsedTexture.isRenderTarget) {
  24501. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24502. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24503. return renderTargetTexture;
  24504. }
  24505. else {
  24506. var texture;
  24507. if (parsedTexture.base64String) {
  24508. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  24509. }
  24510. else {
  24511. texture = new Texture(rootUrl + parsedTexture.name, scene);
  24512. }
  24513. return texture;
  24514. }
  24515. }, parsedTexture, scene);
  24516. // Animations
  24517. if (parsedTexture.animations) {
  24518. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24519. var parsedAnimation = parsedTexture.animations[animationIndex];
  24520. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24521. }
  24522. }
  24523. return texture;
  24524. };
  24525. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  24526. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24527. if (noMipmap === void 0) { noMipmap = false; }
  24528. if (invertY === void 0) { invertY = true; }
  24529. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24530. if (onLoad === void 0) { onLoad = null; }
  24531. if (onError === void 0) { onError = null; }
  24532. if (name.substr(0, 5) !== "data:") {
  24533. name = "data:" + name;
  24534. }
  24535. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  24536. };
  24537. return Texture;
  24538. }(BABYLON.BaseTexture));
  24539. // Constants
  24540. Texture.NEAREST_SAMPLINGMODE = 1;
  24541. Texture.BILINEAR_SAMPLINGMODE = 2;
  24542. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24543. Texture.EXPLICIT_MODE = 0;
  24544. Texture.SPHERICAL_MODE = 1;
  24545. Texture.PLANAR_MODE = 2;
  24546. Texture.CUBIC_MODE = 3;
  24547. Texture.PROJECTION_MODE = 4;
  24548. Texture.SKYBOX_MODE = 5;
  24549. Texture.INVCUBIC_MODE = 6;
  24550. Texture.EQUIRECTANGULAR_MODE = 7;
  24551. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24552. Texture.CLAMP_ADDRESSMODE = 0;
  24553. Texture.WRAP_ADDRESSMODE = 1;
  24554. Texture.MIRROR_ADDRESSMODE = 2;
  24555. __decorate([
  24556. BABYLON.serialize()
  24557. ], Texture.prototype, "url", void 0);
  24558. __decorate([
  24559. BABYLON.serialize()
  24560. ], Texture.prototype, "uOffset", void 0);
  24561. __decorate([
  24562. BABYLON.serialize()
  24563. ], Texture.prototype, "vOffset", void 0);
  24564. __decorate([
  24565. BABYLON.serialize()
  24566. ], Texture.prototype, "uScale", void 0);
  24567. __decorate([
  24568. BABYLON.serialize()
  24569. ], Texture.prototype, "vScale", void 0);
  24570. __decorate([
  24571. BABYLON.serialize()
  24572. ], Texture.prototype, "uAng", void 0);
  24573. __decorate([
  24574. BABYLON.serialize()
  24575. ], Texture.prototype, "vAng", void 0);
  24576. __decorate([
  24577. BABYLON.serialize()
  24578. ], Texture.prototype, "wAng", void 0);
  24579. BABYLON.Texture = Texture;
  24580. })(BABYLON || (BABYLON = {}));
  24581. //# sourceMappingURL=babylon.texture.js.map
  24582. var BABYLON;
  24583. (function (BABYLON) {
  24584. var CubeTexture = (function (_super) {
  24585. __extends(CubeTexture, _super);
  24586. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  24587. if (onLoad === void 0) { onLoad = null; }
  24588. if (onError === void 0) { onError = null; }
  24589. var _this = _super.call(this, scene) || this;
  24590. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  24591. _this.name = rootUrl;
  24592. _this.url = rootUrl;
  24593. _this._noMipmap = noMipmap;
  24594. _this.hasAlpha = false;
  24595. if (!rootUrl && !files) {
  24596. return _this;
  24597. }
  24598. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  24599. if (!files) {
  24600. if (!extensions) {
  24601. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  24602. }
  24603. files = [];
  24604. for (var index = 0; index < extensions.length; index++) {
  24605. files.push(rootUrl + extensions[index]);
  24606. }
  24607. _this._extensions = extensions;
  24608. }
  24609. _this._files = files;
  24610. if (!_this._texture) {
  24611. if (!scene.useDelayedTextureLoading) {
  24612. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  24613. }
  24614. else {
  24615. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24616. }
  24617. }
  24618. else if (onLoad) {
  24619. if (_this._texture.isReady) {
  24620. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  24621. }
  24622. else {
  24623. _this._texture.onLoadedCallbacks.push(onLoad);
  24624. }
  24625. }
  24626. _this.isCube = true;
  24627. _this._textureMatrix = BABYLON.Matrix.Identity();
  24628. return _this;
  24629. }
  24630. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  24631. return new CubeTexture("", scene, null, noMipmap, files);
  24632. };
  24633. // Methods
  24634. CubeTexture.prototype.delayLoad = function () {
  24635. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24636. return;
  24637. }
  24638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24639. this._texture = this._getFromCache(this.url, this._noMipmap);
  24640. if (!this._texture) {
  24641. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  24642. }
  24643. };
  24644. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  24645. return this._textureMatrix;
  24646. };
  24647. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  24648. var texture = BABYLON.SerializationHelper.Parse(function () {
  24649. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  24650. }, parsedTexture, scene);
  24651. // Animations
  24652. if (parsedTexture.animations) {
  24653. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24654. var parsedAnimation = parsedTexture.animations[animationIndex];
  24655. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24656. }
  24657. }
  24658. return texture;
  24659. };
  24660. CubeTexture.prototype.clone = function () {
  24661. var _this = this;
  24662. return BABYLON.SerializationHelper.Clone(function () {
  24663. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  24664. }, this);
  24665. };
  24666. return CubeTexture;
  24667. }(BABYLON.BaseTexture));
  24668. BABYLON.CubeTexture = CubeTexture;
  24669. })(BABYLON || (BABYLON = {}));
  24670. //# sourceMappingURL=babylon.cubeTexture.js.map
  24671. var BABYLON;
  24672. (function (BABYLON) {
  24673. var RenderTargetTexture = (function (_super) {
  24674. __extends(RenderTargetTexture, _super);
  24675. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  24676. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  24677. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24678. if (isCube === void 0) { isCube = false; }
  24679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24680. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24681. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  24682. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24683. _this.isCube = isCube;
  24684. /**
  24685. * Use this list to define the list of mesh you want to render.
  24686. */
  24687. _this.renderList = new Array();
  24688. _this.renderParticles = true;
  24689. _this.renderSprites = false;
  24690. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  24691. // Events
  24692. /**
  24693. * An event triggered when the texture is unbind.
  24694. * @type {BABYLON.Observable}
  24695. */
  24696. _this.onAfterUnbindObservable = new BABYLON.Observable();
  24697. /**
  24698. * An event triggered before rendering the texture
  24699. * @type {BABYLON.Observable}
  24700. */
  24701. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24702. /**
  24703. * An event triggered after rendering the texture
  24704. * @type {BABYLON.Observable}
  24705. */
  24706. _this.onAfterRenderObservable = new BABYLON.Observable();
  24707. /**
  24708. * An event triggered after the texture clear
  24709. * @type {BABYLON.Observable}
  24710. */
  24711. _this.onClearObservable = new BABYLON.Observable();
  24712. _this._currentRefreshId = -1;
  24713. _this._refreshRate = 1;
  24714. _this.name = name;
  24715. _this.isRenderTarget = true;
  24716. _this._size = size;
  24717. _this._generateMipMaps = generateMipMaps;
  24718. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24719. _this._renderTargetOptions = {
  24720. generateMipMaps: generateMipMaps,
  24721. type: type,
  24722. samplingMode: samplingMode,
  24723. generateDepthBuffer: generateDepthBuffer,
  24724. generateStencilBuffer: generateStencilBuffer
  24725. };
  24726. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24727. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24728. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24729. }
  24730. if (isCube) {
  24731. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24732. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24733. _this._textureMatrix = BABYLON.Matrix.Identity();
  24734. }
  24735. else {
  24736. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24737. }
  24738. // Rendering groups
  24739. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24740. return _this;
  24741. }
  24742. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24743. get: function () {
  24744. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24750. get: function () {
  24751. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24757. get: function () {
  24758. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24764. set: function (callback) {
  24765. if (this._onAfterUnbindObserver) {
  24766. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24767. }
  24768. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24774. set: function (callback) {
  24775. if (this._onBeforeRenderObserver) {
  24776. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24777. }
  24778. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24784. set: function (callback) {
  24785. if (this._onAfterRenderObserver) {
  24786. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24787. }
  24788. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24789. },
  24790. enumerable: true,
  24791. configurable: true
  24792. });
  24793. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24794. set: function (callback) {
  24795. if (this._onClearObserver) {
  24796. this.onClearObservable.remove(this._onClearObserver);
  24797. }
  24798. this._onClearObserver = this.onClearObservable.add(callback);
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24804. this._currentRefreshId = -1;
  24805. };
  24806. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24807. get: function () {
  24808. return this._refreshRate;
  24809. },
  24810. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24811. set: function (value) {
  24812. this._refreshRate = value;
  24813. this.resetRefreshCounter();
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. RenderTargetTexture.prototype._shouldRender = function () {
  24819. if (this._currentRefreshId === -1) {
  24820. this._currentRefreshId = 1;
  24821. return true;
  24822. }
  24823. if (this.refreshRate === this._currentRefreshId) {
  24824. this._currentRefreshId = 1;
  24825. return true;
  24826. }
  24827. this._currentRefreshId++;
  24828. return false;
  24829. };
  24830. RenderTargetTexture.prototype.isReady = function () {
  24831. if (!this.getScene().renderTargetsEnabled) {
  24832. return false;
  24833. }
  24834. return _super.prototype.isReady.call(this);
  24835. };
  24836. RenderTargetTexture.prototype.getRenderSize = function () {
  24837. return this._size;
  24838. };
  24839. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24840. get: function () {
  24841. return true;
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. RenderTargetTexture.prototype.scale = function (ratio) {
  24847. var newSize = this._size * ratio;
  24848. this.resize(newSize);
  24849. };
  24850. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24851. if (this.isCube) {
  24852. return this._textureMatrix;
  24853. }
  24854. return _super.prototype.getReflectionTextureMatrix.call(this);
  24855. };
  24856. RenderTargetTexture.prototype.resize = function (size) {
  24857. this.releaseInternalTexture();
  24858. if (this.isCube) {
  24859. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24860. }
  24861. else {
  24862. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24863. }
  24864. };
  24865. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24866. var scene = this.getScene();
  24867. var engine = scene.getEngine();
  24868. if (this.useCameraPostProcesses !== undefined) {
  24869. useCameraPostProcess = this.useCameraPostProcesses;
  24870. }
  24871. if (this._waitingRenderList) {
  24872. this.renderList = [];
  24873. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24874. var id = this._waitingRenderList[index];
  24875. this.renderList.push(scene.getMeshByID(id));
  24876. }
  24877. delete this._waitingRenderList;
  24878. }
  24879. // Is predicate defined?
  24880. if (this.renderListPredicate) {
  24881. this.renderList.splice(0); // Clear previous renderList
  24882. var sceneMeshes = this.getScene().meshes;
  24883. for (var index = 0; index < sceneMeshes.length; index++) {
  24884. var mesh = sceneMeshes[index];
  24885. if (this.renderListPredicate(mesh)) {
  24886. this.renderList.push(mesh);
  24887. }
  24888. }
  24889. }
  24890. if (this.renderList && this.renderList.length === 0) {
  24891. return;
  24892. }
  24893. // Set custom projection.
  24894. // Needs to be before binding to prevent changing the aspect ratio.
  24895. if (this.activeCamera) {
  24896. engine.setViewport(this.activeCamera.viewport);
  24897. if (this.activeCamera !== scene.activeCamera) {
  24898. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24899. }
  24900. }
  24901. else {
  24902. engine.setViewport(scene.activeCamera.viewport);
  24903. }
  24904. // Prepare renderingManager
  24905. this._renderingManager.reset();
  24906. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24907. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24908. var sceneRenderId = scene.getRenderId();
  24909. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24910. var mesh = currentRenderList[meshIndex];
  24911. if (mesh) {
  24912. if (!mesh.isReady()) {
  24913. // Reset _currentRefreshId
  24914. this.resetRefreshCounter();
  24915. continue;
  24916. }
  24917. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24918. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24919. mesh._activate(sceneRenderId);
  24920. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24921. var subMesh = mesh.subMeshes[subIndex];
  24922. scene._activeIndices.addCount(subMesh.indexCount, false);
  24923. this._renderingManager.dispatch(subMesh);
  24924. }
  24925. }
  24926. }
  24927. }
  24928. if (this.isCube) {
  24929. for (var face = 0; face < 6; face++) {
  24930. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24931. scene.incrementRenderId();
  24932. scene.resetCachedMaterial();
  24933. }
  24934. }
  24935. else {
  24936. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24937. }
  24938. this.onAfterUnbindObservable.notifyObservers(this);
  24939. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24940. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24941. }
  24942. engine.setViewport(scene.activeCamera.viewport);
  24943. scene.resetCachedMaterial();
  24944. };
  24945. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24946. var scene = this.getScene();
  24947. var engine = scene.getEngine();
  24948. // Bind
  24949. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24950. if (this.isCube) {
  24951. engine.bindFramebuffer(this._texture, faceIndex);
  24952. }
  24953. else {
  24954. engine.bindFramebuffer(this._texture);
  24955. }
  24956. }
  24957. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24958. // Clear
  24959. if (this.onClearObservable.hasObservers()) {
  24960. this.onClearObservable.notifyObservers(engine);
  24961. }
  24962. else {
  24963. engine.clear(scene.clearColor, true, true, true);
  24964. }
  24965. if (!this._doNotChangeAspectRatio) {
  24966. scene.updateTransformMatrix(true);
  24967. }
  24968. // Render
  24969. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24970. if (useCameraPostProcess) {
  24971. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24972. }
  24973. if (!this._doNotChangeAspectRatio) {
  24974. scene.updateTransformMatrix(true);
  24975. }
  24976. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24977. // Dump ?
  24978. if (dumpForDebug) {
  24979. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24980. }
  24981. // Unbind
  24982. if (!this.isCube || faceIndex === 5) {
  24983. if (this.isCube) {
  24984. if (faceIndex === 5) {
  24985. engine.generateMipMapsForCubemap(this._texture);
  24986. }
  24987. }
  24988. engine.unBindFramebuffer(this._texture, this.isCube);
  24989. }
  24990. };
  24991. /**
  24992. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24993. * This allowed control for front to back rendering or reversly depending of the special needs.
  24994. *
  24995. * @param renderingGroupId The rendering group id corresponding to its index
  24996. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24997. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24998. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24999. */
  25000. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25001. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25002. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25003. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25004. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25005. };
  25006. /**
  25007. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25008. *
  25009. * @param renderingGroupId The rendering group id corresponding to its index
  25010. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25011. */
  25012. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  25013. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  25014. };
  25015. RenderTargetTexture.prototype.clone = function () {
  25016. var textureSize = this.getSize();
  25017. 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);
  25018. // Base texture
  25019. newTexture.hasAlpha = this.hasAlpha;
  25020. newTexture.level = this.level;
  25021. // RenderTarget Texture
  25022. newTexture.coordinatesMode = this.coordinatesMode;
  25023. newTexture.renderList = this.renderList.slice(0);
  25024. return newTexture;
  25025. };
  25026. RenderTargetTexture.prototype.serialize = function () {
  25027. if (!this.name) {
  25028. return null;
  25029. }
  25030. var serializationObject = _super.prototype.serialize.call(this);
  25031. serializationObject.renderTargetSize = this.getRenderSize();
  25032. serializationObject.renderList = [];
  25033. for (var index = 0; index < this.renderList.length; index++) {
  25034. serializationObject.renderList.push(this.renderList[index].id);
  25035. }
  25036. return serializationObject;
  25037. };
  25038. return RenderTargetTexture;
  25039. }(BABYLON.Texture));
  25040. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  25041. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  25042. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  25043. BABYLON.RenderTargetTexture = RenderTargetTexture;
  25044. })(BABYLON || (BABYLON = {}));
  25045. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  25046. var BABYLON;
  25047. (function (BABYLON) {
  25048. var ProceduralTexture = (function (_super) {
  25049. __extends(ProceduralTexture, _super);
  25050. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  25051. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25052. if (isCube === void 0) { isCube = false; }
  25053. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25054. _this.isCube = isCube;
  25055. _this.isEnabled = true;
  25056. _this._currentRefreshId = -1;
  25057. _this._refreshRate = 1;
  25058. _this._vertexBuffers = {};
  25059. _this._uniforms = new Array();
  25060. _this._samplers = new Array();
  25061. _this._textures = new Array();
  25062. _this._floats = new Array();
  25063. _this._floatsArrays = {};
  25064. _this._colors3 = new Array();
  25065. _this._colors4 = new Array();
  25066. _this._vectors2 = new Array();
  25067. _this._vectors3 = new Array();
  25068. _this._matrices = new Array();
  25069. _this._fallbackTextureUsed = false;
  25070. scene._proceduralTextures.push(_this);
  25071. _this.name = name;
  25072. _this.isRenderTarget = true;
  25073. _this._size = size;
  25074. _this._generateMipMaps = generateMipMaps;
  25075. _this.setFragment(fragment);
  25076. _this._fallbackTexture = fallbackTexture;
  25077. var engine = scene.getEngine();
  25078. if (isCube) {
  25079. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  25080. _this.setFloat("face", 0);
  25081. }
  25082. else {
  25083. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  25084. }
  25085. // VBO
  25086. var vertices = [];
  25087. vertices.push(1, 1);
  25088. vertices.push(-1, 1);
  25089. vertices.push(-1, -1);
  25090. vertices.push(1, -1);
  25091. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25092. // Indices
  25093. var indices = [];
  25094. indices.push(0);
  25095. indices.push(1);
  25096. indices.push(2);
  25097. indices.push(0);
  25098. indices.push(2);
  25099. indices.push(3);
  25100. _this._indexBuffer = engine.createIndexBuffer(indices);
  25101. return _this;
  25102. }
  25103. ProceduralTexture.prototype.reset = function () {
  25104. if (this._effect === undefined) {
  25105. return;
  25106. }
  25107. var engine = this.getScene().getEngine();
  25108. engine._releaseEffect(this._effect);
  25109. };
  25110. ProceduralTexture.prototype.isReady = function () {
  25111. var _this = this;
  25112. var engine = this.getScene().getEngine();
  25113. var shaders;
  25114. if (!this._fragment) {
  25115. return false;
  25116. }
  25117. if (this._fallbackTextureUsed) {
  25118. return true;
  25119. }
  25120. if (this._fragment.fragmentElement !== undefined) {
  25121. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  25122. }
  25123. else {
  25124. shaders = { vertex: "procedural", fragment: this._fragment };
  25125. }
  25126. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  25127. _this.releaseInternalTexture();
  25128. if (_this._fallbackTexture) {
  25129. _this._texture = _this._fallbackTexture._texture;
  25130. _this._texture.references++;
  25131. }
  25132. _this._fallbackTextureUsed = true;
  25133. });
  25134. return this._effect.isReady();
  25135. };
  25136. ProceduralTexture.prototype.resetRefreshCounter = function () {
  25137. this._currentRefreshId = -1;
  25138. };
  25139. ProceduralTexture.prototype.setFragment = function (fragment) {
  25140. this._fragment = fragment;
  25141. };
  25142. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  25143. get: function () {
  25144. return this._refreshRate;
  25145. },
  25146. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  25147. set: function (value) {
  25148. this._refreshRate = value;
  25149. this.resetRefreshCounter();
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. ProceduralTexture.prototype._shouldRender = function () {
  25155. if (!this.isEnabled || !this.isReady() || !this._texture) {
  25156. return false;
  25157. }
  25158. if (this._fallbackTextureUsed) {
  25159. return false;
  25160. }
  25161. if (this._currentRefreshId === -1) {
  25162. this._currentRefreshId = 1;
  25163. return true;
  25164. }
  25165. if (this.refreshRate === this._currentRefreshId) {
  25166. this._currentRefreshId = 1;
  25167. return true;
  25168. }
  25169. this._currentRefreshId++;
  25170. return false;
  25171. };
  25172. ProceduralTexture.prototype.getRenderSize = function () {
  25173. return this._size;
  25174. };
  25175. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  25176. if (this._fallbackTextureUsed) {
  25177. return;
  25178. }
  25179. this.releaseInternalTexture();
  25180. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  25181. };
  25182. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  25183. if (this._uniforms.indexOf(uniformName) === -1) {
  25184. this._uniforms.push(uniformName);
  25185. }
  25186. };
  25187. ProceduralTexture.prototype.setTexture = function (name, texture) {
  25188. if (this._samplers.indexOf(name) === -1) {
  25189. this._samplers.push(name);
  25190. }
  25191. this._textures[name] = texture;
  25192. return this;
  25193. };
  25194. ProceduralTexture.prototype.setFloat = function (name, value) {
  25195. this._checkUniform(name);
  25196. this._floats[name] = value;
  25197. return this;
  25198. };
  25199. ProceduralTexture.prototype.setFloats = function (name, value) {
  25200. this._checkUniform(name);
  25201. this._floatsArrays[name] = value;
  25202. return this;
  25203. };
  25204. ProceduralTexture.prototype.setColor3 = function (name, value) {
  25205. this._checkUniform(name);
  25206. this._colors3[name] = value;
  25207. return this;
  25208. };
  25209. ProceduralTexture.prototype.setColor4 = function (name, value) {
  25210. this._checkUniform(name);
  25211. this._colors4[name] = value;
  25212. return this;
  25213. };
  25214. ProceduralTexture.prototype.setVector2 = function (name, value) {
  25215. this._checkUniform(name);
  25216. this._vectors2[name] = value;
  25217. return this;
  25218. };
  25219. ProceduralTexture.prototype.setVector3 = function (name, value) {
  25220. this._checkUniform(name);
  25221. this._vectors3[name] = value;
  25222. return this;
  25223. };
  25224. ProceduralTexture.prototype.setMatrix = function (name, value) {
  25225. this._checkUniform(name);
  25226. this._matrices[name] = value;
  25227. return this;
  25228. };
  25229. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25230. var scene = this.getScene();
  25231. var engine = scene.getEngine();
  25232. // Render
  25233. engine.enableEffect(this._effect);
  25234. engine.setState(false);
  25235. // Texture
  25236. for (var name in this._textures) {
  25237. this._effect.setTexture(name, this._textures[name]);
  25238. }
  25239. // Float
  25240. for (name in this._floats) {
  25241. this._effect.setFloat(name, this._floats[name]);
  25242. }
  25243. // Floats
  25244. for (name in this._floatsArrays) {
  25245. this._effect.setArray(name, this._floatsArrays[name]);
  25246. }
  25247. // Color3
  25248. for (name in this._colors3) {
  25249. this._effect.setColor3(name, this._colors3[name]);
  25250. }
  25251. // Color4
  25252. for (name in this._colors4) {
  25253. var color = this._colors4[name];
  25254. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25255. }
  25256. // Vector2
  25257. for (name in this._vectors2) {
  25258. this._effect.setVector2(name, this._vectors2[name]);
  25259. }
  25260. // Vector3
  25261. for (name in this._vectors3) {
  25262. this._effect.setVector3(name, this._vectors3[name]);
  25263. }
  25264. // Matrix
  25265. for (name in this._matrices) {
  25266. this._effect.setMatrix(name, this._matrices[name]);
  25267. }
  25268. if (this.isCube) {
  25269. for (var face = 0; face < 6; face++) {
  25270. engine.bindFramebuffer(this._texture, face);
  25271. // VBOs
  25272. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25273. this._effect.setFloat("face", face);
  25274. // Clear
  25275. engine.clear(scene.clearColor, true, true, true);
  25276. // Draw order
  25277. engine.draw(true, 0, 6);
  25278. // Mipmaps
  25279. if (face === 5) {
  25280. engine.generateMipMapsForCubemap(this._texture);
  25281. }
  25282. }
  25283. }
  25284. else {
  25285. engine.bindFramebuffer(this._texture);
  25286. // VBOs
  25287. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25288. // Clear
  25289. engine.clear(scene.clearColor, true, true, true);
  25290. // Draw order
  25291. engine.draw(true, 0, 6);
  25292. }
  25293. // Unbind
  25294. engine.unBindFramebuffer(this._texture, this.isCube);
  25295. if (this.onGenerated) {
  25296. this.onGenerated();
  25297. }
  25298. };
  25299. ProceduralTexture.prototype.clone = function () {
  25300. var textureSize = this.getSize();
  25301. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  25302. // Base texture
  25303. newTexture.hasAlpha = this.hasAlpha;
  25304. newTexture.level = this.level;
  25305. // RenderTarget Texture
  25306. newTexture.coordinatesMode = this.coordinatesMode;
  25307. return newTexture;
  25308. };
  25309. ProceduralTexture.prototype.dispose = function () {
  25310. var index = this.getScene()._proceduralTextures.indexOf(this);
  25311. if (index >= 0) {
  25312. this.getScene()._proceduralTextures.splice(index, 1);
  25313. }
  25314. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25315. if (vertexBuffer) {
  25316. vertexBuffer.dispose();
  25317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25318. }
  25319. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  25320. this._indexBuffer = null;
  25321. }
  25322. _super.prototype.dispose.call(this);
  25323. };
  25324. return ProceduralTexture;
  25325. }(BABYLON.Texture));
  25326. BABYLON.ProceduralTexture = ProceduralTexture;
  25327. })(BABYLON || (BABYLON = {}));
  25328. //# sourceMappingURL=babylon.proceduralTexture.js.map
  25329. var BABYLON;
  25330. (function (BABYLON) {
  25331. var MirrorTexture = (function (_super) {
  25332. __extends(MirrorTexture, _super);
  25333. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  25334. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  25336. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  25337. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  25338. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  25339. _this._transformMatrix = BABYLON.Matrix.Zero();
  25340. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  25341. _this.onBeforeRenderObservable.add(function () {
  25342. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  25343. _this._savedViewMatrix = scene.getViewMatrix();
  25344. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  25345. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  25346. scene.clipPlane = _this.mirrorPlane;
  25347. scene.getEngine().cullBackFaces = false;
  25348. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  25349. });
  25350. _this.onAfterRenderObservable.add(function () {
  25351. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  25352. scene.getEngine().cullBackFaces = true;
  25353. scene._mirroredCameraPosition = null;
  25354. delete scene.clipPlane;
  25355. });
  25356. return _this;
  25357. }
  25358. MirrorTexture.prototype.clone = function () {
  25359. var textureSize = this.getSize();
  25360. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  25361. // Base texture
  25362. newTexture.hasAlpha = this.hasAlpha;
  25363. newTexture.level = this.level;
  25364. // Mirror Texture
  25365. newTexture.mirrorPlane = this.mirrorPlane.clone();
  25366. newTexture.renderList = this.renderList.slice(0);
  25367. return newTexture;
  25368. };
  25369. MirrorTexture.prototype.serialize = function () {
  25370. if (!this.name) {
  25371. return null;
  25372. }
  25373. var serializationObject = _super.prototype.serialize.call(this);
  25374. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  25375. return serializationObject;
  25376. };
  25377. return MirrorTexture;
  25378. }(BABYLON.RenderTargetTexture));
  25379. BABYLON.MirrorTexture = MirrorTexture;
  25380. })(BABYLON || (BABYLON = {}));
  25381. //# sourceMappingURL=babylon.mirrorTexture.js.map
  25382. var BABYLON;
  25383. (function (BABYLON) {
  25384. /**
  25385. * Creates a refraction texture used by refraction channel of the standard material.
  25386. * @param name the texture name
  25387. * @param size size of the underlying texture
  25388. * @param scene root scene
  25389. */
  25390. var RefractionTexture = (function (_super) {
  25391. __extends(RefractionTexture, _super);
  25392. function RefractionTexture(name, size, scene, generateMipMaps) {
  25393. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  25394. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  25395. _this.depth = 2.0;
  25396. _this.onBeforeRenderObservable.add(function () {
  25397. scene.clipPlane = _this.refractionPlane;
  25398. });
  25399. _this.onAfterRenderObservable.add(function () {
  25400. delete scene.clipPlane;
  25401. });
  25402. return _this;
  25403. }
  25404. RefractionTexture.prototype.clone = function () {
  25405. var textureSize = this.getSize();
  25406. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  25407. // Base texture
  25408. newTexture.hasAlpha = this.hasAlpha;
  25409. newTexture.level = this.level;
  25410. // Refraction Texture
  25411. newTexture.refractionPlane = this.refractionPlane.clone();
  25412. newTexture.renderList = this.renderList.slice(0);
  25413. newTexture.depth = this.depth;
  25414. return newTexture;
  25415. };
  25416. RefractionTexture.prototype.serialize = function () {
  25417. if (!this.name) {
  25418. return null;
  25419. }
  25420. var serializationObject = _super.prototype.serialize.call(this);
  25421. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  25422. serializationObject.depth = this.depth;
  25423. return serializationObject;
  25424. };
  25425. return RefractionTexture;
  25426. }(BABYLON.RenderTargetTexture));
  25427. BABYLON.RefractionTexture = RefractionTexture;
  25428. })(BABYLON || (BABYLON = {}));
  25429. //# sourceMappingURL=babylon.refractionTexture.js.map
  25430. var BABYLON;
  25431. (function (BABYLON) {
  25432. var DynamicTexture = (function (_super) {
  25433. __extends(DynamicTexture, _super);
  25434. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  25435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25436. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25437. _this.name = name;
  25438. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25439. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25440. _this._generateMipMaps = generateMipMaps;
  25441. if (options.getContext) {
  25442. _this._canvas = options;
  25443. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25444. }
  25445. else {
  25446. _this._canvas = document.createElement("canvas");
  25447. if (options.width) {
  25448. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25449. }
  25450. else {
  25451. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  25452. }
  25453. }
  25454. var textureSize = _this.getSize();
  25455. _this._canvas.width = textureSize.width;
  25456. _this._canvas.height = textureSize.height;
  25457. _this._context = _this._canvas.getContext("2d");
  25458. return _this;
  25459. }
  25460. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  25461. get: function () {
  25462. return true;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. DynamicTexture.prototype.scale = function (ratio) {
  25468. var textureSize = this.getSize();
  25469. textureSize.width *= ratio;
  25470. textureSize.height *= ratio;
  25471. this._canvas.width = textureSize.width;
  25472. this._canvas.height = textureSize.height;
  25473. this.releaseInternalTexture();
  25474. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  25475. };
  25476. DynamicTexture.prototype.getContext = function () {
  25477. return this._context;
  25478. };
  25479. DynamicTexture.prototype.clear = function () {
  25480. var size = this.getSize();
  25481. this._context.fillRect(0, 0, size.width, size.height);
  25482. };
  25483. DynamicTexture.prototype.update = function (invertY) {
  25484. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  25485. };
  25486. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  25487. if (update === void 0) { update = true; }
  25488. var size = this.getSize();
  25489. if (clearColor) {
  25490. this._context.fillStyle = clearColor;
  25491. this._context.fillRect(0, 0, size.width, size.height);
  25492. }
  25493. this._context.font = font;
  25494. if (x === null) {
  25495. var textSize = this._context.measureText(text);
  25496. x = (size.width - textSize.width) / 2;
  25497. }
  25498. this._context.fillStyle = color;
  25499. this._context.fillText(text, x, y);
  25500. if (update) {
  25501. this.update(invertY);
  25502. }
  25503. };
  25504. DynamicTexture.prototype.clone = function () {
  25505. var textureSize = this.getSize();
  25506. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  25507. // Base texture
  25508. newTexture.hasAlpha = this.hasAlpha;
  25509. newTexture.level = this.level;
  25510. // Dynamic Texture
  25511. newTexture.wrapU = this.wrapU;
  25512. newTexture.wrapV = this.wrapV;
  25513. return newTexture;
  25514. };
  25515. return DynamicTexture;
  25516. }(BABYLON.Texture));
  25517. BABYLON.DynamicTexture = DynamicTexture;
  25518. })(BABYLON || (BABYLON = {}));
  25519. //# sourceMappingURL=babylon.dynamicTexture.js.map
  25520. var BABYLON;
  25521. (function (BABYLON) {
  25522. var VideoTexture = (function (_super) {
  25523. __extends(VideoTexture, _super);
  25524. /**
  25525. * Creates a video texture.
  25526. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  25527. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  25528. * @param {BABYLON.Scene} scene is obviously the current scene.
  25529. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  25530. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  25531. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  25532. */
  25533. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  25534. if (generateMipMaps === void 0) { generateMipMaps = false; }
  25535. if (invertY === void 0) { invertY = false; }
  25536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25537. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  25538. _this._autoLaunch = true;
  25539. var urls;
  25540. _this.name = name;
  25541. if (urlsOrVideo instanceof HTMLVideoElement) {
  25542. _this.video = urlsOrVideo;
  25543. }
  25544. else {
  25545. urls = urlsOrVideo;
  25546. _this.video = document.createElement("video");
  25547. _this.video.autoplay = false;
  25548. _this.video.loop = true;
  25549. }
  25550. _this._generateMipMaps = generateMipMaps;
  25551. _this._samplingMode = samplingMode;
  25552. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  25553. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25554. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25555. }
  25556. else {
  25557. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25558. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25559. _this._generateMipMaps = false;
  25560. }
  25561. if (urls) {
  25562. _this.video.addEventListener("canplaythrough", function () {
  25563. _this._createTexture();
  25564. });
  25565. urls.forEach(function (url) {
  25566. var source = document.createElement("source");
  25567. source.src = url;
  25568. _this.video.appendChild(source);
  25569. });
  25570. }
  25571. else {
  25572. _this._createTexture();
  25573. }
  25574. _this._lastUpdate = BABYLON.Tools.Now;
  25575. return _this;
  25576. }
  25577. VideoTexture.prototype._createTexture = function () {
  25578. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  25579. this._texture.isReady = true;
  25580. };
  25581. VideoTexture.prototype.update = function () {
  25582. if (this._autoLaunch) {
  25583. this._autoLaunch = false;
  25584. this.video.play();
  25585. }
  25586. var now = BABYLON.Tools.Now;
  25587. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  25588. return false;
  25589. }
  25590. this._lastUpdate = now;
  25591. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  25592. return true;
  25593. };
  25594. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  25595. var video = document.createElement("video");
  25596. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  25597. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  25598. if (navigator.getUserMedia) {
  25599. navigator.getUserMedia({
  25600. video: {
  25601. width: {
  25602. min: (constraints && constraints.minWidth) || 256,
  25603. max: (constraints && constraints.maxWidth) || 640
  25604. },
  25605. height: {
  25606. min: (constraints && constraints.minHeight) || 256,
  25607. max: (constraints && constraints.maxHeight) || 480
  25608. }
  25609. }
  25610. }, function (stream) {
  25611. if (video.mozSrcObject !== undefined) {
  25612. video.mozSrcObject = stream;
  25613. }
  25614. else {
  25615. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  25616. }
  25617. video.play();
  25618. if (onReady) {
  25619. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  25620. }
  25621. }, function (e) {
  25622. BABYLON.Tools.Error(e.name);
  25623. });
  25624. }
  25625. };
  25626. return VideoTexture;
  25627. }(BABYLON.Texture));
  25628. BABYLON.VideoTexture = VideoTexture;
  25629. })(BABYLON || (BABYLON = {}));
  25630. //# sourceMappingURL=babylon.videoTexture.js.map
  25631. var BABYLON;
  25632. (function (BABYLON) {
  25633. var CustomProceduralTexture = (function (_super) {
  25634. __extends(CustomProceduralTexture, _super);
  25635. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  25636. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  25637. _this._animate = true;
  25638. _this._time = 0;
  25639. _this._texturePath = texturePath;
  25640. //Try to load json
  25641. _this.loadJson(texturePath);
  25642. _this.refreshRate = 1;
  25643. return _this;
  25644. }
  25645. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  25646. var _this = this;
  25647. var that = this;
  25648. function noConfigFile() {
  25649. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  25650. try {
  25651. that.setFragment(that._texturePath);
  25652. }
  25653. catch (ex) {
  25654. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  25655. }
  25656. }
  25657. var configFileUrl = jsonUrl + "/config.json";
  25658. var xhr = new XMLHttpRequest();
  25659. xhr.open("GET", configFileUrl, true);
  25660. xhr.addEventListener("load", function () {
  25661. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  25662. try {
  25663. _this._config = JSON.parse(xhr.response);
  25664. _this.updateShaderUniforms();
  25665. _this.updateTextures();
  25666. _this.setFragment(_this._texturePath + "/custom");
  25667. _this._animate = _this._config.animate;
  25668. _this.refreshRate = _this._config.refreshrate;
  25669. }
  25670. catch (ex) {
  25671. noConfigFile();
  25672. }
  25673. }
  25674. else {
  25675. noConfigFile();
  25676. }
  25677. }, false);
  25678. xhr.addEventListener("error", function () {
  25679. noConfigFile();
  25680. }, false);
  25681. try {
  25682. xhr.send();
  25683. }
  25684. catch (ex) {
  25685. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  25686. }
  25687. };
  25688. CustomProceduralTexture.prototype.isReady = function () {
  25689. if (!_super.prototype.isReady.call(this)) {
  25690. return false;
  25691. }
  25692. for (var name in this._textures) {
  25693. var texture = this._textures[name];
  25694. if (!texture.isReady()) {
  25695. return false;
  25696. }
  25697. }
  25698. return true;
  25699. };
  25700. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25701. if (this._animate) {
  25702. this._time += this.getScene().getAnimationRatio() * 0.03;
  25703. this.updateShaderUniforms();
  25704. }
  25705. _super.prototype.render.call(this, useCameraPostProcess);
  25706. };
  25707. CustomProceduralTexture.prototype.updateTextures = function () {
  25708. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  25709. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  25710. }
  25711. };
  25712. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  25713. if (this._config) {
  25714. for (var j = 0; j < this._config.uniforms.length; j++) {
  25715. var uniform = this._config.uniforms[j];
  25716. switch (uniform.type) {
  25717. case "float":
  25718. this.setFloat(uniform.name, uniform.value);
  25719. break;
  25720. case "color3":
  25721. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25722. break;
  25723. case "color4":
  25724. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25725. break;
  25726. case "vector2":
  25727. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25728. break;
  25729. case "vector3":
  25730. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25731. break;
  25732. }
  25733. }
  25734. }
  25735. this.setFloat("time", this._time);
  25736. };
  25737. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25738. get: function () {
  25739. return this._animate;
  25740. },
  25741. set: function (value) {
  25742. this._animate = value;
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. return CustomProceduralTexture;
  25748. }(BABYLON.ProceduralTexture));
  25749. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25750. })(BABYLON || (BABYLON = {}));
  25751. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25752. var BABYLON;
  25753. (function (BABYLON) {
  25754. var EffectFallbacks = (function () {
  25755. function EffectFallbacks() {
  25756. this._defines = {};
  25757. this._currentRank = 32;
  25758. this._maxRank = -1;
  25759. }
  25760. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25761. if (!this._defines[rank]) {
  25762. if (rank < this._currentRank) {
  25763. this._currentRank = rank;
  25764. }
  25765. if (rank > this._maxRank) {
  25766. this._maxRank = rank;
  25767. }
  25768. this._defines[rank] = new Array();
  25769. }
  25770. this._defines[rank].push(define);
  25771. };
  25772. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25773. this._meshRank = rank;
  25774. this._mesh = mesh;
  25775. if (rank > this._maxRank) {
  25776. this._maxRank = rank;
  25777. }
  25778. };
  25779. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25780. get: function () {
  25781. return this._currentRank <= this._maxRank;
  25782. },
  25783. enumerable: true,
  25784. configurable: true
  25785. });
  25786. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25787. var currentFallbacks = this._defines[this._currentRank];
  25788. for (var index = 0; index < currentFallbacks.length; index++) {
  25789. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25790. }
  25791. if (this._mesh && this._currentRank === this._meshRank) {
  25792. this._mesh.computeBonesUsingShaders = false;
  25793. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25794. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25795. }
  25796. this._currentRank++;
  25797. return currentDefines;
  25798. };
  25799. return EffectFallbacks;
  25800. }());
  25801. BABYLON.EffectFallbacks = EffectFallbacks;
  25802. var Effect = (function () {
  25803. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25804. var _this = this;
  25805. this.uniqueId = 0;
  25806. this._isReady = false;
  25807. this._compilationError = "";
  25808. this._valueCache = {};
  25809. this._engine = engine;
  25810. this.name = baseName;
  25811. this.defines = defines;
  25812. this._uniformsNames = uniformsNames.concat(samplers);
  25813. this._samplers = samplers;
  25814. this._attributesNames = attributesNames;
  25815. this.onError = onError;
  25816. this.onCompiled = onCompiled;
  25817. this._indexParameters = indexParameters;
  25818. this.uniqueId = Effect._uniqueIdSeed++;
  25819. var vertexSource;
  25820. var fragmentSource;
  25821. if (baseName.vertexElement) {
  25822. vertexSource = document.getElementById(baseName.vertexElement);
  25823. if (!vertexSource) {
  25824. vertexSource = baseName.vertexElement;
  25825. }
  25826. }
  25827. else {
  25828. vertexSource = baseName.vertex || baseName;
  25829. }
  25830. if (baseName.fragmentElement) {
  25831. fragmentSource = document.getElementById(baseName.fragmentElement);
  25832. if (!fragmentSource) {
  25833. fragmentSource = baseName.fragmentElement;
  25834. }
  25835. }
  25836. else {
  25837. fragmentSource = baseName.fragment || baseName;
  25838. }
  25839. this._loadVertexShader(vertexSource, function (vertexCode) {
  25840. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25841. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25842. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25843. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25844. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25845. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25846. });
  25847. });
  25848. });
  25849. });
  25850. });
  25851. });
  25852. }
  25853. Object.defineProperty(Effect.prototype, "key", {
  25854. get: function () {
  25855. return this._key;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. // Properties
  25861. Effect.prototype.isReady = function () {
  25862. return this._isReady;
  25863. };
  25864. Effect.prototype.getProgram = function () {
  25865. return this._program;
  25866. };
  25867. Effect.prototype.getAttributesNames = function () {
  25868. return this._attributesNames;
  25869. };
  25870. Effect.prototype.getAttributeLocation = function (index) {
  25871. return this._attributes[index];
  25872. };
  25873. Effect.prototype.getAttributeLocationByName = function (name) {
  25874. var index = this._attributesNames.indexOf(name);
  25875. return this._attributes[index];
  25876. };
  25877. Effect.prototype.getAttributesCount = function () {
  25878. return this._attributes.length;
  25879. };
  25880. Effect.prototype.getUniformIndex = function (uniformName) {
  25881. return this._uniformsNames.indexOf(uniformName);
  25882. };
  25883. Effect.prototype.getUniform = function (uniformName) {
  25884. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25885. };
  25886. Effect.prototype.getSamplers = function () {
  25887. return this._samplers;
  25888. };
  25889. Effect.prototype.getCompilationError = function () {
  25890. return this._compilationError;
  25891. };
  25892. Effect.prototype.getVertexShaderSource = function () {
  25893. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25894. };
  25895. Effect.prototype.getFragmentShaderSource = function () {
  25896. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25897. };
  25898. // Methods
  25899. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25900. // DOM element ?
  25901. if (vertex instanceof HTMLElement) {
  25902. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25903. callback(vertexCode);
  25904. return;
  25905. }
  25906. // Base64 encoded ?
  25907. if (vertex.substr(0, 7) === "base64:") {
  25908. var vertexBinary = window.atob(vertex.substr(7));
  25909. callback(vertexBinary);
  25910. return;
  25911. }
  25912. // Is in local store ?
  25913. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25914. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25915. return;
  25916. }
  25917. var vertexShaderUrl;
  25918. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25919. vertexShaderUrl = vertex;
  25920. }
  25921. else {
  25922. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25923. }
  25924. // Vertex shader
  25925. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25926. };
  25927. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25928. // DOM element ?
  25929. if (fragment instanceof HTMLElement) {
  25930. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25931. callback(fragmentCode);
  25932. return;
  25933. }
  25934. // Base64 encoded ?
  25935. if (fragment.substr(0, 7) === "base64:") {
  25936. var fragmentBinary = window.atob(fragment.substr(7));
  25937. callback(fragmentBinary);
  25938. return;
  25939. }
  25940. // Is in local store ?
  25941. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25942. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25943. return;
  25944. }
  25945. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25946. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25947. return;
  25948. }
  25949. var fragmentShaderUrl;
  25950. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25951. fragmentShaderUrl = fragment;
  25952. }
  25953. else {
  25954. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25955. }
  25956. // Fragment shader
  25957. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25958. };
  25959. Effect.prototype._dumpShadersName = function () {
  25960. if (this.name.vertexElement) {
  25961. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25962. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25963. }
  25964. else if (this.name.vertex) {
  25965. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25966. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25967. }
  25968. else {
  25969. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25970. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25971. }
  25972. };
  25973. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25974. var preparedSourceCode = this._processPrecision(sourceCode);
  25975. if (this._engine.webGLVersion == 1) {
  25976. callback(preparedSourceCode);
  25977. return;
  25978. }
  25979. // Already converted
  25980. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25981. callback(preparedSourceCode);
  25982. return;
  25983. }
  25984. // Remove extensions
  25985. // #extension GL_OES_standard_derivatives : enable
  25986. // #extension GL_EXT_shader_texture_lod : enable
  25987. // #extension GL_EXT_frag_depth : enable
  25988. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  25989. var result = preparedSourceCode.replace(regex, "");
  25990. // Migrate to GLSL v300
  25991. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  25992. result = result.replace(/attribute[ \t]/g, "in ");
  25993. result = result.replace(/[ \t]attribute/g, " in");
  25994. if (isFragment) {
  25995. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  25996. result = result.replace(/texture2D\(/g, "texture(");
  25997. result = result.replace(/textureCube\(/g, "texture(");
  25998. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25999. result = result.replace(/gl_FragColor/g, "glFragColor");
  26000. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  26001. }
  26002. callback(result);
  26003. };
  26004. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26005. var _this = this;
  26006. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26007. var match = regex.exec(sourceCode);
  26008. var returnValue = new String(sourceCode);
  26009. while (match != null) {
  26010. var includeFile = match[1];
  26011. if (Effect.IncludesShadersStore[includeFile]) {
  26012. // Substitution
  26013. var includeContent = Effect.IncludesShadersStore[includeFile];
  26014. if (match[2]) {
  26015. var splits = match[3].split(",");
  26016. for (var index = 0; index < splits.length; index += 2) {
  26017. var source = new RegExp(splits[index], "g");
  26018. var dest = splits[index + 1];
  26019. includeContent = includeContent.replace(source, dest);
  26020. }
  26021. }
  26022. if (match[4]) {
  26023. var indexString = match[5];
  26024. if (indexString.indexOf("..") !== -1) {
  26025. var indexSplits = indexString.split("..");
  26026. var minIndex = parseInt(indexSplits[0]);
  26027. var maxIndex = parseInt(indexSplits[1]);
  26028. var sourceIncludeContent = includeContent.slice(0);
  26029. includeContent = "";
  26030. if (isNaN(maxIndex)) {
  26031. maxIndex = this._indexParameters[indexSplits[1]];
  26032. }
  26033. for (var i = minIndex; i <= maxIndex; i++) {
  26034. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  26035. }
  26036. }
  26037. else {
  26038. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26039. }
  26040. }
  26041. // Replace
  26042. returnValue = returnValue.replace(match[0], includeContent);
  26043. }
  26044. else {
  26045. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26046. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26047. Effect.IncludesShadersStore[includeFile] = fileContent;
  26048. _this._processIncludes(returnValue, callback);
  26049. });
  26050. return;
  26051. }
  26052. match = regex.exec(sourceCode);
  26053. }
  26054. callback(returnValue);
  26055. };
  26056. Effect.prototype._processPrecision = function (source) {
  26057. if (source.indexOf("precision highp float") === -1) {
  26058. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26059. source = "precision mediump float;\n" + source;
  26060. }
  26061. else {
  26062. source = "precision highp float;\n" + source;
  26063. }
  26064. }
  26065. else {
  26066. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26067. source = source.replace("precision highp float", "precision mediump float");
  26068. }
  26069. }
  26070. return source;
  26071. };
  26072. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  26073. try {
  26074. var engine = this._engine;
  26075. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  26076. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26077. this._attributes = engine.getAttributes(this._program, attributesNames);
  26078. var index;
  26079. for (index = 0; index < this._samplers.length; index++) {
  26080. var sampler = this.getUniform(this._samplers[index]);
  26081. if (sampler == null) {
  26082. this._samplers.splice(index, 1);
  26083. index--;
  26084. }
  26085. }
  26086. engine.bindSamplers(this);
  26087. this._compilationError = "";
  26088. this._isReady = true;
  26089. if (this.onCompiled) {
  26090. this.onCompiled(this);
  26091. }
  26092. }
  26093. catch (e) {
  26094. this._compilationError = e.message;
  26095. // Let's go through fallbacks then
  26096. BABYLON.Tools.Error("Unable to compile effect: ");
  26097. BABYLON.Tools.Error("Defines: " + defines);
  26098. BABYLON.Tools.Error("Error: " + this._compilationError);
  26099. this._dumpShadersName();
  26100. if (fallbacks && fallbacks.isMoreFallbacks) {
  26101. BABYLON.Tools.Error("Trying next fallback.");
  26102. defines = fallbacks.reduce(defines);
  26103. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  26104. }
  26105. else {
  26106. if (this.onError) {
  26107. this.onError(this, this._compilationError);
  26108. }
  26109. }
  26110. }
  26111. };
  26112. Object.defineProperty(Effect.prototype, "isSupported", {
  26113. get: function () {
  26114. return this._compilationError === "";
  26115. },
  26116. enumerable: true,
  26117. configurable: true
  26118. });
  26119. Effect.prototype._bindTexture = function (channel, texture) {
  26120. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26121. };
  26122. Effect.prototype.setTexture = function (channel, texture) {
  26123. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26124. };
  26125. Effect.prototype.setTextureArray = function (channel, textures) {
  26126. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26127. var initialPos = this._samplers.indexOf(channel);
  26128. for (var index = 1; index < textures.length; index++) {
  26129. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26130. }
  26131. }
  26132. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26133. };
  26134. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26135. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26136. };
  26137. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26138. var changed = false;
  26139. var cache = this._valueCache[uniformName];
  26140. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  26141. changed = true;
  26142. cache = new BABYLON.Matrix();
  26143. }
  26144. var tm = cache.m;
  26145. var om = matrix.m;
  26146. for (var index = 0; index < 16; index++) {
  26147. if (tm[index] !== om[index]) {
  26148. tm[index] = om[index];
  26149. changed = true;
  26150. }
  26151. }
  26152. this._valueCache[uniformName] = cache;
  26153. return changed;
  26154. };
  26155. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26156. var cache = this._valueCache[uniformName];
  26157. if (!cache) {
  26158. cache = [x, y];
  26159. this._valueCache[uniformName] = cache;
  26160. return true;
  26161. }
  26162. var changed = false;
  26163. if (cache[0] !== x) {
  26164. cache[0] = x;
  26165. changed = true;
  26166. }
  26167. if (cache[1] !== y) {
  26168. cache[1] = y;
  26169. changed = true;
  26170. }
  26171. return changed;
  26172. };
  26173. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26174. var cache = this._valueCache[uniformName];
  26175. if (!cache) {
  26176. cache = [x, y, z];
  26177. this._valueCache[uniformName] = cache;
  26178. return true;
  26179. }
  26180. var changed = false;
  26181. if (cache[0] !== x) {
  26182. cache[0] = x;
  26183. changed = true;
  26184. }
  26185. if (cache[1] !== y) {
  26186. cache[1] = y;
  26187. changed = true;
  26188. }
  26189. if (cache[2] !== z) {
  26190. cache[2] = z;
  26191. changed = true;
  26192. }
  26193. return changed;
  26194. };
  26195. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26196. var cache = this._valueCache[uniformName];
  26197. if (!cache) {
  26198. cache = [x, y, z, w];
  26199. this._valueCache[uniformName] = cache;
  26200. return true;
  26201. }
  26202. var changed = false;
  26203. if (cache[0] !== x) {
  26204. cache[0] = x;
  26205. changed = true;
  26206. }
  26207. if (cache[1] !== y) {
  26208. cache[1] = y;
  26209. changed = true;
  26210. }
  26211. if (cache[2] !== z) {
  26212. cache[2] = z;
  26213. changed = true;
  26214. }
  26215. if (cache[3] !== w) {
  26216. cache[3] = w;
  26217. changed = true;
  26218. }
  26219. return changed;
  26220. };
  26221. Effect.prototype.setIntArray = function (uniformName, array) {
  26222. this._valueCache[uniformName] = null;
  26223. this._engine.setIntArray(this.getUniform(uniformName), array);
  26224. return this;
  26225. };
  26226. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26227. this._valueCache[uniformName] = null;
  26228. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26229. return this;
  26230. };
  26231. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26232. this._valueCache[uniformName] = null;
  26233. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26234. return this;
  26235. };
  26236. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26237. this._valueCache[uniformName] = null;
  26238. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26239. return this;
  26240. };
  26241. Effect.prototype.setFloatArray = function (uniformName, array) {
  26242. this._valueCache[uniformName] = null;
  26243. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26244. return this;
  26245. };
  26246. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26247. this._valueCache[uniformName] = null;
  26248. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26249. return this;
  26250. };
  26251. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26252. this._valueCache[uniformName] = null;
  26253. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26254. return this;
  26255. };
  26256. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26257. this._valueCache[uniformName] = null;
  26258. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26259. return this;
  26260. };
  26261. Effect.prototype.setArray = function (uniformName, array) {
  26262. this._valueCache[uniformName] = null;
  26263. this._engine.setArray(this.getUniform(uniformName), array);
  26264. return this;
  26265. };
  26266. Effect.prototype.setArray2 = function (uniformName, array) {
  26267. this._valueCache[uniformName] = null;
  26268. this._engine.setArray2(this.getUniform(uniformName), array);
  26269. return this;
  26270. };
  26271. Effect.prototype.setArray3 = function (uniformName, array) {
  26272. this._valueCache[uniformName] = null;
  26273. this._engine.setArray3(this.getUniform(uniformName), array);
  26274. return this;
  26275. };
  26276. Effect.prototype.setArray4 = function (uniformName, array) {
  26277. this._valueCache[uniformName] = null;
  26278. this._engine.setArray4(this.getUniform(uniformName), array);
  26279. return this;
  26280. };
  26281. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26282. this._valueCache[uniformName] = null;
  26283. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26284. return this;
  26285. };
  26286. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26287. if (this._cacheMatrix(uniformName, matrix)) {
  26288. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26289. }
  26290. return this;
  26291. };
  26292. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26293. this._valueCache[uniformName] = null;
  26294. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26295. return this;
  26296. };
  26297. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26298. this._valueCache[uniformName] = null;
  26299. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26300. return this;
  26301. };
  26302. Effect.prototype.setFloat = function (uniformName, value) {
  26303. var cache = this._valueCache[uniformName];
  26304. if (cache !== undefined && cache === value)
  26305. return this;
  26306. this._valueCache[uniformName] = value;
  26307. this._engine.setFloat(this.getUniform(uniformName), value);
  26308. return this;
  26309. };
  26310. Effect.prototype.setBool = function (uniformName, bool) {
  26311. var cache = this._valueCache[uniformName];
  26312. if (cache !== undefined && cache === bool)
  26313. return this;
  26314. this._valueCache[uniformName] = bool;
  26315. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26316. return this;
  26317. };
  26318. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26319. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26320. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26321. }
  26322. return this;
  26323. };
  26324. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26325. if (this._cacheFloat2(uniformName, x, y)) {
  26326. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26327. }
  26328. return this;
  26329. };
  26330. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26331. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26332. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26333. }
  26334. return this;
  26335. };
  26336. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26337. if (this._cacheFloat3(uniformName, x, y, z)) {
  26338. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26339. }
  26340. return this;
  26341. };
  26342. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26343. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26344. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26345. }
  26346. return this;
  26347. };
  26348. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26349. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26350. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26351. }
  26352. return this;
  26353. };
  26354. Effect.prototype.setColor3 = function (uniformName, color3) {
  26355. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26356. this._engine.setColor3(this.getUniform(uniformName), color3);
  26357. }
  26358. return this;
  26359. };
  26360. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26361. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26362. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26363. }
  26364. return this;
  26365. };
  26366. Effect.prototype._recombineShader = function (node) {
  26367. if (node.define) {
  26368. if (node.condition) {
  26369. var defineIndex = this.defines.indexOf("#define " + node.define);
  26370. if (defineIndex === -1) {
  26371. return null;
  26372. }
  26373. var nextComma = this.defines.indexOf("\n", defineIndex);
  26374. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  26375. var condition = defineValue + node.condition;
  26376. if (!eval(condition)) {
  26377. return null;
  26378. }
  26379. }
  26380. else if (node.ndef) {
  26381. if (this.defines.indexOf("#define " + node.define) !== -1) {
  26382. return null;
  26383. }
  26384. }
  26385. else if (this.defines.indexOf("#define " + node.define) === -1) {
  26386. return null;
  26387. }
  26388. }
  26389. var result = "";
  26390. for (var index = 0; index < node.children.length; index++) {
  26391. var line = node.children[index];
  26392. if (line.children) {
  26393. var combined = this._recombineShader(line);
  26394. if (combined !== null) {
  26395. result += combined + "\r\n";
  26396. }
  26397. continue;
  26398. }
  26399. if (line.length > 0) {
  26400. result += line + "\r\n";
  26401. }
  26402. }
  26403. return result;
  26404. };
  26405. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  26406. var root = {
  26407. children: []
  26408. };
  26409. var currentNode = root;
  26410. var lines = shaderString.split("\n");
  26411. for (var index = 0; index < lines.length; index++) {
  26412. var line = lines[index].trim();
  26413. // #ifdef
  26414. var pos = line.indexOf("#ifdef ");
  26415. if (pos !== -1) {
  26416. var define = line.substr(pos + 7);
  26417. var newNode = {
  26418. condition: null,
  26419. ndef: false,
  26420. define: define,
  26421. children: [],
  26422. parent: currentNode
  26423. };
  26424. currentNode.children.push(newNode);
  26425. currentNode = newNode;
  26426. continue;
  26427. }
  26428. // #ifndef
  26429. var pos = line.indexOf("#ifndef ");
  26430. if (pos !== -1) {
  26431. var define = line.substr(pos + 8);
  26432. newNode = {
  26433. condition: null,
  26434. define: define,
  26435. ndef: true,
  26436. children: [],
  26437. parent: currentNode
  26438. };
  26439. currentNode.children.push(newNode);
  26440. currentNode = newNode;
  26441. continue;
  26442. }
  26443. // #if
  26444. var pos = line.indexOf("#if ");
  26445. if (pos !== -1) {
  26446. var define = line.substr(pos + 4).trim();
  26447. var conditionPos = define.indexOf(" ");
  26448. newNode = {
  26449. condition: define.substr(conditionPos + 1),
  26450. define: define.substr(0, conditionPos),
  26451. ndef: false,
  26452. children: [],
  26453. parent: currentNode
  26454. };
  26455. currentNode.children.push(newNode);
  26456. currentNode = newNode;
  26457. continue;
  26458. }
  26459. // #endif
  26460. pos = line.indexOf("#endif");
  26461. if (pos !== -1) {
  26462. currentNode = currentNode.parent;
  26463. continue;
  26464. }
  26465. currentNode.children.push(line);
  26466. }
  26467. // Recombine
  26468. return this._recombineShader(root);
  26469. };
  26470. return Effect;
  26471. }());
  26472. Effect._uniqueIdSeed = 0;
  26473. // Statics
  26474. Effect.ShadersStore = {};
  26475. Effect.IncludesShadersStore = {};
  26476. BABYLON.Effect = Effect;
  26477. })(BABYLON || (BABYLON = {}));
  26478. //# sourceMappingURL=babylon.effect.js.map
  26479. var BABYLON;
  26480. (function (BABYLON) {
  26481. var MaterialHelper = (function () {
  26482. function MaterialHelper() {
  26483. }
  26484. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  26485. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26486. var lightIndex = 0;
  26487. var needNormals = false;
  26488. var needRebuild = false;
  26489. var needShadows = false;
  26490. var lightmapMode = false;
  26491. for (var index = 0; index < scene.lights.length; index++) {
  26492. var light = scene.lights[index];
  26493. if (!light.isEnabled()) {
  26494. continue;
  26495. }
  26496. // Excluded check
  26497. if (light._excludedMeshesIds.length > 0) {
  26498. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  26499. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  26500. if (excludedMesh) {
  26501. light.excludedMeshes.push(excludedMesh);
  26502. }
  26503. }
  26504. light._excludedMeshesIds = [];
  26505. }
  26506. // Included check
  26507. if (light._includedOnlyMeshesIds.length > 0) {
  26508. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  26509. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  26510. if (includedOnlyMesh) {
  26511. light.includedOnlyMeshes.push(includedOnlyMesh);
  26512. }
  26513. }
  26514. light._includedOnlyMeshesIds = [];
  26515. }
  26516. if (!light.canAffectMesh(mesh)) {
  26517. continue;
  26518. }
  26519. needNormals = true;
  26520. if (defines["LIGHT" + lightIndex] === undefined) {
  26521. needRebuild = true;
  26522. }
  26523. defines["LIGHT" + lightIndex] = true;
  26524. var type;
  26525. if (light instanceof BABYLON.SpotLight) {
  26526. type = "SPOTLIGHT" + lightIndex;
  26527. }
  26528. else if (light instanceof BABYLON.HemisphericLight) {
  26529. type = "HEMILIGHT" + lightIndex;
  26530. }
  26531. else if (light instanceof BABYLON.PointLight) {
  26532. type = "POINTLIGHT" + lightIndex;
  26533. }
  26534. else {
  26535. type = "DIRLIGHT" + lightIndex;
  26536. }
  26537. if (defines[type] === undefined) {
  26538. needRebuild = true;
  26539. }
  26540. defines[type] = true;
  26541. // Specular
  26542. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  26543. defines["SPECULARTERM"] = true;
  26544. }
  26545. // Shadows
  26546. if (scene.shadowsEnabled) {
  26547. var shadowGenerator = light.getShadowGenerator();
  26548. if (mesh && mesh.receiveShadows && shadowGenerator) {
  26549. if (defines["SHADOW" + lightIndex] === undefined) {
  26550. needRebuild = true;
  26551. }
  26552. defines["SHADOW" + lightIndex] = true;
  26553. defines["SHADOWS"] = true;
  26554. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  26555. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  26556. needRebuild = true;
  26557. }
  26558. defines["SHADOWVSM" + lightIndex] = true;
  26559. }
  26560. if (shadowGenerator.usePoissonSampling) {
  26561. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  26562. needRebuild = true;
  26563. }
  26564. defines["SHADOWPCF" + lightIndex] = true;
  26565. }
  26566. needShadows = true;
  26567. }
  26568. }
  26569. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26570. lightmapMode = true;
  26571. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  26572. needRebuild = true;
  26573. }
  26574. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  26575. needRebuild = true;
  26576. }
  26577. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26578. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  26579. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  26580. }
  26581. }
  26582. lightIndex++;
  26583. if (lightIndex === maxSimultaneousLights)
  26584. break;
  26585. }
  26586. var caps = scene.getEngine().getCaps();
  26587. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  26588. if (defines["SHADOWFULLFLOAT"] === undefined) {
  26589. needRebuild = true;
  26590. }
  26591. defines["SHADOWFULLFLOAT"] = true;
  26592. }
  26593. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  26594. needRebuild = true;
  26595. }
  26596. if (lightmapMode) {
  26597. defines["LIGHTMAPEXCLUDED"] = true;
  26598. }
  26599. if (needRebuild) {
  26600. defines.rebuild();
  26601. }
  26602. return needNormals;
  26603. };
  26604. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  26605. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26606. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26607. if (!defines["LIGHT" + lightIndex]) {
  26608. break;
  26609. }
  26610. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  26611. samplersList.push("shadowSampler" + lightIndex);
  26612. }
  26613. };
  26614. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26615. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26616. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26617. if (!defines["LIGHT" + lightIndex]) {
  26618. break;
  26619. }
  26620. if (lightIndex > 0) {
  26621. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26622. }
  26623. if (defines["SHADOW" + lightIndex]) {
  26624. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26625. }
  26626. if (defines["SHADOWPCF" + lightIndex]) {
  26627. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26628. }
  26629. if (defines["SHADOWVSM" + lightIndex]) {
  26630. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  26631. }
  26632. }
  26633. };
  26634. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26635. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26636. fallbacks.addCPUSkinningFallback(0, mesh);
  26637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26639. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26642. }
  26643. }
  26644. };
  26645. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26646. if (defines["INSTANCES"]) {
  26647. attribs.push("world0");
  26648. attribs.push("world1");
  26649. attribs.push("world2");
  26650. attribs.push("world3");
  26651. }
  26652. };
  26653. // Bindings
  26654. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  26655. var shadowGenerator = light.getShadowGenerator();
  26656. if (mesh.receiveShadows && shadowGenerator) {
  26657. if (!light.needCube()) {
  26658. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  26659. }
  26660. else {
  26661. if (!depthValuesAlreadySet) {
  26662. depthValuesAlreadySet = true;
  26663. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  26664. }
  26665. }
  26666. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  26667. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  26668. }
  26669. return depthValuesAlreadySet;
  26670. };
  26671. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26672. if (light instanceof BABYLON.PointLight) {
  26673. // Point Light
  26674. light.transferToEffect(effect, "vLightData" + lightIndex);
  26675. }
  26676. else if (light instanceof BABYLON.DirectionalLight) {
  26677. // Directional Light
  26678. light.transferToEffect(effect, "vLightData" + lightIndex);
  26679. }
  26680. else if (light instanceof BABYLON.SpotLight) {
  26681. // Spot Light
  26682. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  26683. }
  26684. else if (light instanceof BABYLON.HemisphericLight) {
  26685. // Hemispheric Light
  26686. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  26687. }
  26688. };
  26689. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  26690. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26691. var lightIndex = 0;
  26692. var depthValuesAlreadySet = false;
  26693. for (var index = 0; index < scene.lights.length; index++) {
  26694. var light = scene.lights[index];
  26695. if (!light.isEnabled()) {
  26696. continue;
  26697. }
  26698. if (!light.canAffectMesh(mesh)) {
  26699. continue;
  26700. }
  26701. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26702. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  26703. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  26704. if (defines["SPECULARTERM"]) {
  26705. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  26706. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  26707. }
  26708. // Shadows
  26709. if (scene.shadowsEnabled) {
  26710. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  26711. }
  26712. lightIndex++;
  26713. if (lightIndex === maxSimultaneousLights)
  26714. break;
  26715. }
  26716. };
  26717. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26718. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26719. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26720. effect.setColor3("vFogColor", scene.fogColor);
  26721. }
  26722. };
  26723. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26724. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26725. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26726. if (matrices) {
  26727. effect.setMatrices("mBones", matrices);
  26728. }
  26729. }
  26730. };
  26731. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26732. if (defines["LOGARITHMICDEPTH"]) {
  26733. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26734. }
  26735. };
  26736. MaterialHelper.BindClipPlane = function (effect, scene) {
  26737. if (scene.clipPlane) {
  26738. var clipPlane = scene.clipPlane;
  26739. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26740. }
  26741. };
  26742. return MaterialHelper;
  26743. }());
  26744. BABYLON.MaterialHelper = MaterialHelper;
  26745. })(BABYLON || (BABYLON = {}));
  26746. //# sourceMappingURL=babylon.materialHelper.js.map
  26747. var BABYLON;
  26748. (function (BABYLON) {
  26749. var FresnelParameters = (function () {
  26750. function FresnelParameters() {
  26751. this.isEnabled = true;
  26752. this.leftColor = BABYLON.Color3.White();
  26753. this.rightColor = BABYLON.Color3.Black();
  26754. this.bias = 0;
  26755. this.power = 1;
  26756. }
  26757. FresnelParameters.prototype.clone = function () {
  26758. var newFresnelParameters = new FresnelParameters();
  26759. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26760. return newFresnelParameters;
  26761. };
  26762. FresnelParameters.prototype.serialize = function () {
  26763. var serializationObject = {};
  26764. serializationObject.isEnabled = this.isEnabled;
  26765. serializationObject.leftColor = this.leftColor;
  26766. serializationObject.rightColor = this.rightColor;
  26767. serializationObject.bias = this.bias;
  26768. serializationObject.power = this.power;
  26769. return serializationObject;
  26770. };
  26771. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26772. var fresnelParameters = new FresnelParameters();
  26773. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26774. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26775. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26776. fresnelParameters.bias = parsedFresnelParameters.bias;
  26777. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26778. return fresnelParameters;
  26779. };
  26780. return FresnelParameters;
  26781. }());
  26782. BABYLON.FresnelParameters = FresnelParameters;
  26783. })(BABYLON || (BABYLON = {}));
  26784. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26785. var BABYLON;
  26786. (function (BABYLON) {
  26787. var MaterialDefines = (function () {
  26788. function MaterialDefines() {
  26789. }
  26790. MaterialDefines.prototype.rebuild = function () {
  26791. if (this._keys) {
  26792. delete this._keys;
  26793. }
  26794. this._keys = Object.keys(this);
  26795. };
  26796. MaterialDefines.prototype.isEqual = function (other) {
  26797. if (this._keys.length !== other._keys.length) {
  26798. return false;
  26799. }
  26800. for (var index = 0; index < this._keys.length; index++) {
  26801. var prop = this._keys[index];
  26802. if (this[prop] !== other[prop]) {
  26803. return false;
  26804. }
  26805. }
  26806. return true;
  26807. };
  26808. MaterialDefines.prototype.cloneTo = function (other) {
  26809. if (this._keys.length !== other._keys.length) {
  26810. other._keys = this._keys.slice(0);
  26811. }
  26812. for (var index = 0; index < this._keys.length; index++) {
  26813. var prop = this._keys[index];
  26814. other[prop] = this[prop];
  26815. }
  26816. };
  26817. MaterialDefines.prototype.reset = function () {
  26818. for (var index = 0; index < this._keys.length; index++) {
  26819. var prop = this._keys[index];
  26820. if (typeof (this[prop]) === "number") {
  26821. this[prop] = 0;
  26822. }
  26823. else {
  26824. this[prop] = false;
  26825. }
  26826. }
  26827. };
  26828. MaterialDefines.prototype.toString = function () {
  26829. var result = "";
  26830. for (var index = 0; index < this._keys.length; index++) {
  26831. var prop = this._keys[index];
  26832. if (typeof (this[prop]) === "number") {
  26833. result += "#define " + prop + " " + this[prop] + "\n";
  26834. }
  26835. else if (this[prop]) {
  26836. result += "#define " + prop + "\n";
  26837. }
  26838. }
  26839. return result;
  26840. };
  26841. return MaterialDefines;
  26842. }());
  26843. BABYLON.MaterialDefines = MaterialDefines;
  26844. var Material = (function () {
  26845. function Material(name, scene, doNotAdd) {
  26846. this.checkReadyOnEveryCall = false;
  26847. this.checkReadyOnlyOnce = false;
  26848. this.state = "";
  26849. this.alpha = 1.0;
  26850. this.backFaceCulling = true;
  26851. this.doNotSerialize = false;
  26852. /**
  26853. * An event triggered when the material is disposed.
  26854. * @type {BABYLON.Observable}
  26855. */
  26856. this.onDisposeObservable = new BABYLON.Observable();
  26857. /**
  26858. * An event triggered when the material is bound.
  26859. * @type {BABYLON.Observable}
  26860. */
  26861. this.onBindObservable = new BABYLON.Observable();
  26862. /**
  26863. * An event triggered when the material is unbound.
  26864. * @type {BABYLON.Observable}
  26865. */
  26866. this.onUnBindObservable = new BABYLON.Observable();
  26867. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26868. this.disableDepthWrite = false;
  26869. this.fogEnabled = true;
  26870. this.pointSize = 1.0;
  26871. this.zOffset = 0;
  26872. this._wasPreviouslyReady = false;
  26873. this._fillMode = Material.TriangleFillMode;
  26874. this.name = name;
  26875. this.id = name;
  26876. this._scene = scene;
  26877. if (scene.useRightHandedSystem) {
  26878. this.sideOrientation = Material.ClockWiseSideOrientation;
  26879. }
  26880. else {
  26881. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26882. }
  26883. if (!doNotAdd) {
  26884. scene.materials.push(this);
  26885. }
  26886. }
  26887. Object.defineProperty(Material, "TriangleFillMode", {
  26888. get: function () {
  26889. return Material._TriangleFillMode;
  26890. },
  26891. enumerable: true,
  26892. configurable: true
  26893. });
  26894. Object.defineProperty(Material, "WireFrameFillMode", {
  26895. get: function () {
  26896. return Material._WireFrameFillMode;
  26897. },
  26898. enumerable: true,
  26899. configurable: true
  26900. });
  26901. Object.defineProperty(Material, "PointFillMode", {
  26902. get: function () {
  26903. return Material._PointFillMode;
  26904. },
  26905. enumerable: true,
  26906. configurable: true
  26907. });
  26908. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26909. get: function () {
  26910. return Material._ClockWiseSideOrientation;
  26911. },
  26912. enumerable: true,
  26913. configurable: true
  26914. });
  26915. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26916. get: function () {
  26917. return Material._CounterClockWiseSideOrientation;
  26918. },
  26919. enumerable: true,
  26920. configurable: true
  26921. });
  26922. Object.defineProperty(Material.prototype, "onDispose", {
  26923. set: function (callback) {
  26924. if (this._onDisposeObserver) {
  26925. this.onDisposeObservable.remove(this._onDisposeObserver);
  26926. }
  26927. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26928. },
  26929. enumerable: true,
  26930. configurable: true
  26931. });
  26932. Object.defineProperty(Material.prototype, "onBind", {
  26933. set: function (callback) {
  26934. if (this._onBindObserver) {
  26935. this.onBindObservable.remove(this._onBindObserver);
  26936. }
  26937. this._onBindObserver = this.onBindObservable.add(callback);
  26938. },
  26939. enumerable: true,
  26940. configurable: true
  26941. });
  26942. Object.defineProperty(Material.prototype, "wireframe", {
  26943. get: function () {
  26944. return this._fillMode === Material.WireFrameFillMode;
  26945. },
  26946. set: function (value) {
  26947. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26948. },
  26949. enumerable: true,
  26950. configurable: true
  26951. });
  26952. Object.defineProperty(Material.prototype, "pointsCloud", {
  26953. get: function () {
  26954. return this._fillMode === Material.PointFillMode;
  26955. },
  26956. set: function (value) {
  26957. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26958. },
  26959. enumerable: true,
  26960. configurable: true
  26961. });
  26962. Object.defineProperty(Material.prototype, "fillMode", {
  26963. get: function () {
  26964. return this._fillMode;
  26965. },
  26966. set: function (value) {
  26967. this._fillMode = value;
  26968. },
  26969. enumerable: true,
  26970. configurable: true
  26971. });
  26972. /**
  26973. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26974. * subclasses should override adding information pertainent to themselves
  26975. */
  26976. Material.prototype.toString = function (fullDetails) {
  26977. var ret = "Name: " + this.name;
  26978. if (fullDetails) {
  26979. }
  26980. return ret;
  26981. };
  26982. Material.prototype.getClassName = function () {
  26983. return "Material";
  26984. };
  26985. Object.defineProperty(Material.prototype, "isFrozen", {
  26986. get: function () {
  26987. return this.checkReadyOnlyOnce;
  26988. },
  26989. enumerable: true,
  26990. configurable: true
  26991. });
  26992. Material.prototype.freeze = function () {
  26993. this.checkReadyOnlyOnce = true;
  26994. };
  26995. Material.prototype.unfreeze = function () {
  26996. this.checkReadyOnlyOnce = false;
  26997. };
  26998. Material.prototype.isReady = function (mesh, useInstances) {
  26999. return true;
  27000. };
  27001. Material.prototype.getEffect = function () {
  27002. return this._effect;
  27003. };
  27004. Material.prototype.getScene = function () {
  27005. return this._scene;
  27006. };
  27007. Material.prototype.needAlphaBlending = function () {
  27008. return (this.alpha < 1.0);
  27009. };
  27010. Material.prototype.needAlphaTesting = function () {
  27011. return false;
  27012. };
  27013. Material.prototype.getAlphaTestTexture = function () {
  27014. return null;
  27015. };
  27016. Material.prototype.markDirty = function () {
  27017. this._wasPreviouslyReady = false;
  27018. };
  27019. Material.prototype._preBind = function () {
  27020. var engine = this._scene.getEngine();
  27021. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  27022. engine.enableEffect(this._effect);
  27023. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27024. };
  27025. Material.prototype.bind = function (world, mesh) {
  27026. this._scene._cachedMaterial = this;
  27027. this.onBindObservable.notifyObservers(mesh);
  27028. if (this.disableDepthWrite) {
  27029. var engine = this._scene.getEngine();
  27030. this._cachedDepthWriteState = engine.getDepthWrite();
  27031. engine.setDepthWrite(false);
  27032. }
  27033. };
  27034. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27035. };
  27036. Material.prototype.unbind = function () {
  27037. this.onUnBindObservable.notifyObservers(this);
  27038. if (this.disableDepthWrite) {
  27039. var engine = this._scene.getEngine();
  27040. engine.setDepthWrite(this._cachedDepthWriteState);
  27041. }
  27042. };
  27043. Material.prototype.clone = function (name) {
  27044. return null;
  27045. };
  27046. Material.prototype.getBindedMeshes = function () {
  27047. var result = new Array();
  27048. for (var index = 0; index < this._scene.meshes.length; index++) {
  27049. var mesh = this._scene.meshes[index];
  27050. if (mesh.material === this) {
  27051. result.push(mesh);
  27052. }
  27053. }
  27054. return result;
  27055. };
  27056. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27057. // Animations
  27058. this.getScene().stopAnimation(this);
  27059. // Remove from scene
  27060. var index = this._scene.materials.indexOf(this);
  27061. if (index >= 0) {
  27062. this._scene.materials.splice(index, 1);
  27063. }
  27064. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27065. if (forceDisposeEffect && this._effect) {
  27066. this._scene.getEngine()._releaseEffect(this._effect);
  27067. this._effect = null;
  27068. }
  27069. // Remove from meshes
  27070. for (index = 0; index < this._scene.meshes.length; index++) {
  27071. var mesh = this._scene.meshes[index];
  27072. if (mesh.material === this) {
  27073. mesh.material = null;
  27074. }
  27075. }
  27076. // Callback
  27077. this.onDisposeObservable.notifyObservers(this);
  27078. this.onDisposeObservable.clear();
  27079. this.onBindObservable.clear();
  27080. this.onUnBindObservable.clear();
  27081. };
  27082. Material.prototype.serialize = function () {
  27083. return BABYLON.SerializationHelper.Serialize(this);
  27084. };
  27085. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27086. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27087. multiMaterial.id = parsedMultiMaterial.id;
  27088. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27089. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27090. var subMatId = parsedMultiMaterial.materials[matIndex];
  27091. if (subMatId) {
  27092. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27093. }
  27094. else {
  27095. multiMaterial.subMaterials.push(null);
  27096. }
  27097. }
  27098. return multiMaterial;
  27099. };
  27100. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27101. if (!parsedMaterial.customType) {
  27102. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27103. }
  27104. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27105. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27106. ;
  27107. };
  27108. return Material;
  27109. }());
  27110. Material._TriangleFillMode = 0;
  27111. Material._WireFrameFillMode = 1;
  27112. Material._PointFillMode = 2;
  27113. Material._ClockWiseSideOrientation = 0;
  27114. Material._CounterClockWiseSideOrientation = 1;
  27115. __decorate([
  27116. BABYLON.serialize()
  27117. ], Material.prototype, "id", void 0);
  27118. __decorate([
  27119. BABYLON.serialize()
  27120. ], Material.prototype, "name", void 0);
  27121. __decorate([
  27122. BABYLON.serialize()
  27123. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27124. __decorate([
  27125. BABYLON.serialize()
  27126. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27127. __decorate([
  27128. BABYLON.serialize()
  27129. ], Material.prototype, "state", void 0);
  27130. __decorate([
  27131. BABYLON.serialize()
  27132. ], Material.prototype, "alpha", void 0);
  27133. __decorate([
  27134. BABYLON.serialize()
  27135. ], Material.prototype, "backFaceCulling", void 0);
  27136. __decorate([
  27137. BABYLON.serialize()
  27138. ], Material.prototype, "sideOrientation", void 0);
  27139. __decorate([
  27140. BABYLON.serialize()
  27141. ], Material.prototype, "alphaMode", void 0);
  27142. __decorate([
  27143. BABYLON.serialize()
  27144. ], Material.prototype, "disableDepthWrite", void 0);
  27145. __decorate([
  27146. BABYLON.serialize()
  27147. ], Material.prototype, "fogEnabled", void 0);
  27148. __decorate([
  27149. BABYLON.serialize()
  27150. ], Material.prototype, "pointSize", void 0);
  27151. __decorate([
  27152. BABYLON.serialize()
  27153. ], Material.prototype, "zOffset", void 0);
  27154. __decorate([
  27155. BABYLON.serialize()
  27156. ], Material.prototype, "wireframe", null);
  27157. __decorate([
  27158. BABYLON.serialize()
  27159. ], Material.prototype, "pointsCloud", null);
  27160. __decorate([
  27161. BABYLON.serialize()
  27162. ], Material.prototype, "fillMode", null);
  27163. BABYLON.Material = Material;
  27164. })(BABYLON || (BABYLON = {}));
  27165. //# sourceMappingURL=babylon.material.js.map
  27166. var BABYLON;
  27167. (function (BABYLON) {
  27168. var StandardMaterialDefines = (function (_super) {
  27169. __extends(StandardMaterialDefines, _super);
  27170. function StandardMaterialDefines() {
  27171. var _this = _super.call(this) || this;
  27172. _this.DIFFUSE = false;
  27173. _this.AMBIENT = false;
  27174. _this.OPACITY = false;
  27175. _this.OPACITYRGB = false;
  27176. _this.REFLECTION = false;
  27177. _this.EMISSIVE = false;
  27178. _this.SPECULAR = false;
  27179. _this.BUMP = false;
  27180. _this.PARALLAX = false;
  27181. _this.PARALLAXOCCLUSION = false;
  27182. _this.SPECULAROVERALPHA = false;
  27183. _this.CLIPPLANE = false;
  27184. _this.ALPHATEST = false;
  27185. _this.ALPHAFROMDIFFUSE = false;
  27186. _this.POINTSIZE = false;
  27187. _this.FOG = false;
  27188. _this.SPECULARTERM = false;
  27189. _this.DIFFUSEFRESNEL = false;
  27190. _this.OPACITYFRESNEL = false;
  27191. _this.REFLECTIONFRESNEL = false;
  27192. _this.REFRACTIONFRESNEL = false;
  27193. _this.EMISSIVEFRESNEL = false;
  27194. _this.FRESNEL = false;
  27195. _this.NORMAL = false;
  27196. _this.UV1 = false;
  27197. _this.UV2 = false;
  27198. _this.VERTEXCOLOR = false;
  27199. _this.VERTEXALPHA = false;
  27200. _this.NUM_BONE_INFLUENCERS = 0;
  27201. _this.BonesPerMesh = 0;
  27202. _this.INSTANCES = false;
  27203. _this.GLOSSINESS = false;
  27204. _this.ROUGHNESS = false;
  27205. _this.EMISSIVEASILLUMINATION = false;
  27206. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27207. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27208. _this.LIGHTMAP = false;
  27209. _this.USELIGHTMAPASSHADOWMAP = false;
  27210. _this.REFLECTIONMAP_3D = false;
  27211. _this.REFLECTIONMAP_SPHERICAL = false;
  27212. _this.REFLECTIONMAP_PLANAR = false;
  27213. _this.REFLECTIONMAP_CUBIC = false;
  27214. _this.REFLECTIONMAP_PROJECTION = false;
  27215. _this.REFLECTIONMAP_SKYBOX = false;
  27216. _this.REFLECTIONMAP_EXPLICIT = false;
  27217. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27218. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27219. _this.INVERTCUBICMAP = false;
  27220. _this.LOGARITHMICDEPTH = false;
  27221. _this.REFRACTION = false;
  27222. _this.REFRACTIONMAP_3D = false;
  27223. _this.REFLECTIONOVERALPHA = false;
  27224. _this.INVERTNORMALMAPX = false;
  27225. _this.INVERTNORMALMAPY = false;
  27226. _this.SHADOWFULLFLOAT = false;
  27227. _this.CAMERACOLORGRADING = false;
  27228. _this.CAMERACOLORCURVES = false;
  27229. _this.rebuild();
  27230. return _this;
  27231. }
  27232. return StandardMaterialDefines;
  27233. }(BABYLON.MaterialDefines));
  27234. var StandardMaterial = (function (_super) {
  27235. __extends(StandardMaterial, _super);
  27236. function StandardMaterial(name, scene) {
  27237. var _this = _super.call(this, name, scene) || this;
  27238. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27239. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27240. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27241. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27242. _this.specularPower = 64;
  27243. _this.useAlphaFromDiffuseTexture = false;
  27244. _this.useEmissiveAsIllumination = false;
  27245. _this.linkEmissiveWithDiffuse = false;
  27246. _this.useReflectionFresnelFromSpecular = false;
  27247. _this.useSpecularOverAlpha = false;
  27248. _this.useReflectionOverAlpha = false;
  27249. _this.disableLighting = false;
  27250. _this.useParallax = false;
  27251. _this.useParallaxOcclusion = false;
  27252. _this.parallaxScaleBias = 0.05;
  27253. _this.roughness = 0;
  27254. _this.indexOfRefraction = 0.98;
  27255. _this.invertRefractionY = true;
  27256. _this.useLightmapAsShadowmap = false;
  27257. _this.useGlossinessFromSpecularMapAlpha = false;
  27258. _this.maxSimultaneousLights = 4;
  27259. /**
  27260. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27261. */
  27262. _this.invertNormalMapX = false;
  27263. /**
  27264. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27265. */
  27266. _this.invertNormalMapY = false;
  27267. /**
  27268. * Color Grading 2D Lookup Texture.
  27269. * This allows special effects like sepia, black and white to sixties rendering style.
  27270. */
  27271. _this.cameraColorGradingTexture = null;
  27272. /**
  27273. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27274. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27275. * 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;
  27276. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27277. */
  27278. _this.cameraColorCurves = null;
  27279. _this._renderTargets = new BABYLON.SmartArray(16);
  27280. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27281. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27282. _this._defines = new StandardMaterialDefines();
  27283. _this._cachedDefines = new StandardMaterialDefines();
  27284. _this._cachedDefines.BonesPerMesh = -1;
  27285. _this.getRenderTargetTextures = function () {
  27286. _this._renderTargets.reset();
  27287. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27288. _this._renderTargets.push(_this.reflectionTexture);
  27289. }
  27290. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27291. _this._renderTargets.push(_this.refractionTexture);
  27292. }
  27293. return _this._renderTargets;
  27294. };
  27295. return _this;
  27296. }
  27297. StandardMaterial.prototype.getClassName = function () {
  27298. return "StandardMaterial";
  27299. };
  27300. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27301. get: function () {
  27302. return this._useLogarithmicDepth;
  27303. },
  27304. set: function (value) {
  27305. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. StandardMaterial.prototype.needAlphaBlending = function () {
  27311. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27312. };
  27313. StandardMaterial.prototype.needAlphaTesting = function () {
  27314. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  27315. };
  27316. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27317. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  27318. };
  27319. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27320. return this.diffuseTexture;
  27321. };
  27322. // Methods
  27323. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27324. if (!mesh) {
  27325. return true;
  27326. }
  27327. if (this._defines.INSTANCES !== useInstances) {
  27328. return false;
  27329. }
  27330. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  27331. return true;
  27332. }
  27333. return false;
  27334. };
  27335. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  27336. if (this.isFrozen) {
  27337. if (this._wasPreviouslyReady) {
  27338. return true;
  27339. }
  27340. }
  27341. var scene = this.getScene();
  27342. var engine = scene.getEngine();
  27343. var needUVs = false;
  27344. var needNormals = false;
  27345. this._defines.reset();
  27346. // Lights
  27347. if (scene.lightsEnabled && !this.disableLighting) {
  27348. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  27349. }
  27350. if (!this.checkReadyOnEveryCall) {
  27351. if (this._renderId === scene.getRenderId()) {
  27352. if (this._checkCache(scene, mesh, useInstances)) {
  27353. return true;
  27354. }
  27355. }
  27356. }
  27357. // Textures
  27358. if (scene.texturesEnabled) {
  27359. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27360. if (!this.diffuseTexture.isReady()) {
  27361. return false;
  27362. }
  27363. else {
  27364. needUVs = true;
  27365. this._defines.DIFFUSE = true;
  27366. }
  27367. }
  27368. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27369. if (!this.ambientTexture.isReady()) {
  27370. return false;
  27371. }
  27372. else {
  27373. needUVs = true;
  27374. this._defines.AMBIENT = true;
  27375. }
  27376. }
  27377. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27378. if (!this.opacityTexture.isReady()) {
  27379. return false;
  27380. }
  27381. else {
  27382. needUVs = true;
  27383. this._defines.OPACITY = true;
  27384. if (this.opacityTexture.getAlphaFromRGB) {
  27385. this._defines.OPACITYRGB = true;
  27386. }
  27387. }
  27388. }
  27389. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27390. if (!this.reflectionTexture.isReady()) {
  27391. return false;
  27392. }
  27393. else {
  27394. needNormals = true;
  27395. this._defines.REFLECTION = true;
  27396. if (this.roughness > 0) {
  27397. this._defines.ROUGHNESS = true;
  27398. }
  27399. if (this.useReflectionOverAlpha) {
  27400. this._defines.REFLECTIONOVERALPHA = true;
  27401. }
  27402. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  27403. this._defines.INVERTCUBICMAP = true;
  27404. }
  27405. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  27406. switch (this.reflectionTexture.coordinatesMode) {
  27407. case BABYLON.Texture.CUBIC_MODE:
  27408. case BABYLON.Texture.INVCUBIC_MODE:
  27409. this._defines.REFLECTIONMAP_CUBIC = true;
  27410. break;
  27411. case BABYLON.Texture.EXPLICIT_MODE:
  27412. this._defines.REFLECTIONMAP_EXPLICIT = true;
  27413. break;
  27414. case BABYLON.Texture.PLANAR_MODE:
  27415. this._defines.REFLECTIONMAP_PLANAR = true;
  27416. break;
  27417. case BABYLON.Texture.PROJECTION_MODE:
  27418. this._defines.REFLECTIONMAP_PROJECTION = true;
  27419. break;
  27420. case BABYLON.Texture.SKYBOX_MODE:
  27421. this._defines.REFLECTIONMAP_SKYBOX = true;
  27422. break;
  27423. case BABYLON.Texture.SPHERICAL_MODE:
  27424. this._defines.REFLECTIONMAP_SPHERICAL = true;
  27425. break;
  27426. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27427. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  27428. break;
  27429. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27430. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  27431. break;
  27432. }
  27433. }
  27434. }
  27435. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27436. if (!this.emissiveTexture.isReady()) {
  27437. return false;
  27438. }
  27439. else {
  27440. needUVs = true;
  27441. this._defines.EMISSIVE = true;
  27442. }
  27443. }
  27444. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27445. if (!this.lightmapTexture.isReady()) {
  27446. return false;
  27447. }
  27448. else {
  27449. needUVs = true;
  27450. this._defines.LIGHTMAP = true;
  27451. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  27452. }
  27453. }
  27454. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27455. if (!this.specularTexture.isReady()) {
  27456. return false;
  27457. }
  27458. else {
  27459. needUVs = true;
  27460. this._defines.SPECULAR = true;
  27461. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  27462. }
  27463. }
  27464. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27465. if (!this.bumpTexture.isReady()) {
  27466. return false;
  27467. }
  27468. else {
  27469. needUVs = true;
  27470. this._defines.BUMP = true;
  27471. if (this.useParallax) {
  27472. this._defines.PARALLAX = true;
  27473. if (this.useParallaxOcclusion) {
  27474. this._defines.PARALLAXOCCLUSION = true;
  27475. }
  27476. }
  27477. if (this.invertNormalMapX) {
  27478. this._defines.INVERTNORMALMAPX = true;
  27479. }
  27480. if (this.invertNormalMapY) {
  27481. this._defines.INVERTNORMALMAPY = true;
  27482. }
  27483. if (scene._mirroredCameraPosition) {
  27484. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  27485. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  27486. }
  27487. }
  27488. }
  27489. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27490. if (!this.refractionTexture.isReady()) {
  27491. return false;
  27492. }
  27493. else {
  27494. needUVs = true;
  27495. this._defines.REFRACTION = true;
  27496. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  27497. }
  27498. }
  27499. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27500. if (!this.cameraColorGradingTexture.isReady()) {
  27501. return false;
  27502. }
  27503. else {
  27504. this._defines.CAMERACOLORGRADING = true;
  27505. }
  27506. }
  27507. }
  27508. // Effect
  27509. if (scene.clipPlane) {
  27510. this._defines.CLIPPLANE = true;
  27511. }
  27512. if (engine.getAlphaTesting()) {
  27513. this._defines.ALPHATEST = true;
  27514. }
  27515. if (this._shouldUseAlphaFromDiffuseTexture()) {
  27516. this._defines.ALPHAFROMDIFFUSE = true;
  27517. }
  27518. if (this.useEmissiveAsIllumination) {
  27519. this._defines.EMISSIVEASILLUMINATION = true;
  27520. }
  27521. if (this.linkEmissiveWithDiffuse) {
  27522. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  27523. }
  27524. if (this.useLogarithmicDepth) {
  27525. this._defines.LOGARITHMICDEPTH = true;
  27526. }
  27527. if (this.cameraColorCurves) {
  27528. this._defines.CAMERACOLORCURVES = true;
  27529. }
  27530. // Point size
  27531. if (this.pointsCloud || scene.forcePointsCloud) {
  27532. this._defines.POINTSIZE = true;
  27533. }
  27534. // Fog
  27535. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27536. this._defines.FOG = true;
  27537. }
  27538. if (StandardMaterial.FresnelEnabled) {
  27539. // Fresnel
  27540. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  27541. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  27542. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  27543. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  27544. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27545. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27546. this._defines.DIFFUSEFRESNEL = true;
  27547. }
  27548. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27549. this._defines.OPACITYFRESNEL = true;
  27550. }
  27551. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27552. this._defines.REFLECTIONFRESNEL = true;
  27553. if (this.useReflectionFresnelFromSpecular) {
  27554. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  27555. }
  27556. }
  27557. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27558. this._defines.REFRACTIONFRESNEL = true;
  27559. }
  27560. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27561. this._defines.EMISSIVEFRESNEL = true;
  27562. }
  27563. needNormals = true;
  27564. this._defines.FRESNEL = true;
  27565. }
  27566. }
  27567. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  27568. this._defines.SPECULAROVERALPHA = true;
  27569. }
  27570. // Attribs
  27571. if (mesh) {
  27572. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27573. this._defines.NORMAL = true;
  27574. }
  27575. if (needUVs) {
  27576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27577. this._defines.UV1 = true;
  27578. }
  27579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27580. this._defines.UV2 = true;
  27581. }
  27582. }
  27583. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27584. this._defines.VERTEXCOLOR = true;
  27585. if (mesh.hasVertexAlpha) {
  27586. this._defines.VERTEXALPHA = true;
  27587. }
  27588. }
  27589. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  27590. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  27591. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  27592. }
  27593. // Instances
  27594. if (useInstances) {
  27595. this._defines.INSTANCES = true;
  27596. }
  27597. }
  27598. // Get correct effect
  27599. if (!this._defines.isEqual(this._cachedDefines)) {
  27600. this._defines.cloneTo(this._cachedDefines);
  27601. scene.resetCachedMaterial();
  27602. // Fallbacks
  27603. var fallbacks = new BABYLON.EffectFallbacks();
  27604. if (this._defines.REFLECTION) {
  27605. fallbacks.addFallback(0, "REFLECTION");
  27606. }
  27607. if (this._defines.SPECULAR) {
  27608. fallbacks.addFallback(0, "SPECULAR");
  27609. }
  27610. if (this._defines.BUMP) {
  27611. fallbacks.addFallback(0, "BUMP");
  27612. }
  27613. if (this._defines.PARALLAX) {
  27614. fallbacks.addFallback(1, "PARALLAX");
  27615. }
  27616. if (this._defines.PARALLAXOCCLUSION) {
  27617. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27618. }
  27619. if (this._defines.SPECULAROVERALPHA) {
  27620. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27621. }
  27622. if (this._defines.FOG) {
  27623. fallbacks.addFallback(1, "FOG");
  27624. }
  27625. if (this._defines.POINTSIZE) {
  27626. fallbacks.addFallback(0, "POINTSIZE");
  27627. }
  27628. if (this._defines.LOGARITHMICDEPTH) {
  27629. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27630. }
  27631. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  27632. if (this._defines.SPECULARTERM) {
  27633. fallbacks.addFallback(0, "SPECULARTERM");
  27634. }
  27635. if (this._defines.DIFFUSEFRESNEL) {
  27636. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27637. }
  27638. if (this._defines.OPACITYFRESNEL) {
  27639. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27640. }
  27641. if (this._defines.REFLECTIONFRESNEL) {
  27642. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27643. }
  27644. if (this._defines.EMISSIVEFRESNEL) {
  27645. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27646. }
  27647. if (this._defines.FRESNEL) {
  27648. fallbacks.addFallback(4, "FRESNEL");
  27649. }
  27650. //Attributes
  27651. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27652. if (this._defines.NORMAL) {
  27653. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27654. }
  27655. if (this._defines.UV1) {
  27656. attribs.push(BABYLON.VertexBuffer.UVKind);
  27657. }
  27658. if (this._defines.UV2) {
  27659. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27660. }
  27661. if (this._defines.VERTEXCOLOR) {
  27662. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27663. }
  27664. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  27665. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  27666. var shaderName = "default";
  27667. var join = this._defines.toString();
  27668. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27669. "vFogInfos", "vFogColor", "pointSize",
  27670. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27671. "mBones",
  27672. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27673. "depthValues",
  27674. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27675. "logarithmicDepthConstant"
  27676. ];
  27677. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27678. if (this._defines.CAMERACOLORCURVES) {
  27679. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27680. }
  27681. if (this._defines.CAMERACOLORGRADING) {
  27682. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27683. }
  27684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  27685. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  27686. }
  27687. if (!this._effect.isReady()) {
  27688. return false;
  27689. }
  27690. this._renderId = scene.getRenderId();
  27691. this._wasPreviouslyReady = true;
  27692. if (mesh) {
  27693. if (!mesh._materialDefines) {
  27694. mesh._materialDefines = new StandardMaterialDefines();
  27695. }
  27696. this._defines.cloneTo(mesh._materialDefines);
  27697. }
  27698. return true;
  27699. };
  27700. StandardMaterial.prototype.unbind = function () {
  27701. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  27702. this._effect.setTexture("reflection2DSampler", null);
  27703. }
  27704. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  27705. this._effect.setTexture("refraction2DSampler", null);
  27706. }
  27707. _super.prototype.unbind.call(this);
  27708. };
  27709. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27710. this._effect.setMatrix("world", world);
  27711. };
  27712. StandardMaterial.prototype.bind = function (world, mesh) {
  27713. var scene = this.getScene();
  27714. // Matrices
  27715. this.bindOnlyWorldMatrix(world);
  27716. // Bones
  27717. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  27718. if (scene.getCachedMaterial() !== this) {
  27719. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27720. if (StandardMaterial.FresnelEnabled) {
  27721. // Fresnel
  27722. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27723. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27724. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27725. }
  27726. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27727. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27728. }
  27729. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27730. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27731. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27732. }
  27733. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27734. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27735. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27736. }
  27737. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27738. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27739. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27740. }
  27741. }
  27742. // Textures
  27743. if (scene.texturesEnabled) {
  27744. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27745. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27746. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27747. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27748. }
  27749. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27750. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27751. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27752. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27753. }
  27754. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27755. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27756. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27757. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27758. }
  27759. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27760. if (this.reflectionTexture.isCube) {
  27761. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27762. }
  27763. else {
  27764. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27765. }
  27766. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27767. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27768. }
  27769. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27770. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27771. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27772. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27773. }
  27774. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27775. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27776. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27777. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27778. }
  27779. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27780. this._effect.setTexture("specularSampler", this.specularTexture);
  27781. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27782. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27783. }
  27784. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27785. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27786. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27787. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27788. }
  27789. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27790. var depth = 1.0;
  27791. if (this.refractionTexture.isCube) {
  27792. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27793. }
  27794. else {
  27795. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27796. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27797. if (this.refractionTexture.depth) {
  27798. depth = this.refractionTexture.depth;
  27799. }
  27800. }
  27801. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27802. }
  27803. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27804. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27805. }
  27806. }
  27807. // Clip plane
  27808. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27809. // Point size
  27810. if (this.pointsCloud) {
  27811. this._effect.setFloat("pointSize", this.pointSize);
  27812. }
  27813. // Colors
  27814. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27815. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27816. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27817. if (this._defines.SPECULARTERM) {
  27818. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27819. }
  27820. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27821. }
  27822. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27823. // Diffuse
  27824. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27825. // Lights
  27826. if (scene.lightsEnabled && !this.disableLighting) {
  27827. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27828. }
  27829. // View
  27830. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27831. this._effect.setMatrix("view", scene.getViewMatrix());
  27832. }
  27833. // Fog
  27834. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27835. // Log. depth
  27836. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27837. // Color Curves
  27838. if (this.cameraColorCurves) {
  27839. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27840. }
  27841. }
  27842. _super.prototype.bind.call(this, world, mesh);
  27843. };
  27844. StandardMaterial.prototype.getAnimatables = function () {
  27845. var results = [];
  27846. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27847. results.push(this.diffuseTexture);
  27848. }
  27849. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27850. results.push(this.ambientTexture);
  27851. }
  27852. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27853. results.push(this.opacityTexture);
  27854. }
  27855. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27856. results.push(this.reflectionTexture);
  27857. }
  27858. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27859. results.push(this.emissiveTexture);
  27860. }
  27861. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27862. results.push(this.specularTexture);
  27863. }
  27864. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27865. results.push(this.bumpTexture);
  27866. }
  27867. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27868. results.push(this.lightmapTexture);
  27869. }
  27870. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27871. results.push(this.refractionTexture);
  27872. }
  27873. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27874. results.push(this.cameraColorGradingTexture);
  27875. }
  27876. return results;
  27877. };
  27878. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27879. if (forceDisposeTextures) {
  27880. if (this.diffuseTexture) {
  27881. this.diffuseTexture.dispose();
  27882. }
  27883. if (this.ambientTexture) {
  27884. this.ambientTexture.dispose();
  27885. }
  27886. if (this.opacityTexture) {
  27887. this.opacityTexture.dispose();
  27888. }
  27889. if (this.reflectionTexture) {
  27890. this.reflectionTexture.dispose();
  27891. }
  27892. if (this.emissiveTexture) {
  27893. this.emissiveTexture.dispose();
  27894. }
  27895. if (this.specularTexture) {
  27896. this.specularTexture.dispose();
  27897. }
  27898. if (this.bumpTexture) {
  27899. this.bumpTexture.dispose();
  27900. }
  27901. if (this.lightmapTexture) {
  27902. this.lightmapTexture.dispose();
  27903. }
  27904. if (this.refractionTexture) {
  27905. this.refractionTexture.dispose();
  27906. }
  27907. if (this.cameraColorGradingTexture) {
  27908. this.cameraColorGradingTexture.dispose();
  27909. }
  27910. }
  27911. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27912. };
  27913. StandardMaterial.prototype.clone = function (name) {
  27914. var _this = this;
  27915. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27916. };
  27917. StandardMaterial.prototype.serialize = function () {
  27918. return BABYLON.SerializationHelper.Serialize(this);
  27919. };
  27920. // Statics
  27921. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27922. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27923. };
  27924. return StandardMaterial;
  27925. }(BABYLON.Material));
  27926. // Flags used to enable or disable a type of texture for all Standard Materials
  27927. StandardMaterial.DiffuseTextureEnabled = true;
  27928. StandardMaterial.AmbientTextureEnabled = true;
  27929. StandardMaterial.OpacityTextureEnabled = true;
  27930. StandardMaterial.ReflectionTextureEnabled = true;
  27931. StandardMaterial.EmissiveTextureEnabled = true;
  27932. StandardMaterial.SpecularTextureEnabled = true;
  27933. StandardMaterial.BumpTextureEnabled = true;
  27934. StandardMaterial.FresnelEnabled = true;
  27935. StandardMaterial.LightmapTextureEnabled = true;
  27936. StandardMaterial.RefractionTextureEnabled = true;
  27937. StandardMaterial.ColorGradingTextureEnabled = true;
  27938. __decorate([
  27939. BABYLON.serializeAsTexture()
  27940. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27941. __decorate([
  27942. BABYLON.serializeAsTexture()
  27943. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27944. __decorate([
  27945. BABYLON.serializeAsTexture()
  27946. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27947. __decorate([
  27948. BABYLON.serializeAsTexture()
  27949. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27950. __decorate([
  27951. BABYLON.serializeAsTexture()
  27952. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27953. __decorate([
  27954. BABYLON.serializeAsTexture()
  27955. ], StandardMaterial.prototype, "specularTexture", void 0);
  27956. __decorate([
  27957. BABYLON.serializeAsTexture()
  27958. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27959. __decorate([
  27960. BABYLON.serializeAsTexture()
  27961. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27962. __decorate([
  27963. BABYLON.serializeAsTexture()
  27964. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27965. __decorate([
  27966. BABYLON.serializeAsColor3("ambient")
  27967. ], StandardMaterial.prototype, "ambientColor", void 0);
  27968. __decorate([
  27969. BABYLON.serializeAsColor3("diffuse")
  27970. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27971. __decorate([
  27972. BABYLON.serializeAsColor3("specular")
  27973. ], StandardMaterial.prototype, "specularColor", void 0);
  27974. __decorate([
  27975. BABYLON.serializeAsColor3("emissive")
  27976. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27977. __decorate([
  27978. BABYLON.serialize()
  27979. ], StandardMaterial.prototype, "specularPower", void 0);
  27980. __decorate([
  27981. BABYLON.serialize()
  27982. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27983. __decorate([
  27984. BABYLON.serialize()
  27985. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27986. __decorate([
  27987. BABYLON.serialize()
  27988. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27989. __decorate([
  27990. BABYLON.serialize()
  27991. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27992. __decorate([
  27993. BABYLON.serialize()
  27994. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27995. __decorate([
  27996. BABYLON.serialize()
  27997. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27998. __decorate([
  27999. BABYLON.serialize()
  28000. ], StandardMaterial.prototype, "disableLighting", void 0);
  28001. __decorate([
  28002. BABYLON.serialize()
  28003. ], StandardMaterial.prototype, "useParallax", void 0);
  28004. __decorate([
  28005. BABYLON.serialize()
  28006. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28007. __decorate([
  28008. BABYLON.serialize()
  28009. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28010. __decorate([
  28011. BABYLON.serialize()
  28012. ], StandardMaterial.prototype, "roughness", void 0);
  28013. __decorate([
  28014. BABYLON.serialize()
  28015. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28016. __decorate([
  28017. BABYLON.serialize()
  28018. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28019. __decorate([
  28020. BABYLON.serialize()
  28021. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28022. __decorate([
  28023. BABYLON.serializeAsFresnelParameters()
  28024. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28025. __decorate([
  28026. BABYLON.serializeAsFresnelParameters()
  28027. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28028. __decorate([
  28029. BABYLON.serializeAsFresnelParameters()
  28030. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28031. __decorate([
  28032. BABYLON.serializeAsFresnelParameters()
  28033. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28034. __decorate([
  28035. BABYLON.serializeAsFresnelParameters()
  28036. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28037. __decorate([
  28038. BABYLON.serialize()
  28039. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28040. __decorate([
  28041. BABYLON.serialize()
  28042. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28043. __decorate([
  28044. BABYLON.serialize()
  28045. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28046. __decorate([
  28047. BABYLON.serialize()
  28048. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28049. __decorate([
  28050. BABYLON.serializeAsTexture()
  28051. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28052. __decorate([
  28053. BABYLON.serializeAsColorCurves()
  28054. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28055. __decorate([
  28056. BABYLON.serialize()
  28057. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28058. BABYLON.StandardMaterial = StandardMaterial;
  28059. })(BABYLON || (BABYLON = {}));
  28060. //# sourceMappingURL=babylon.standardMaterial.js.map
  28061. var BABYLON;
  28062. (function (BABYLON) {
  28063. var MultiMaterial = (function (_super) {
  28064. __extends(MultiMaterial, _super);
  28065. function MultiMaterial(name, scene) {
  28066. var _this = _super.call(this, name, scene, true) || this;
  28067. _this.subMaterials = new Array();
  28068. scene.multiMaterials.push(_this);
  28069. return _this;
  28070. }
  28071. // Properties
  28072. MultiMaterial.prototype.getSubMaterial = function (index) {
  28073. if (index < 0 || index >= this.subMaterials.length) {
  28074. return this.getScene().defaultMaterial;
  28075. }
  28076. return this.subMaterials[index];
  28077. };
  28078. // Methods
  28079. MultiMaterial.prototype.getClassName = function () {
  28080. return "MultiMaterial";
  28081. };
  28082. MultiMaterial.prototype.isReady = function (mesh) {
  28083. for (var index = 0; index < this.subMaterials.length; index++) {
  28084. var subMaterial = this.subMaterials[index];
  28085. if (subMaterial) {
  28086. if (!this.subMaterials[index].isReady(mesh)) {
  28087. return false;
  28088. }
  28089. }
  28090. }
  28091. return true;
  28092. };
  28093. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  28094. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  28095. for (var index = 0; index < this.subMaterials.length; index++) {
  28096. var subMaterial = null;
  28097. if (cloneChildren) {
  28098. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  28099. }
  28100. else {
  28101. subMaterial = this.subMaterials[index];
  28102. }
  28103. newMultiMaterial.subMaterials.push(subMaterial);
  28104. }
  28105. return newMultiMaterial;
  28106. };
  28107. MultiMaterial.prototype.serialize = function () {
  28108. var serializationObject = {};
  28109. serializationObject.name = this.name;
  28110. serializationObject.id = this.id;
  28111. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28112. serializationObject.materials = [];
  28113. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  28114. var subMat = this.subMaterials[matIndex];
  28115. if (subMat) {
  28116. serializationObject.materials.push(subMat.id);
  28117. }
  28118. else {
  28119. serializationObject.materials.push(null);
  28120. }
  28121. }
  28122. return serializationObject;
  28123. };
  28124. return MultiMaterial;
  28125. }(BABYLON.Material));
  28126. BABYLON.MultiMaterial = MultiMaterial;
  28127. })(BABYLON || (BABYLON = {}));
  28128. //# sourceMappingURL=babylon.multiMaterial.js.map
  28129. var BABYLON;
  28130. (function (BABYLON) {
  28131. var SceneLoader = (function () {
  28132. function SceneLoader() {
  28133. }
  28134. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  28135. get: function () {
  28136. return 0;
  28137. },
  28138. enumerable: true,
  28139. configurable: true
  28140. });
  28141. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  28142. get: function () {
  28143. return 1;
  28144. },
  28145. enumerable: true,
  28146. configurable: true
  28147. });
  28148. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  28149. get: function () {
  28150. return 2;
  28151. },
  28152. enumerable: true,
  28153. configurable: true
  28154. });
  28155. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  28156. get: function () {
  28157. return 3;
  28158. },
  28159. enumerable: true,
  28160. configurable: true
  28161. });
  28162. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  28163. get: function () {
  28164. return SceneLoader._ForceFullSceneLoadingForIncremental;
  28165. },
  28166. set: function (value) {
  28167. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  28173. get: function () {
  28174. return SceneLoader._ShowLoadingScreen;
  28175. },
  28176. set: function (value) {
  28177. SceneLoader._ShowLoadingScreen = value;
  28178. },
  28179. enumerable: true,
  28180. configurable: true
  28181. });
  28182. Object.defineProperty(SceneLoader, "loggingLevel", {
  28183. get: function () {
  28184. return SceneLoader._loggingLevel;
  28185. },
  28186. set: function (value) {
  28187. SceneLoader._loggingLevel = value;
  28188. },
  28189. enumerable: true,
  28190. configurable: true
  28191. });
  28192. SceneLoader._getDefaultPlugin = function () {
  28193. return SceneLoader._registeredPlugins[".babylon"];
  28194. };
  28195. SceneLoader._getPluginForExtension = function (extension) {
  28196. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  28197. if (registeredPlugin) {
  28198. return registeredPlugin;
  28199. }
  28200. return SceneLoader._getDefaultPlugin();
  28201. };
  28202. SceneLoader._getPluginForFilename = function (sceneFilename) {
  28203. if (sceneFilename.name) {
  28204. sceneFilename = sceneFilename.name;
  28205. }
  28206. var dotPosition = sceneFilename.lastIndexOf(".");
  28207. var queryStringPosition = sceneFilename.indexOf("?");
  28208. if (queryStringPosition === -1) {
  28209. queryStringPosition = sceneFilename.length;
  28210. }
  28211. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  28212. return SceneLoader._getPluginForExtension(extension);
  28213. };
  28214. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  28215. SceneLoader._getDirectLoad = function (sceneFilename) {
  28216. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  28217. return sceneFilename.substr(5);
  28218. }
  28219. return null;
  28220. };
  28221. // Public functions
  28222. SceneLoader.GetPluginForExtension = function (extension) {
  28223. return SceneLoader._getPluginForExtension(extension).plugin;
  28224. };
  28225. SceneLoader.RegisterPlugin = function (plugin) {
  28226. if (typeof plugin.extensions === "string") {
  28227. var extension = plugin.extensions;
  28228. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28229. plugin: plugin,
  28230. isBinary: false
  28231. };
  28232. }
  28233. else {
  28234. var extensions = plugin.extensions;
  28235. Object.keys(extensions).forEach(function (extension) {
  28236. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28237. plugin: plugin,
  28238. isBinary: extensions[extension].isBinary
  28239. };
  28240. });
  28241. }
  28242. };
  28243. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28244. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28245. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28246. return;
  28247. }
  28248. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28249. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28250. return;
  28251. }
  28252. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28253. var loadingToken = {};
  28254. scene._addPendingData(loadingToken);
  28255. var manifestChecked = function (success) {
  28256. scene.database = database;
  28257. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28258. var plugin = registeredPlugin.plugin;
  28259. var useArrayBuffer = registeredPlugin.isBinary;
  28260. var importMeshFromData = function (data) {
  28261. var meshes = [];
  28262. var particleSystems = [];
  28263. var skeletons = [];
  28264. try {
  28265. if (plugin.importMesh) {
  28266. var syncedPlugin = plugin;
  28267. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  28268. if (onerror) {
  28269. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28270. }
  28271. scene._removePendingData(loadingToken);
  28272. return;
  28273. }
  28274. if (onsuccess) {
  28275. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28276. onsuccess(meshes, particleSystems, skeletons);
  28277. scene._removePendingData(loadingToken);
  28278. }
  28279. }
  28280. else {
  28281. var asyncedPlugin = plugin;
  28282. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  28283. if (onsuccess) {
  28284. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28285. onsuccess(meshes, particleSystems, skeletons);
  28286. scene._removePendingData(loadingToken);
  28287. }
  28288. }, function () {
  28289. if (onerror) {
  28290. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28291. }
  28292. scene._removePendingData(loadingToken);
  28293. });
  28294. }
  28295. }
  28296. catch (e) {
  28297. if (onerror) {
  28298. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  28299. }
  28300. scene._removePendingData(loadingToken);
  28301. }
  28302. };
  28303. if (directLoad) {
  28304. importMeshFromData(directLoad);
  28305. return;
  28306. }
  28307. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  28308. importMeshFromData(data);
  28309. }, progressCallBack, database, useArrayBuffer);
  28310. };
  28311. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  28312. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28313. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28314. }
  28315. else {
  28316. // If the scene is a data stream or offline support is not enabled, it's a direct load
  28317. manifestChecked(true);
  28318. }
  28319. };
  28320. /**
  28321. * Load a scene
  28322. * @param rootUrl a string that defines the root url for scene and resources
  28323. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28324. * @param engine is the instance of BABYLON.Engine to use to create the scene
  28325. */
  28326. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  28327. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  28328. };
  28329. /**
  28330. * Append a scene
  28331. * @param rootUrl a string that defines the root url for scene and resources
  28332. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28333. * @param scene is the instance of BABYLON.Scene to append to
  28334. */
  28335. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28336. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28337. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28338. return;
  28339. }
  28340. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28341. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28342. var plugin = registeredPlugin.plugin;
  28343. var useArrayBuffer = registeredPlugin.isBinary;
  28344. var database;
  28345. var loadingToken = {};
  28346. scene._addPendingData(loadingToken);
  28347. if (SceneLoader.ShowLoadingScreen) {
  28348. scene.getEngine().displayLoadingUI();
  28349. }
  28350. var loadSceneFromData = function (data) {
  28351. scene.database = database;
  28352. if (plugin.load) {
  28353. var syncedPlugin = plugin;
  28354. if (!syncedPlugin.load(scene, data, rootUrl)) {
  28355. if (onerror) {
  28356. onerror(scene);
  28357. }
  28358. scene._removePendingData(loadingToken);
  28359. scene.getEngine().hideLoadingUI();
  28360. return;
  28361. }
  28362. if (onsuccess) {
  28363. onsuccess(scene);
  28364. }
  28365. scene._removePendingData(loadingToken);
  28366. }
  28367. else {
  28368. var asyncedPlugin = plugin;
  28369. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  28370. if (onsuccess) {
  28371. onsuccess(scene);
  28372. }
  28373. scene._removePendingData(loadingToken);
  28374. }, function () {
  28375. if (onerror) {
  28376. onerror(scene);
  28377. }
  28378. scene._removePendingData(loadingToken);
  28379. scene.getEngine().hideLoadingUI();
  28380. });
  28381. }
  28382. if (SceneLoader.ShowLoadingScreen) {
  28383. scene.executeWhenReady(function () {
  28384. scene.getEngine().hideLoadingUI();
  28385. });
  28386. }
  28387. };
  28388. var manifestChecked = function (success) {
  28389. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  28390. };
  28391. if (directLoad) {
  28392. loadSceneFromData(directLoad);
  28393. return;
  28394. }
  28395. if (rootUrl.indexOf("file:") === -1) {
  28396. if (scene.getEngine().enableOfflineSupport) {
  28397. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28398. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28399. }
  28400. else {
  28401. manifestChecked(true);
  28402. }
  28403. }
  28404. else {
  28405. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  28406. }
  28407. };
  28408. return SceneLoader;
  28409. }());
  28410. // Flags
  28411. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  28412. SceneLoader._ShowLoadingScreen = true;
  28413. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  28414. // Members
  28415. SceneLoader._registeredPlugins = {};
  28416. BABYLON.SceneLoader = SceneLoader;
  28417. ;
  28418. })(BABYLON || (BABYLON = {}));
  28419. //# sourceMappingURL=babylon.sceneLoader.js.map
  28420. var BABYLON;
  28421. (function (BABYLON) {
  28422. var Internals;
  28423. (function (Internals) {
  28424. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  28425. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28426. var parsedMaterial = parsedData.materials[index];
  28427. if (parsedMaterial.id === id) {
  28428. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28429. }
  28430. }
  28431. return null;
  28432. };
  28433. var isDescendantOf = function (mesh, names, hierarchyIds) {
  28434. names = (names instanceof Array) ? names : [names];
  28435. for (var i in names) {
  28436. if (mesh.name === names[i]) {
  28437. hierarchyIds.push(mesh.id);
  28438. return true;
  28439. }
  28440. }
  28441. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  28442. hierarchyIds.push(mesh.id);
  28443. return true;
  28444. }
  28445. return false;
  28446. };
  28447. var logOperation = function (operation, producer) {
  28448. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  28449. };
  28450. BABYLON.SceneLoader.RegisterPlugin({
  28451. extensions: ".babylon",
  28452. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  28453. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28454. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28455. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28456. // and avoid problems with multiple concurrent .babylon loads.
  28457. var log = "importMesh has failed JSON parse";
  28458. try {
  28459. var parsedData = JSON.parse(data);
  28460. log = "";
  28461. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28462. var loadedSkeletonsIds = [];
  28463. var loadedMaterialsIds = [];
  28464. var hierarchyIds = [];
  28465. var index;
  28466. var cache;
  28467. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28468. var parsedMesh = parsedData.meshes[index];
  28469. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  28470. if (meshesNames instanceof Array) {
  28471. // Remove found mesh name from list.
  28472. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  28473. }
  28474. //Geometry?
  28475. if (parsedMesh.geometryId) {
  28476. //does the file contain geometries?
  28477. if (parsedData.geometries) {
  28478. //find the correct geometry and add it to the scene
  28479. var found = false;
  28480. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  28481. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  28482. return;
  28483. }
  28484. else {
  28485. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  28486. if (parsedGeometryData.id === parsedMesh.geometryId) {
  28487. switch (geometryType) {
  28488. case "boxes":
  28489. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  28490. break;
  28491. case "spheres":
  28492. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  28493. break;
  28494. case "cylinders":
  28495. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  28496. break;
  28497. case "toruses":
  28498. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  28499. break;
  28500. case "grounds":
  28501. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  28502. break;
  28503. case "planes":
  28504. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  28505. break;
  28506. case "torusKnots":
  28507. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  28508. break;
  28509. case "vertexData":
  28510. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  28511. break;
  28512. }
  28513. found = true;
  28514. }
  28515. });
  28516. }
  28517. });
  28518. if (!found) {
  28519. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  28520. }
  28521. }
  28522. }
  28523. // Material ?
  28524. if (parsedMesh.materialId) {
  28525. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  28526. if (!materialFound && parsedData.multiMaterials) {
  28527. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  28528. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  28529. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  28530. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  28531. var subMatId = parsedMultiMaterial.materials[matIndex];
  28532. loadedMaterialsIds.push(subMatId);
  28533. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  28534. log += "\n\tMaterial " + mat.toString(fullDetails);
  28535. }
  28536. loadedMaterialsIds.push(parsedMultiMaterial.id);
  28537. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28538. materialFound = true;
  28539. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  28540. break;
  28541. }
  28542. }
  28543. }
  28544. if (!materialFound) {
  28545. loadedMaterialsIds.push(parsedMesh.materialId);
  28546. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  28547. if (!mat) {
  28548. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  28549. }
  28550. else {
  28551. log += "\n\tMaterial " + mat.toString(fullDetails);
  28552. }
  28553. }
  28554. }
  28555. // Skeleton ?
  28556. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  28557. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  28558. if (!skeletonAlreadyLoaded) {
  28559. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  28560. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  28561. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  28562. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28563. skeletons.push(skeleton);
  28564. loadedSkeletonsIds.push(parsedSkeleton.id);
  28565. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  28566. }
  28567. }
  28568. }
  28569. }
  28570. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28571. meshes.push(mesh);
  28572. log += "\n\tMesh " + mesh.toString(fullDetails);
  28573. }
  28574. }
  28575. // Connecting parents
  28576. var currentMesh;
  28577. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28578. currentMesh = scene.meshes[index];
  28579. if (currentMesh._waitingParentId) {
  28580. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  28581. currentMesh._waitingParentId = undefined;
  28582. }
  28583. }
  28584. // freeze and compute world matrix application
  28585. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28586. currentMesh = scene.meshes[index];
  28587. if (currentMesh._waitingFreezeWorldMatrix) {
  28588. currentMesh.freezeWorldMatrix();
  28589. currentMesh._waitingFreezeWorldMatrix = undefined;
  28590. }
  28591. else {
  28592. currentMesh.computeWorldMatrix(true);
  28593. }
  28594. }
  28595. // Particles
  28596. if (parsedData.particleSystems) {
  28597. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28598. var parsedParticleSystem = parsedData.particleSystems[index];
  28599. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  28600. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  28601. }
  28602. }
  28603. }
  28604. return true;
  28605. }
  28606. catch (err) {
  28607. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  28608. log = null;
  28609. throw err;
  28610. }
  28611. finally {
  28612. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28613. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28614. }
  28615. }
  28616. },
  28617. load: function (scene, data, rootUrl) {
  28618. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28619. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28620. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28621. // and avoid problems with multiple concurrent .babylon loads.
  28622. var log = "importScene has failed JSON parse";
  28623. try {
  28624. var parsedData = JSON.parse(data);
  28625. log = "";
  28626. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28627. // Scene
  28628. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  28629. scene.autoClear = parsedData.autoClear;
  28630. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  28631. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  28632. if (parsedData.gravity) {
  28633. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  28634. }
  28635. // Fog
  28636. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  28637. scene.fogMode = parsedData.fogMode;
  28638. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  28639. scene.fogStart = parsedData.fogStart;
  28640. scene.fogEnd = parsedData.fogEnd;
  28641. scene.fogDensity = parsedData.fogDensity;
  28642. log += "\tFog mode for scene: ";
  28643. switch (scene.fogMode) {
  28644. // getters not compiling, so using hardcoded
  28645. case 1:
  28646. log += "exp\n";
  28647. break;
  28648. case 2:
  28649. log += "exp2\n";
  28650. break;
  28651. case 3:
  28652. log += "linear\n";
  28653. break;
  28654. }
  28655. }
  28656. //Physics
  28657. if (parsedData.physicsEnabled) {
  28658. var physicsPlugin;
  28659. if (parsedData.physicsEngine === "cannon") {
  28660. physicsPlugin = new BABYLON.CannonJSPlugin();
  28661. }
  28662. else if (parsedData.physicsEngine === "oimo") {
  28663. physicsPlugin = new BABYLON.OimoJSPlugin();
  28664. }
  28665. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  28666. //else - default engine, which is currently oimo
  28667. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  28668. scene.enablePhysics(physicsGravity, physicsPlugin);
  28669. }
  28670. // Metadata
  28671. if (parsedData.metadata !== undefined) {
  28672. scene.metadata = parsedData.metadata;
  28673. }
  28674. //collisions, if defined. otherwise, default is true
  28675. if (parsedData.collisionsEnabled != undefined) {
  28676. scene.collisionsEnabled = parsedData.collisionsEnabled;
  28677. }
  28678. scene.workerCollisions = !!parsedData.workerCollisions;
  28679. var index;
  28680. var cache;
  28681. // Lights
  28682. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  28683. var parsedLight = parsedData.lights[index];
  28684. var light = BABYLON.Light.Parse(parsedLight, scene);
  28685. log += (index === 0 ? "\n\tLights:" : "");
  28686. log += "\n\t\t" + light.toString(fullDetails);
  28687. }
  28688. // Animations
  28689. if (parsedData.animations) {
  28690. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  28691. var parsedAnimation = parsedData.animations[index];
  28692. var animation = BABYLON.Animation.Parse(parsedAnimation);
  28693. scene.animations.push(animation);
  28694. log += (index === 0 ? "\n\tAnimations:" : "");
  28695. log += "\n\t\t" + animation.toString(fullDetails);
  28696. }
  28697. }
  28698. if (parsedData.autoAnimate) {
  28699. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  28700. }
  28701. // Materials
  28702. if (parsedData.materials) {
  28703. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28704. var parsedMaterial = parsedData.materials[index];
  28705. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28706. log += (index === 0 ? "\n\tMaterials:" : "");
  28707. log += "\n\t\t" + mat.toString(fullDetails);
  28708. }
  28709. }
  28710. if (parsedData.multiMaterials) {
  28711. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  28712. var parsedMultiMaterial = parsedData.multiMaterials[index];
  28713. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28714. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  28715. log += "\n\t\t" + mmat.toString(fullDetails);
  28716. }
  28717. }
  28718. // Skeletons
  28719. if (parsedData.skeletons) {
  28720. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  28721. var parsedSkeleton = parsedData.skeletons[index];
  28722. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28723. log += (index === 0 ? "\n\tSkeletons:" : "");
  28724. log += "\n\t\t" + skeleton.toString(fullDetails);
  28725. }
  28726. }
  28727. // Geometries
  28728. var geometries = parsedData.geometries;
  28729. if (geometries) {
  28730. // Boxes
  28731. var boxes = geometries.boxes;
  28732. if (boxes) {
  28733. for (index = 0, cache = boxes.length; index < cache; index++) {
  28734. var parsedBox = boxes[index];
  28735. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28736. }
  28737. }
  28738. // Spheres
  28739. var spheres = geometries.spheres;
  28740. if (spheres) {
  28741. for (index = 0, cache = spheres.length; index < cache; index++) {
  28742. var parsedSphere = spheres[index];
  28743. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28744. }
  28745. }
  28746. // Cylinders
  28747. var cylinders = geometries.cylinders;
  28748. if (cylinders) {
  28749. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28750. var parsedCylinder = cylinders[index];
  28751. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28752. }
  28753. }
  28754. // Toruses
  28755. var toruses = geometries.toruses;
  28756. if (toruses) {
  28757. for (index = 0, cache = toruses.length; index < cache; index++) {
  28758. var parsedTorus = toruses[index];
  28759. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28760. }
  28761. }
  28762. // Grounds
  28763. var grounds = geometries.grounds;
  28764. if (grounds) {
  28765. for (index = 0, cache = grounds.length; index < cache; index++) {
  28766. var parsedGround = grounds[index];
  28767. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28768. }
  28769. }
  28770. // Planes
  28771. var planes = geometries.planes;
  28772. if (planes) {
  28773. for (index = 0, cache = planes.length; index < cache; index++) {
  28774. var parsedPlane = planes[index];
  28775. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28776. }
  28777. }
  28778. // TorusKnots
  28779. var torusKnots = geometries.torusKnots;
  28780. if (torusKnots) {
  28781. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28782. var parsedTorusKnot = torusKnots[index];
  28783. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28784. }
  28785. }
  28786. // VertexData
  28787. var vertexData = geometries.vertexData;
  28788. if (vertexData) {
  28789. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28790. var parsedVertexData = vertexData[index];
  28791. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28792. }
  28793. }
  28794. }
  28795. // Meshes
  28796. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28797. var parsedMesh = parsedData.meshes[index];
  28798. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28799. log += (index === 0 ? "\n\tMeshes:" : "");
  28800. log += "\n\t\t" + mesh.toString(fullDetails);
  28801. }
  28802. // Cameras
  28803. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28804. var parsedCamera = parsedData.cameras[index];
  28805. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28806. log += (index === 0 ? "\n\tCameras:" : "");
  28807. log += "\n\t\t" + camera.toString(fullDetails);
  28808. }
  28809. if (parsedData.activeCameraID) {
  28810. scene.setActiveCameraByID(parsedData.activeCameraID);
  28811. }
  28812. // Browsing all the graph to connect the dots
  28813. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28814. var camera = scene.cameras[index];
  28815. if (camera._waitingParentId) {
  28816. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28817. camera._waitingParentId = undefined;
  28818. }
  28819. }
  28820. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28821. var light = scene.lights[index];
  28822. if (light._waitingParentId) {
  28823. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28824. light._waitingParentId = undefined;
  28825. }
  28826. }
  28827. // Sounds
  28828. var loadedSounds = [];
  28829. var loadedSound;
  28830. if (BABYLON.AudioEngine && parsedData.sounds) {
  28831. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28832. var parsedSound = parsedData.sounds[index];
  28833. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28834. if (!parsedSound.url)
  28835. parsedSound.url = parsedSound.name;
  28836. if (!loadedSounds[parsedSound.url]) {
  28837. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28838. loadedSounds[parsedSound.url] = loadedSound;
  28839. }
  28840. else {
  28841. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28842. }
  28843. }
  28844. else {
  28845. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28846. }
  28847. }
  28848. }
  28849. loadedSounds = [];
  28850. // Connect parents & children and parse actions
  28851. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28852. var mesh = scene.meshes[index];
  28853. if (mesh._waitingParentId) {
  28854. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28855. mesh._waitingParentId = undefined;
  28856. }
  28857. if (mesh._waitingActions) {
  28858. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28859. mesh._waitingActions = undefined;
  28860. }
  28861. }
  28862. // freeze world matrix application
  28863. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28864. var currentMesh = scene.meshes[index];
  28865. if (currentMesh._waitingFreezeWorldMatrix) {
  28866. currentMesh.freezeWorldMatrix();
  28867. currentMesh._waitingFreezeWorldMatrix = undefined;
  28868. }
  28869. else {
  28870. currentMesh.computeWorldMatrix(true);
  28871. }
  28872. }
  28873. // Particles Systems
  28874. if (parsedData.particleSystems) {
  28875. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28876. var parsedParticleSystem = parsedData.particleSystems[index];
  28877. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28878. }
  28879. }
  28880. // Lens flares
  28881. if (parsedData.lensFlareSystems) {
  28882. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28883. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28884. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28885. }
  28886. }
  28887. // Shadows
  28888. if (parsedData.shadowGenerators) {
  28889. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28890. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28891. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28892. }
  28893. }
  28894. // Actions (scene)
  28895. if (parsedData.actions) {
  28896. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28897. }
  28898. // Finish
  28899. return true;
  28900. }
  28901. catch (err) {
  28902. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28903. log = null;
  28904. throw err;
  28905. }
  28906. finally {
  28907. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28908. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28909. }
  28910. }
  28911. }
  28912. });
  28913. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28914. })(BABYLON || (BABYLON = {}));
  28915. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28916. var BABYLON;
  28917. (function (BABYLON) {
  28918. var SpriteManager = (function () {
  28919. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28920. if (epsilon === void 0) { epsilon = 0.01; }
  28921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28922. this.name = name;
  28923. this.sprites = new Array();
  28924. this.renderingGroupId = 0;
  28925. this.layerMask = 0x0FFFFFFF;
  28926. this.fogEnabled = true;
  28927. this.isPickable = false;
  28928. /**
  28929. * An event triggered when the manager is disposed.
  28930. * @type {BABYLON.Observable}
  28931. */
  28932. this.onDisposeObservable = new BABYLON.Observable();
  28933. this._vertexBuffers = {};
  28934. this._capacity = capacity;
  28935. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28936. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28937. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28938. if (cellSize.width && cellSize.height) {
  28939. this.cellWidth = cellSize.width;
  28940. this.cellHeight = cellSize.height;
  28941. }
  28942. else if (cellSize !== undefined) {
  28943. this.cellWidth = cellSize;
  28944. this.cellHeight = cellSize;
  28945. }
  28946. else {
  28947. return;
  28948. }
  28949. this._epsilon = epsilon;
  28950. this._scene = scene;
  28951. this._scene.spriteManagers.push(this);
  28952. var indices = [];
  28953. var index = 0;
  28954. for (var count = 0; count < capacity; count++) {
  28955. indices.push(index);
  28956. indices.push(index + 1);
  28957. indices.push(index + 2);
  28958. indices.push(index);
  28959. indices.push(index + 2);
  28960. indices.push(index + 3);
  28961. index += 4;
  28962. }
  28963. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28964. // VBO
  28965. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28966. this._vertexData = new Float32Array(capacity * 16 * 4);
  28967. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28968. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28969. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28970. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28971. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28972. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28973. this._vertexBuffers["options"] = options;
  28974. this._vertexBuffers["cellInfo"] = cellInfo;
  28975. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28976. // Effects
  28977. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28978. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28979. }
  28980. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28981. set: function (callback) {
  28982. if (this._onDisposeObserver) {
  28983. this.onDisposeObservable.remove(this._onDisposeObserver);
  28984. }
  28985. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28986. },
  28987. enumerable: true,
  28988. configurable: true
  28989. });
  28990. Object.defineProperty(SpriteManager.prototype, "texture", {
  28991. get: function () {
  28992. return this._spriteTexture;
  28993. },
  28994. set: function (value) {
  28995. this._spriteTexture = value;
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  29001. var arrayOffset = index * 16;
  29002. if (offsetX === 0)
  29003. offsetX = this._epsilon;
  29004. else if (offsetX === 1)
  29005. offsetX = 1 - this._epsilon;
  29006. if (offsetY === 0)
  29007. offsetY = this._epsilon;
  29008. else if (offsetY === 1)
  29009. offsetY = 1 - this._epsilon;
  29010. this._vertexData[arrayOffset] = sprite.position.x;
  29011. this._vertexData[arrayOffset + 1] = sprite.position.y;
  29012. this._vertexData[arrayOffset + 2] = sprite.position.z;
  29013. this._vertexData[arrayOffset + 3] = sprite.angle;
  29014. this._vertexData[arrayOffset + 4] = sprite.width;
  29015. this._vertexData[arrayOffset + 5] = sprite.height;
  29016. this._vertexData[arrayOffset + 6] = offsetX;
  29017. this._vertexData[arrayOffset + 7] = offsetY;
  29018. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  29019. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  29020. var offset = (sprite.cellIndex / rowSize) >> 0;
  29021. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  29022. this._vertexData[arrayOffset + 11] = offset;
  29023. // Color
  29024. this._vertexData[arrayOffset + 12] = sprite.color.r;
  29025. this._vertexData[arrayOffset + 13] = sprite.color.g;
  29026. this._vertexData[arrayOffset + 14] = sprite.color.b;
  29027. this._vertexData[arrayOffset + 15] = sprite.color.a;
  29028. };
  29029. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  29030. var count = Math.min(this._capacity, this.sprites.length);
  29031. var min = BABYLON.Vector3.Zero();
  29032. var max = BABYLON.Vector3.Zero();
  29033. var distance = Number.MAX_VALUE;
  29034. var currentSprite;
  29035. var cameraSpacePosition = BABYLON.Vector3.Zero();
  29036. var cameraView = camera.getViewMatrix();
  29037. for (var index = 0; index < count; index++) {
  29038. var sprite = this.sprites[index];
  29039. if (!sprite) {
  29040. continue;
  29041. }
  29042. if (predicate) {
  29043. if (!predicate(sprite)) {
  29044. continue;
  29045. }
  29046. }
  29047. else if (!sprite.isPickable) {
  29048. continue;
  29049. }
  29050. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  29051. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  29052. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  29053. if (ray.intersectsBoxMinMax(min, max)) {
  29054. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  29055. if (distance > currentDistance) {
  29056. distance = currentDistance;
  29057. currentSprite = sprite;
  29058. if (fastCheck) {
  29059. break;
  29060. }
  29061. }
  29062. }
  29063. }
  29064. if (currentSprite) {
  29065. var result = new BABYLON.PickingInfo();
  29066. result.hit = true;
  29067. result.pickedSprite = currentSprite;
  29068. result.distance = distance;
  29069. return result;
  29070. }
  29071. return null;
  29072. };
  29073. SpriteManager.prototype.render = function () {
  29074. // Check
  29075. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  29076. return;
  29077. var engine = this._scene.getEngine();
  29078. var baseSize = this._spriteTexture.getBaseSize();
  29079. // Sprites
  29080. var deltaTime = engine.getDeltaTime();
  29081. var max = Math.min(this._capacity, this.sprites.length);
  29082. var rowSize = baseSize.width / this.cellWidth;
  29083. var offset = 0;
  29084. for (var index = 0; index < max; index++) {
  29085. var sprite = this.sprites[index];
  29086. if (!sprite) {
  29087. continue;
  29088. }
  29089. sprite._animate(deltaTime);
  29090. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  29091. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  29092. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  29093. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  29094. }
  29095. this._buffer.update(this._vertexData);
  29096. // Render
  29097. var effect = this._effectBase;
  29098. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29099. effect = this._effectFog;
  29100. }
  29101. engine.enableEffect(effect);
  29102. var viewMatrix = this._scene.getViewMatrix();
  29103. effect.setTexture("diffuseSampler", this._spriteTexture);
  29104. effect.setMatrix("view", viewMatrix);
  29105. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29106. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  29107. // Fog
  29108. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29109. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  29110. effect.setColor3("vFogColor", this._scene.fogColor);
  29111. }
  29112. // VBOs
  29113. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29114. // Draw order
  29115. engine.setDepthFunctionToLessOrEqual();
  29116. effect.setBool("alphaTest", true);
  29117. engine.setColorWrite(false);
  29118. engine.draw(true, 0, max * 6);
  29119. engine.setColorWrite(true);
  29120. effect.setBool("alphaTest", false);
  29121. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29122. engine.draw(true, 0, max * 6);
  29123. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29124. };
  29125. SpriteManager.prototype.dispose = function () {
  29126. if (this._buffer) {
  29127. this._buffer.dispose();
  29128. this._buffer = null;
  29129. }
  29130. if (this._indexBuffer) {
  29131. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29132. this._indexBuffer = null;
  29133. }
  29134. if (this._spriteTexture) {
  29135. this._spriteTexture.dispose();
  29136. this._spriteTexture = null;
  29137. }
  29138. // Remove from scene
  29139. var index = this._scene.spriteManagers.indexOf(this);
  29140. this._scene.spriteManagers.splice(index, 1);
  29141. // Callback
  29142. this.onDisposeObservable.notifyObservers(this);
  29143. this.onDisposeObservable.clear();
  29144. };
  29145. return SpriteManager;
  29146. }());
  29147. BABYLON.SpriteManager = SpriteManager;
  29148. })(BABYLON || (BABYLON = {}));
  29149. //# sourceMappingURL=babylon.spriteManager.js.map
  29150. var BABYLON;
  29151. (function (BABYLON) {
  29152. var Sprite = (function () {
  29153. function Sprite(name, manager) {
  29154. this.name = name;
  29155. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29156. this.width = 1.0;
  29157. this.height = 1.0;
  29158. this.angle = 0;
  29159. this.cellIndex = 0;
  29160. this.invertU = 0;
  29161. this.invertV = 0;
  29162. this.animations = new Array();
  29163. this.isPickable = false;
  29164. this._animationStarted = false;
  29165. this._loopAnimation = false;
  29166. this._fromIndex = 0;
  29167. this._toIndex = 0;
  29168. this._delay = 0;
  29169. this._direction = 1;
  29170. this._frameCount = 0;
  29171. this._time = 0;
  29172. this._manager = manager;
  29173. this._manager.sprites.push(this);
  29174. this.position = BABYLON.Vector3.Zero();
  29175. }
  29176. Object.defineProperty(Sprite.prototype, "size", {
  29177. get: function () {
  29178. return this.width;
  29179. },
  29180. set: function (value) {
  29181. this.width = value;
  29182. this.height = value;
  29183. },
  29184. enumerable: true,
  29185. configurable: true
  29186. });
  29187. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  29188. this._fromIndex = from;
  29189. this._toIndex = to;
  29190. this._loopAnimation = loop;
  29191. this._delay = delay;
  29192. this._animationStarted = true;
  29193. this._direction = from < to ? 1 : -1;
  29194. this.cellIndex = from;
  29195. this._time = 0;
  29196. this._onAnimationEnd = onAnimationEnd;
  29197. };
  29198. Sprite.prototype.stopAnimation = function () {
  29199. this._animationStarted = false;
  29200. };
  29201. Sprite.prototype._animate = function (deltaTime) {
  29202. if (!this._animationStarted)
  29203. return;
  29204. this._time += deltaTime;
  29205. if (this._time > this._delay) {
  29206. this._time = this._time % this._delay;
  29207. this.cellIndex += this._direction;
  29208. if (this.cellIndex === this._toIndex) {
  29209. if (this._loopAnimation) {
  29210. this.cellIndex = this._fromIndex;
  29211. }
  29212. else {
  29213. this._animationStarted = false;
  29214. if (this._onAnimationEnd) {
  29215. this._onAnimationEnd();
  29216. }
  29217. if (this.disposeWhenFinishedAnimating) {
  29218. this.dispose();
  29219. }
  29220. }
  29221. }
  29222. }
  29223. };
  29224. Sprite.prototype.dispose = function () {
  29225. for (var i = 0; i < this._manager.sprites.length; i++) {
  29226. if (this._manager.sprites[i] == this) {
  29227. this._manager.sprites.splice(i, 1);
  29228. }
  29229. }
  29230. };
  29231. return Sprite;
  29232. }());
  29233. BABYLON.Sprite = Sprite;
  29234. })(BABYLON || (BABYLON = {}));
  29235. //# sourceMappingURL=babylon.sprite.js.map
  29236. var BABYLON;
  29237. (function (BABYLON) {
  29238. var Layer = (function () {
  29239. function Layer(name, imgUrl, scene, isBackground, color) {
  29240. this.name = name;
  29241. this.scale = new BABYLON.Vector2(1, 1);
  29242. this.offset = new BABYLON.Vector2(0, 0);
  29243. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  29244. this._vertexBuffers = {};
  29245. // Events
  29246. /**
  29247. * An event triggered when the layer is disposed.
  29248. * @type {BABYLON.Observable}
  29249. */
  29250. this.onDisposeObservable = new BABYLON.Observable();
  29251. /**
  29252. * An event triggered before rendering the scene
  29253. * @type {BABYLON.Observable}
  29254. */
  29255. this.onBeforeRenderObservable = new BABYLON.Observable();
  29256. /**
  29257. * An event triggered after rendering the scene
  29258. * @type {BABYLON.Observable}
  29259. */
  29260. this.onAfterRenderObservable = new BABYLON.Observable();
  29261. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  29262. this.isBackground = isBackground === undefined ? true : isBackground;
  29263. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  29264. this._scene = scene;
  29265. this._scene.layers.push(this);
  29266. var engine = scene.getEngine();
  29267. // VBO
  29268. var vertices = [];
  29269. vertices.push(1, 1);
  29270. vertices.push(-1, 1);
  29271. vertices.push(-1, -1);
  29272. vertices.push(1, -1);
  29273. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  29275. // Indices
  29276. var indices = [];
  29277. indices.push(0);
  29278. indices.push(1);
  29279. indices.push(2);
  29280. indices.push(0);
  29281. indices.push(2);
  29282. indices.push(3);
  29283. this._indexBuffer = engine.createIndexBuffer(indices);
  29284. // Effects
  29285. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  29286. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  29287. }
  29288. Object.defineProperty(Layer.prototype, "onDispose", {
  29289. set: function (callback) {
  29290. if (this._onDisposeObserver) {
  29291. this.onDisposeObservable.remove(this._onDisposeObserver);
  29292. }
  29293. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29294. },
  29295. enumerable: true,
  29296. configurable: true
  29297. });
  29298. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  29299. set: function (callback) {
  29300. if (this._onBeforeRenderObserver) {
  29301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29302. }
  29303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(Layer.prototype, "onAfterRender", {
  29309. set: function (callback) {
  29310. if (this._onAfterRenderObserver) {
  29311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29312. }
  29313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29314. },
  29315. enumerable: true,
  29316. configurable: true
  29317. });
  29318. Layer.prototype.render = function () {
  29319. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  29320. // Check
  29321. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  29322. return;
  29323. var engine = this._scene.getEngine();
  29324. this.onBeforeRenderObservable.notifyObservers(this);
  29325. // Render
  29326. engine.enableEffect(currentEffect);
  29327. engine.setState(false);
  29328. // Texture
  29329. currentEffect.setTexture("textureSampler", this.texture);
  29330. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  29331. // Color
  29332. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  29333. // Scale / offset
  29334. currentEffect.setVector2("offset", this.offset);
  29335. currentEffect.setVector2("scale", this.scale);
  29336. // VBOs
  29337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  29338. // Draw order
  29339. if (!this.alphaTest) {
  29340. engine.setAlphaMode(this.alphaBlendingMode);
  29341. engine.draw(true, 0, 6);
  29342. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29343. }
  29344. else {
  29345. engine.draw(true, 0, 6);
  29346. }
  29347. this.onAfterRenderObservable.notifyObservers(this);
  29348. };
  29349. Layer.prototype.dispose = function () {
  29350. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29351. if (vertexBuffer) {
  29352. vertexBuffer.dispose();
  29353. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29354. }
  29355. if (this._indexBuffer) {
  29356. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29357. this._indexBuffer = null;
  29358. }
  29359. if (this.texture) {
  29360. this.texture.dispose();
  29361. this.texture = null;
  29362. }
  29363. // Remove from scene
  29364. var index = this._scene.layers.indexOf(this);
  29365. this._scene.layers.splice(index, 1);
  29366. // Callback
  29367. this.onDisposeObservable.notifyObservers(this);
  29368. this.onDisposeObservable.clear();
  29369. this.onAfterRenderObservable.clear();
  29370. this.onBeforeRenderObservable.clear();
  29371. };
  29372. return Layer;
  29373. }());
  29374. BABYLON.Layer = Layer;
  29375. })(BABYLON || (BABYLON = {}));
  29376. //# sourceMappingURL=babylon.layer.js.map
  29377. var BABYLON;
  29378. (function (BABYLON) {
  29379. var Particle = (function () {
  29380. function Particle() {
  29381. this.position = BABYLON.Vector3.Zero();
  29382. this.direction = BABYLON.Vector3.Zero();
  29383. this.color = new BABYLON.Color4(0, 0, 0, 0);
  29384. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  29385. this.lifeTime = 1.0;
  29386. this.age = 0;
  29387. this.size = 0;
  29388. this.angle = 0;
  29389. this.angularSpeed = 0;
  29390. }
  29391. Particle.prototype.copyTo = function (other) {
  29392. other.position.copyFrom(this.position);
  29393. other.direction.copyFrom(this.direction);
  29394. other.color.copyFrom(this.color);
  29395. other.colorStep.copyFrom(this.colorStep);
  29396. other.lifeTime = this.lifeTime;
  29397. other.age = this.age;
  29398. other.size = this.size;
  29399. other.angle = this.angle;
  29400. other.angularSpeed = this.angularSpeed;
  29401. };
  29402. return Particle;
  29403. }());
  29404. BABYLON.Particle = Particle;
  29405. })(BABYLON || (BABYLON = {}));
  29406. //# sourceMappingURL=babylon.particle.js.map
  29407. var BABYLON;
  29408. (function (BABYLON) {
  29409. var randomNumber = function (min, max) {
  29410. if (min === max) {
  29411. return (min);
  29412. }
  29413. var random = Math.random();
  29414. return ((random * (max - min)) + min);
  29415. };
  29416. var ParticleSystem = (function () {
  29417. function ParticleSystem(name, capacity, scene, customEffect) {
  29418. var _this = this;
  29419. this.name = name;
  29420. // Members
  29421. this.animations = [];
  29422. this.renderingGroupId = 0;
  29423. this.emitter = null;
  29424. this.emitRate = 10;
  29425. this.manualEmitCount = -1;
  29426. this.updateSpeed = 0.01;
  29427. this.targetStopDuration = 0;
  29428. this.disposeOnStop = false;
  29429. this.minEmitPower = 1;
  29430. this.maxEmitPower = 1;
  29431. this.minLifeTime = 1;
  29432. this.maxLifeTime = 1;
  29433. this.minSize = 1;
  29434. this.maxSize = 1;
  29435. this.minAngularSpeed = 0;
  29436. this.maxAngularSpeed = 0;
  29437. this.layerMask = 0x0FFFFFFF;
  29438. this.customShader = null;
  29439. this.preventAutoStart = false;
  29440. /**
  29441. * An event triggered when the system is disposed.
  29442. * @type {BABYLON.Observable}
  29443. */
  29444. this.onDisposeObservable = new BABYLON.Observable();
  29445. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  29446. this.forceDepthWrite = false;
  29447. this.gravity = BABYLON.Vector3.Zero();
  29448. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  29449. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  29450. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  29451. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  29452. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29453. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29454. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  29455. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29456. this.particles = new Array();
  29457. this._stockParticles = new Array();
  29458. this._newPartsExcess = 0;
  29459. this._vertexBuffers = {};
  29460. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  29461. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  29462. this._scaledDirection = BABYLON.Vector3.Zero();
  29463. this._scaledGravity = BABYLON.Vector3.Zero();
  29464. this._currentRenderId = -1;
  29465. this._started = false;
  29466. this._stopped = false;
  29467. this._actualFrame = 0;
  29468. this.id = name;
  29469. this._capacity = capacity;
  29470. this._scene = scene;
  29471. this._customEffect = customEffect;
  29472. scene.particleSystems.push(this);
  29473. var indices = [];
  29474. var index = 0;
  29475. for (var count = 0; count < capacity; count++) {
  29476. indices.push(index);
  29477. indices.push(index + 1);
  29478. indices.push(index + 2);
  29479. indices.push(index);
  29480. indices.push(index + 2);
  29481. indices.push(index + 3);
  29482. index += 4;
  29483. }
  29484. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29485. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  29486. this._vertexData = new Float32Array(capacity * 11 * 4);
  29487. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  29488. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  29489. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  29490. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  29491. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29492. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29493. this._vertexBuffers["options"] = options;
  29494. // Default behaviors
  29495. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  29496. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  29497. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  29498. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  29499. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  29500. };
  29501. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  29502. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  29503. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  29504. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  29505. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  29506. };
  29507. this.updateFunction = function (particles) {
  29508. for (var index = 0; index < particles.length; index++) {
  29509. var particle = particles[index];
  29510. particle.age += _this._scaledUpdateSpeed;
  29511. if (particle.age >= particle.lifeTime) {
  29512. _this.recycleParticle(particle);
  29513. index--;
  29514. continue;
  29515. }
  29516. else {
  29517. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  29518. particle.color.addInPlace(_this._scaledColorStep);
  29519. if (particle.color.a < 0)
  29520. particle.color.a = 0;
  29521. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  29522. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  29523. particle.position.addInPlace(_this._scaledDirection);
  29524. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  29525. particle.direction.addInPlace(_this._scaledGravity);
  29526. }
  29527. }
  29528. };
  29529. }
  29530. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  29531. set: function (callback) {
  29532. if (this._onDisposeObserver) {
  29533. this.onDisposeObservable.remove(this._onDisposeObserver);
  29534. }
  29535. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29536. },
  29537. enumerable: true,
  29538. configurable: true
  29539. });
  29540. ParticleSystem.prototype.recycleParticle = function (particle) {
  29541. var lastParticle = this.particles.pop();
  29542. if (lastParticle !== particle) {
  29543. lastParticle.copyTo(particle);
  29544. this._stockParticles.push(lastParticle);
  29545. }
  29546. };
  29547. ParticleSystem.prototype.getCapacity = function () {
  29548. return this._capacity;
  29549. };
  29550. ParticleSystem.prototype.isAlive = function () {
  29551. return this._alive;
  29552. };
  29553. ParticleSystem.prototype.isStarted = function () {
  29554. return this._started;
  29555. };
  29556. ParticleSystem.prototype.start = function () {
  29557. this._started = true;
  29558. this._stopped = false;
  29559. this._actualFrame = 0;
  29560. };
  29561. ParticleSystem.prototype.stop = function () {
  29562. this._stopped = true;
  29563. };
  29564. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  29565. var offset = index * 11;
  29566. this._vertexData[offset] = particle.position.x;
  29567. this._vertexData[offset + 1] = particle.position.y;
  29568. this._vertexData[offset + 2] = particle.position.z;
  29569. this._vertexData[offset + 3] = particle.color.r;
  29570. this._vertexData[offset + 4] = particle.color.g;
  29571. this._vertexData[offset + 5] = particle.color.b;
  29572. this._vertexData[offset + 6] = particle.color.a;
  29573. this._vertexData[offset + 7] = particle.angle;
  29574. this._vertexData[offset + 8] = particle.size;
  29575. this._vertexData[offset + 9] = offsetX;
  29576. this._vertexData[offset + 10] = offsetY;
  29577. };
  29578. ParticleSystem.prototype._update = function (newParticles) {
  29579. // Update current
  29580. this._alive = this.particles.length > 0;
  29581. this.updateFunction(this.particles);
  29582. // Add new ones
  29583. var worldMatrix;
  29584. if (this.emitter.position) {
  29585. worldMatrix = this.emitter.getWorldMatrix();
  29586. }
  29587. else {
  29588. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  29589. }
  29590. var particle;
  29591. for (var index = 0; index < newParticles; index++) {
  29592. if (this.particles.length === this._capacity) {
  29593. break;
  29594. }
  29595. if (this._stockParticles.length !== 0) {
  29596. particle = this._stockParticles.pop();
  29597. particle.age = 0;
  29598. }
  29599. else {
  29600. particle = new BABYLON.Particle();
  29601. }
  29602. this.particles.push(particle);
  29603. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  29604. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  29605. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  29606. particle.size = randomNumber(this.minSize, this.maxSize);
  29607. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  29608. this.startPositionFunction(worldMatrix, particle.position, particle);
  29609. var step = randomNumber(0, 1.0);
  29610. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  29611. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  29612. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  29613. }
  29614. };
  29615. ParticleSystem.prototype._getEffect = function () {
  29616. if (this._customEffect) {
  29617. return this._customEffect;
  29618. }
  29619. ;
  29620. var defines = [];
  29621. if (this._scene.clipPlane) {
  29622. defines.push("#define CLIPPLANE");
  29623. }
  29624. // Effect
  29625. var join = defines.join("\n");
  29626. if (this._cachedDefines !== join) {
  29627. this._cachedDefines = join;
  29628. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  29629. }
  29630. return this._effect;
  29631. };
  29632. ParticleSystem.prototype.animate = function () {
  29633. if (!this._started)
  29634. return;
  29635. var effect = this._getEffect();
  29636. // Check
  29637. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  29638. return;
  29639. if (this._currentRenderId === this._scene.getRenderId()) {
  29640. return;
  29641. }
  29642. this._currentRenderId = this._scene.getRenderId();
  29643. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  29644. // determine the number of particles we need to create
  29645. var newParticles;
  29646. if (this.manualEmitCount > -1) {
  29647. newParticles = this.manualEmitCount;
  29648. this._newPartsExcess = 0;
  29649. this.manualEmitCount = 0;
  29650. }
  29651. else {
  29652. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  29653. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  29654. }
  29655. if (this._newPartsExcess > 1.0) {
  29656. newParticles += this._newPartsExcess >> 0;
  29657. this._newPartsExcess -= this._newPartsExcess >> 0;
  29658. }
  29659. this._alive = false;
  29660. if (!this._stopped) {
  29661. this._actualFrame += this._scaledUpdateSpeed;
  29662. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  29663. this.stop();
  29664. }
  29665. else {
  29666. newParticles = 0;
  29667. }
  29668. this._update(newParticles);
  29669. // Stopped?
  29670. if (this._stopped) {
  29671. if (!this._alive) {
  29672. this._started = false;
  29673. if (this.disposeOnStop) {
  29674. this._scene._toBeDisposed.push(this);
  29675. }
  29676. }
  29677. }
  29678. // Update VBO
  29679. var offset = 0;
  29680. for (var index = 0; index < this.particles.length; index++) {
  29681. var particle = this.particles[index];
  29682. this._appendParticleVertex(offset++, particle, 0, 0);
  29683. this._appendParticleVertex(offset++, particle, 1, 0);
  29684. this._appendParticleVertex(offset++, particle, 1, 1);
  29685. this._appendParticleVertex(offset++, particle, 0, 1);
  29686. }
  29687. this._vertexBuffer.update(this._vertexData);
  29688. };
  29689. ParticleSystem.prototype.render = function () {
  29690. var effect = this._getEffect();
  29691. // Check
  29692. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  29693. return 0;
  29694. var engine = this._scene.getEngine();
  29695. // Render
  29696. engine.enableEffect(effect);
  29697. engine.setState(false);
  29698. var viewMatrix = this._scene.getViewMatrix();
  29699. effect.setTexture("diffuseSampler", this.particleTexture);
  29700. effect.setMatrix("view", viewMatrix);
  29701. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29702. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  29703. if (this._scene.clipPlane) {
  29704. var clipPlane = this._scene.clipPlane;
  29705. var invView = viewMatrix.clone();
  29706. invView.invert();
  29707. effect.setMatrix("invView", invView);
  29708. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29709. }
  29710. // VBOs
  29711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29712. // Draw order
  29713. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  29714. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  29715. }
  29716. else {
  29717. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29718. }
  29719. if (this.forceDepthWrite) {
  29720. engine.setDepthWrite(true);
  29721. }
  29722. engine.draw(true, 0, this.particles.length * 6);
  29723. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29724. return this.particles.length;
  29725. };
  29726. ParticleSystem.prototype.dispose = function () {
  29727. if (this._vertexBuffer) {
  29728. this._vertexBuffer.dispose();
  29729. this._vertexBuffer = null;
  29730. }
  29731. if (this._indexBuffer) {
  29732. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29733. this._indexBuffer = null;
  29734. }
  29735. if (this.particleTexture) {
  29736. this.particleTexture.dispose();
  29737. this.particleTexture = null;
  29738. }
  29739. // Remove from scene
  29740. var index = this._scene.particleSystems.indexOf(this);
  29741. this._scene.particleSystems.splice(index, 1);
  29742. // Callback
  29743. this.onDisposeObservable.notifyObservers(this);
  29744. this.onDisposeObservable.clear();
  29745. };
  29746. // Clone
  29747. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29748. var custom = null;
  29749. var program = null;
  29750. if (this.customShader != null) {
  29751. program = this.customShader;
  29752. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29753. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29754. }
  29755. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  29756. result.customShader = program;
  29757. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  29758. if (newEmitter === undefined) {
  29759. newEmitter = this.emitter;
  29760. }
  29761. result.emitter = newEmitter;
  29762. if (this.particleTexture) {
  29763. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29764. }
  29765. if (!this.preventAutoStart) {
  29766. result.start();
  29767. }
  29768. return result;
  29769. };
  29770. ParticleSystem.prototype.serialize = function () {
  29771. var serializationObject = {};
  29772. serializationObject.name = this.name;
  29773. serializationObject.id = this.id;
  29774. // Emitter
  29775. if (this.emitter.position) {
  29776. serializationObject.emitterId = this.emitter.id;
  29777. }
  29778. else {
  29779. serializationObject.emitter = this.emitter.asArray();
  29780. }
  29781. serializationObject.capacity = this.getCapacity();
  29782. if (this.particleTexture) {
  29783. serializationObject.textureName = this.particleTexture.name;
  29784. }
  29785. // Animations
  29786. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29787. // Particle system
  29788. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29789. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29790. serializationObject.minSize = this.minSize;
  29791. serializationObject.maxSize = this.maxSize;
  29792. serializationObject.minEmitPower = this.minEmitPower;
  29793. serializationObject.maxEmitPower = this.maxEmitPower;
  29794. serializationObject.minLifeTime = this.minLifeTime;
  29795. serializationObject.maxLifeTime = this.maxLifeTime;
  29796. serializationObject.emitRate = this.emitRate;
  29797. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29798. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29799. serializationObject.gravity = this.gravity.asArray();
  29800. serializationObject.direction1 = this.direction1.asArray();
  29801. serializationObject.direction2 = this.direction2.asArray();
  29802. serializationObject.color1 = this.color1.asArray();
  29803. serializationObject.color2 = this.color2.asArray();
  29804. serializationObject.colorDead = this.colorDead.asArray();
  29805. serializationObject.updateSpeed = this.updateSpeed;
  29806. serializationObject.targetStopDuration = this.targetStopDuration;
  29807. serializationObject.textureMask = this.textureMask.asArray();
  29808. serializationObject.blendMode = this.blendMode;
  29809. serializationObject.customShader = this.customShader;
  29810. serializationObject.preventAutoStart = this.preventAutoStart;
  29811. return serializationObject;
  29812. };
  29813. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29814. var name = parsedParticleSystem.name;
  29815. var custom = null;
  29816. var program = null;
  29817. if (parsedParticleSystem.customShader) {
  29818. program = parsedParticleSystem.customShader;
  29819. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29820. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29821. }
  29822. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  29823. particleSystem.customShader = program;
  29824. if (parsedParticleSystem.id) {
  29825. particleSystem.id = parsedParticleSystem.id;
  29826. }
  29827. // Auto start
  29828. if (parsedParticleSystem.preventAutoStart) {
  29829. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  29830. }
  29831. // Texture
  29832. if (parsedParticleSystem.textureName) {
  29833. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29834. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29835. }
  29836. // Emitter
  29837. if (parsedParticleSystem.emitterId) {
  29838. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29839. }
  29840. else {
  29841. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29842. }
  29843. // Animations
  29844. if (parsedParticleSystem.animations) {
  29845. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29846. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29847. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29848. }
  29849. }
  29850. if (parsedParticleSystem.autoAnimate) {
  29851. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29852. }
  29853. // Particle system
  29854. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29855. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29856. particleSystem.minSize = parsedParticleSystem.minSize;
  29857. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29858. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29859. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29860. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29861. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29862. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29863. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29864. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29865. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29866. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29867. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29868. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29869. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29870. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29871. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29872. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29873. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29874. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29875. if (!particleSystem.preventAutoStart) {
  29876. particleSystem.start();
  29877. }
  29878. return particleSystem;
  29879. };
  29880. return ParticleSystem;
  29881. }());
  29882. // Statics
  29883. ParticleSystem.BLENDMODE_ONEONE = 0;
  29884. ParticleSystem.BLENDMODE_STANDARD = 1;
  29885. BABYLON.ParticleSystem = ParticleSystem;
  29886. })(BABYLON || (BABYLON = {}));
  29887. //# sourceMappingURL=babylon.particleSystem.js.map
  29888. var BABYLON;
  29889. (function (BABYLON) {
  29890. var AnimationRange = (function () {
  29891. function AnimationRange(name, from, to) {
  29892. this.name = name;
  29893. this.from = from;
  29894. this.to = to;
  29895. }
  29896. AnimationRange.prototype.clone = function () {
  29897. return new AnimationRange(this.name, this.from, this.to);
  29898. };
  29899. return AnimationRange;
  29900. }());
  29901. BABYLON.AnimationRange = AnimationRange;
  29902. /**
  29903. * Composed of a frame, and an action function
  29904. */
  29905. var AnimationEvent = (function () {
  29906. function AnimationEvent(frame, action, onlyOnce) {
  29907. this.frame = frame;
  29908. this.action = action;
  29909. this.onlyOnce = onlyOnce;
  29910. this.isDone = false;
  29911. }
  29912. return AnimationEvent;
  29913. }());
  29914. BABYLON.AnimationEvent = AnimationEvent;
  29915. var PathCursor = (function () {
  29916. function PathCursor(path) {
  29917. this.path = path;
  29918. this._onchange = new Array();
  29919. this.value = 0;
  29920. this.animations = new Array();
  29921. }
  29922. PathCursor.prototype.getPoint = function () {
  29923. var point = this.path.getPointAtLengthPosition(this.value);
  29924. return new BABYLON.Vector3(point.x, 0, point.y);
  29925. };
  29926. PathCursor.prototype.moveAhead = function (step) {
  29927. if (step === void 0) { step = 0.002; }
  29928. this.move(step);
  29929. return this;
  29930. };
  29931. PathCursor.prototype.moveBack = function (step) {
  29932. if (step === void 0) { step = 0.002; }
  29933. this.move(-step);
  29934. return this;
  29935. };
  29936. PathCursor.prototype.move = function (step) {
  29937. if (Math.abs(step) > 1) {
  29938. throw "step size should be less than 1.";
  29939. }
  29940. this.value += step;
  29941. this.ensureLimits();
  29942. this.raiseOnChange();
  29943. return this;
  29944. };
  29945. PathCursor.prototype.ensureLimits = function () {
  29946. while (this.value > 1) {
  29947. this.value -= 1;
  29948. }
  29949. while (this.value < 0) {
  29950. this.value += 1;
  29951. }
  29952. return this;
  29953. };
  29954. // used by animation engine
  29955. PathCursor.prototype.markAsDirty = function (propertyName) {
  29956. this.ensureLimits();
  29957. this.raiseOnChange();
  29958. return this;
  29959. };
  29960. PathCursor.prototype.raiseOnChange = function () {
  29961. var _this = this;
  29962. this._onchange.forEach(function (f) { return f(_this); });
  29963. return this;
  29964. };
  29965. PathCursor.prototype.onchange = function (f) {
  29966. this._onchange.push(f);
  29967. return this;
  29968. };
  29969. return PathCursor;
  29970. }());
  29971. BABYLON.PathCursor = PathCursor;
  29972. var Animation = (function () {
  29973. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29974. this.name = name;
  29975. this.targetProperty = targetProperty;
  29976. this.framePerSecond = framePerSecond;
  29977. this.dataType = dataType;
  29978. this.loopMode = loopMode;
  29979. this.enableBlending = enableBlending;
  29980. this._offsetsCache = {};
  29981. this._highLimitsCache = {};
  29982. this._stopped = false;
  29983. this._blendingFactor = 0;
  29984. // The set of event that will be linked to this animation
  29985. this._events = new Array();
  29986. this.allowMatricesInterpolation = false;
  29987. this.blendingSpeed = 0.01;
  29988. this._ranges = {};
  29989. this.targetPropertyPath = targetProperty.split(".");
  29990. this.dataType = dataType;
  29991. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29992. }
  29993. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29994. var dataType = undefined;
  29995. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29996. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29997. }
  29998. else if (from instanceof BABYLON.Quaternion) {
  29999. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30000. }
  30001. else if (from instanceof BABYLON.Vector3) {
  30002. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30003. }
  30004. else if (from instanceof BABYLON.Vector2) {
  30005. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30006. }
  30007. else if (from instanceof BABYLON.Color3) {
  30008. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30009. }
  30010. else if (from instanceof BABYLON.Size) {
  30011. dataType = Animation.ANIMATIONTYPE_SIZE;
  30012. }
  30013. if (dataType == undefined) {
  30014. return null;
  30015. }
  30016. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30017. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30018. animation.setKeys(keys);
  30019. if (easingFunction !== undefined) {
  30020. animation.setEasingFunction(easingFunction);
  30021. }
  30022. return animation;
  30023. };
  30024. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30025. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30026. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30027. };
  30028. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30029. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30030. node.animations.push(animation);
  30031. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30032. };
  30033. // Methods
  30034. /**
  30035. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30036. */
  30037. Animation.prototype.toString = function (fullDetails) {
  30038. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30039. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30040. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30041. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30042. if (fullDetails) {
  30043. ret += ", Ranges: {";
  30044. var first = true;
  30045. for (var name in this._ranges) {
  30046. if (first) {
  30047. ret += ", ";
  30048. first = false;
  30049. }
  30050. ret += name;
  30051. }
  30052. ret += "}";
  30053. }
  30054. return ret;
  30055. };
  30056. /**
  30057. * Add an event to this animation.
  30058. */
  30059. Animation.prototype.addEvent = function (event) {
  30060. this._events.push(event);
  30061. };
  30062. /**
  30063. * Remove all events found at the given frame
  30064. * @param frame
  30065. */
  30066. Animation.prototype.removeEvents = function (frame) {
  30067. for (var index = 0; index < this._events.length; index++) {
  30068. if (this._events[index].frame === frame) {
  30069. this._events.splice(index, 1);
  30070. index--;
  30071. }
  30072. }
  30073. };
  30074. Animation.prototype.createRange = function (name, from, to) {
  30075. // check name not already in use; could happen for bones after serialized
  30076. if (!this._ranges[name]) {
  30077. this._ranges[name] = new AnimationRange(name, from, to);
  30078. }
  30079. };
  30080. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30081. if (deleteFrames === void 0) { deleteFrames = true; }
  30082. if (this._ranges[name]) {
  30083. if (deleteFrames) {
  30084. var from = this._ranges[name].from;
  30085. var to = this._ranges[name].to;
  30086. // this loop MUST go high to low for multiple splices to work
  30087. for (var key = this._keys.length - 1; key >= 0; key--) {
  30088. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30089. this._keys.splice(key, 1);
  30090. }
  30091. }
  30092. }
  30093. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30094. }
  30095. };
  30096. Animation.prototype.getRange = function (name) {
  30097. return this._ranges[name];
  30098. };
  30099. Animation.prototype.reset = function () {
  30100. this._offsetsCache = {};
  30101. this._highLimitsCache = {};
  30102. this.currentFrame = 0;
  30103. this._blendingFactor = 0;
  30104. this._originalBlendValue = null;
  30105. };
  30106. Animation.prototype.isStopped = function () {
  30107. return this._stopped;
  30108. };
  30109. Animation.prototype.getKeys = function () {
  30110. return this._keys;
  30111. };
  30112. Animation.prototype.getHighestFrame = function () {
  30113. var ret = 0;
  30114. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30115. if (ret < this._keys[key].frame) {
  30116. ret = this._keys[key].frame;
  30117. }
  30118. }
  30119. return ret;
  30120. };
  30121. Animation.prototype.getEasingFunction = function () {
  30122. return this._easingFunction;
  30123. };
  30124. Animation.prototype.setEasingFunction = function (easingFunction) {
  30125. this._easingFunction = easingFunction;
  30126. };
  30127. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30128. return startValue + (endValue - startValue) * gradient;
  30129. };
  30130. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30131. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30132. };
  30133. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30134. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30135. };
  30136. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30137. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30138. };
  30139. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30140. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30141. };
  30142. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30143. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30144. };
  30145. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30146. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30147. };
  30148. Animation.prototype.clone = function () {
  30149. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30150. clone.enableBlending = this.enableBlending;
  30151. clone.blendingSpeed = this.blendingSpeed;
  30152. if (this._keys) {
  30153. clone.setKeys(this._keys);
  30154. }
  30155. if (this._ranges) {
  30156. clone._ranges = {};
  30157. for (var name in this._ranges) {
  30158. clone._ranges[name] = this._ranges[name].clone();
  30159. }
  30160. }
  30161. return clone;
  30162. };
  30163. Animation.prototype.setKeys = function (values) {
  30164. this._keys = values.slice(0);
  30165. this._offsetsCache = {};
  30166. this._highLimitsCache = {};
  30167. };
  30168. Animation.prototype._getKeyValue = function (value) {
  30169. if (typeof value === "function") {
  30170. return value();
  30171. }
  30172. return value;
  30173. };
  30174. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30175. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30176. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30177. }
  30178. this.currentFrame = currentFrame;
  30179. // Try to get a hash to find the right key
  30180. 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));
  30181. if (this._keys[startKey].frame >= currentFrame) {
  30182. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  30183. startKey--;
  30184. }
  30185. }
  30186. for (var key = startKey; key < this._keys.length; key++) {
  30187. if (this._keys[key + 1].frame >= currentFrame) {
  30188. var startValue = this._getKeyValue(this._keys[key].value);
  30189. var endValue = this._getKeyValue(this._keys[key + 1].value);
  30190. // gradient : percent of currentFrame between the frame inf and the frame sup
  30191. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  30192. // check for easingFunction and correction of gradient
  30193. if (this._easingFunction != null) {
  30194. gradient = this._easingFunction.ease(gradient);
  30195. }
  30196. switch (this.dataType) {
  30197. // Float
  30198. case Animation.ANIMATIONTYPE_FLOAT:
  30199. switch (loopMode) {
  30200. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30201. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30202. return this.floatInterpolateFunction(startValue, endValue, gradient);
  30203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30204. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  30205. }
  30206. break;
  30207. // Quaternion
  30208. case Animation.ANIMATIONTYPE_QUATERNION:
  30209. var quaternion = null;
  30210. switch (loopMode) {
  30211. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30212. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30213. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30214. break;
  30215. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30216. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30217. break;
  30218. }
  30219. return quaternion;
  30220. // Vector3
  30221. case Animation.ANIMATIONTYPE_VECTOR3:
  30222. switch (loopMode) {
  30223. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30224. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30225. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  30226. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30227. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30228. }
  30229. // Vector2
  30230. case Animation.ANIMATIONTYPE_VECTOR2:
  30231. switch (loopMode) {
  30232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30234. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  30235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30236. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30237. }
  30238. // Size
  30239. case Animation.ANIMATIONTYPE_SIZE:
  30240. switch (loopMode) {
  30241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30243. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30245. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30246. }
  30247. // Color3
  30248. case Animation.ANIMATIONTYPE_COLOR3:
  30249. switch (loopMode) {
  30250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30252. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30253. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30254. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30255. }
  30256. // Matrix
  30257. case Animation.ANIMATIONTYPE_MATRIX:
  30258. switch (loopMode) {
  30259. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30260. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30261. if (this.allowMatricesInterpolation) {
  30262. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30263. }
  30264. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30265. return startValue;
  30266. }
  30267. default:
  30268. break;
  30269. }
  30270. break;
  30271. }
  30272. }
  30273. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30274. };
  30275. Animation.prototype.setValue = function (currentValue, blend) {
  30276. if (blend === void 0) { blend = false; }
  30277. // Set value
  30278. var path;
  30279. var destination;
  30280. if (this.targetPropertyPath.length > 1) {
  30281. var property = this._target[this.targetPropertyPath[0]];
  30282. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30283. property = property[this.targetPropertyPath[index]];
  30284. }
  30285. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30286. destination = property;
  30287. }
  30288. else {
  30289. path = this.targetPropertyPath[0];
  30290. destination = this._target;
  30291. }
  30292. // Blending
  30293. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30294. if (!this._originalBlendValue) {
  30295. if (destination[path].clone) {
  30296. this._originalBlendValue = destination[path].clone();
  30297. }
  30298. else {
  30299. this._originalBlendValue = destination[path];
  30300. }
  30301. }
  30302. if (this._originalBlendValue.prototype) {
  30303. if (this._originalBlendValue.prototype.Lerp) {
  30304. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30305. }
  30306. else {
  30307. destination[path] = currentValue;
  30308. }
  30309. }
  30310. else if (this._originalBlendValue.m) {
  30311. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30312. }
  30313. else {
  30314. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30315. }
  30316. this._blendingFactor += this.blendingSpeed;
  30317. }
  30318. else {
  30319. destination[path] = currentValue;
  30320. }
  30321. if (this._target.markAsDirty) {
  30322. this._target.markAsDirty(this.targetProperty);
  30323. }
  30324. };
  30325. Animation.prototype.goToFrame = function (frame) {
  30326. if (frame < this._keys[0].frame) {
  30327. frame = this._keys[0].frame;
  30328. }
  30329. else if (frame > this._keys[this._keys.length - 1].frame) {
  30330. frame = this._keys[this._keys.length - 1].frame;
  30331. }
  30332. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30333. this.setValue(currentValue);
  30334. };
  30335. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30336. if (blend === void 0) { blend = false; }
  30337. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30338. this._stopped = true;
  30339. return false;
  30340. }
  30341. var returnValue = true;
  30342. // Adding a start key at frame 0 if missing
  30343. if (this._keys[0].frame !== 0) {
  30344. var newKey = { frame: 0, value: this._keys[0].value };
  30345. this._keys.splice(0, 0, newKey);
  30346. }
  30347. // Check limits
  30348. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30349. from = this._keys[0].frame;
  30350. }
  30351. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30352. to = this._keys[this._keys.length - 1].frame;
  30353. }
  30354. //to and from cannot be the same key
  30355. if (from === to) {
  30356. from++;
  30357. }
  30358. // Compute ratio
  30359. var range = to - from;
  30360. var offsetValue;
  30361. // ratio represents the frame delta between from and to
  30362. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30363. var highLimitValue = 0;
  30364. if (ratio > range && !loop) {
  30365. returnValue = false;
  30366. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30367. }
  30368. else {
  30369. // Get max value if required
  30370. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30371. var keyOffset = to.toString() + from.toString();
  30372. if (!this._offsetsCache[keyOffset]) {
  30373. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30374. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30375. switch (this.dataType) {
  30376. // Float
  30377. case Animation.ANIMATIONTYPE_FLOAT:
  30378. this._offsetsCache[keyOffset] = toValue - fromValue;
  30379. break;
  30380. // Quaternion
  30381. case Animation.ANIMATIONTYPE_QUATERNION:
  30382. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30383. break;
  30384. // Vector3
  30385. case Animation.ANIMATIONTYPE_VECTOR3:
  30386. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30387. // Vector2
  30388. case Animation.ANIMATIONTYPE_VECTOR2:
  30389. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30390. // Size
  30391. case Animation.ANIMATIONTYPE_SIZE:
  30392. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30393. // Color3
  30394. case Animation.ANIMATIONTYPE_COLOR3:
  30395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30396. default:
  30397. break;
  30398. }
  30399. this._highLimitsCache[keyOffset] = toValue;
  30400. }
  30401. highLimitValue = this._highLimitsCache[keyOffset];
  30402. offsetValue = this._offsetsCache[keyOffset];
  30403. }
  30404. }
  30405. if (offsetValue === undefined) {
  30406. switch (this.dataType) {
  30407. // Float
  30408. case Animation.ANIMATIONTYPE_FLOAT:
  30409. offsetValue = 0;
  30410. break;
  30411. // Quaternion
  30412. case Animation.ANIMATIONTYPE_QUATERNION:
  30413. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30414. break;
  30415. // Vector3
  30416. case Animation.ANIMATIONTYPE_VECTOR3:
  30417. offsetValue = BABYLON.Vector3.Zero();
  30418. break;
  30419. // Vector2
  30420. case Animation.ANIMATIONTYPE_VECTOR2:
  30421. offsetValue = BABYLON.Vector2.Zero();
  30422. break;
  30423. // Size
  30424. case Animation.ANIMATIONTYPE_SIZE:
  30425. offsetValue = BABYLON.Size.Zero();
  30426. break;
  30427. // Color3
  30428. case Animation.ANIMATIONTYPE_COLOR3:
  30429. offsetValue = BABYLON.Color3.Black();
  30430. }
  30431. }
  30432. // Compute value
  30433. var repeatCount = (ratio / range) >> 0;
  30434. var currentFrame = returnValue ? from + ratio % range : to;
  30435. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30436. // Set value
  30437. this.setValue(currentValue);
  30438. // Check events
  30439. for (var index = 0; index < this._events.length; index++) {
  30440. if (currentFrame >= this._events[index].frame) {
  30441. var event = this._events[index];
  30442. if (!event.isDone) {
  30443. // If event should be done only once, remove it.
  30444. if (event.onlyOnce) {
  30445. this._events.splice(index, 1);
  30446. index--;
  30447. }
  30448. event.isDone = true;
  30449. event.action();
  30450. } // Don't do anything if the event has already be done.
  30451. }
  30452. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30453. // reset event, the animation is looping
  30454. this._events[index].isDone = false;
  30455. }
  30456. }
  30457. if (!returnValue) {
  30458. this._stopped = true;
  30459. }
  30460. return returnValue;
  30461. };
  30462. Animation.prototype.serialize = function () {
  30463. var serializationObject = {};
  30464. serializationObject.name = this.name;
  30465. serializationObject.property = this.targetProperty;
  30466. serializationObject.framePerSecond = this.framePerSecond;
  30467. serializationObject.dataType = this.dataType;
  30468. serializationObject.loopBehavior = this.loopMode;
  30469. serializationObject.enableBlending = this.enableBlending;
  30470. serializationObject.blendingSpeed = this.blendingSpeed;
  30471. var dataType = this.dataType;
  30472. serializationObject.keys = [];
  30473. var keys = this.getKeys();
  30474. for (var index = 0; index < keys.length; index++) {
  30475. var animationKey = keys[index];
  30476. var key = {};
  30477. key.frame = animationKey.frame;
  30478. switch (dataType) {
  30479. case Animation.ANIMATIONTYPE_FLOAT:
  30480. key.values = [animationKey.value];
  30481. break;
  30482. case Animation.ANIMATIONTYPE_QUATERNION:
  30483. case Animation.ANIMATIONTYPE_MATRIX:
  30484. case Animation.ANIMATIONTYPE_VECTOR3:
  30485. case Animation.ANIMATIONTYPE_COLOR3:
  30486. key.values = animationKey.value.asArray();
  30487. break;
  30488. }
  30489. serializationObject.keys.push(key);
  30490. }
  30491. serializationObject.ranges = [];
  30492. for (var name in this._ranges) {
  30493. var range = {};
  30494. range.name = name;
  30495. range.from = this._ranges[name].from;
  30496. range.to = this._ranges[name].to;
  30497. serializationObject.ranges.push(range);
  30498. }
  30499. return serializationObject;
  30500. };
  30501. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30502. get: function () {
  30503. return Animation._ANIMATIONTYPE_FLOAT;
  30504. },
  30505. enumerable: true,
  30506. configurable: true
  30507. });
  30508. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30509. get: function () {
  30510. return Animation._ANIMATIONTYPE_VECTOR3;
  30511. },
  30512. enumerable: true,
  30513. configurable: true
  30514. });
  30515. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30516. get: function () {
  30517. return Animation._ANIMATIONTYPE_VECTOR2;
  30518. },
  30519. enumerable: true,
  30520. configurable: true
  30521. });
  30522. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30523. get: function () {
  30524. return Animation._ANIMATIONTYPE_SIZE;
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30530. get: function () {
  30531. return Animation._ANIMATIONTYPE_QUATERNION;
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30537. get: function () {
  30538. return Animation._ANIMATIONTYPE_MATRIX;
  30539. },
  30540. enumerable: true,
  30541. configurable: true
  30542. });
  30543. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30544. get: function () {
  30545. return Animation._ANIMATIONTYPE_COLOR3;
  30546. },
  30547. enumerable: true,
  30548. configurable: true
  30549. });
  30550. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30551. get: function () {
  30552. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30553. },
  30554. enumerable: true,
  30555. configurable: true
  30556. });
  30557. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30558. get: function () {
  30559. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30560. },
  30561. enumerable: true,
  30562. configurable: true
  30563. });
  30564. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30565. get: function () {
  30566. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30567. },
  30568. enumerable: true,
  30569. configurable: true
  30570. });
  30571. Animation.Parse = function (parsedAnimation) {
  30572. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30573. var dataType = parsedAnimation.dataType;
  30574. var keys = [];
  30575. var data;
  30576. var index;
  30577. if (parsedAnimation.enableBlending) {
  30578. animation.enableBlending = parsedAnimation.enableBlending;
  30579. }
  30580. if (parsedAnimation.blendingSpeed) {
  30581. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30582. }
  30583. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30584. var key = parsedAnimation.keys[index];
  30585. switch (dataType) {
  30586. case Animation.ANIMATIONTYPE_FLOAT:
  30587. data = key.values[0];
  30588. break;
  30589. case Animation.ANIMATIONTYPE_QUATERNION:
  30590. data = BABYLON.Quaternion.FromArray(key.values);
  30591. break;
  30592. case Animation.ANIMATIONTYPE_MATRIX:
  30593. data = BABYLON.Matrix.FromArray(key.values);
  30594. break;
  30595. case Animation.ANIMATIONTYPE_COLOR3:
  30596. data = BABYLON.Color3.FromArray(key.values);
  30597. break;
  30598. case Animation.ANIMATIONTYPE_VECTOR3:
  30599. default:
  30600. data = BABYLON.Vector3.FromArray(key.values);
  30601. break;
  30602. }
  30603. keys.push({
  30604. frame: key.frame,
  30605. value: data
  30606. });
  30607. }
  30608. animation.setKeys(keys);
  30609. if (parsedAnimation.ranges) {
  30610. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30611. data = parsedAnimation.ranges[index];
  30612. animation.createRange(data.name, data.from, data.to);
  30613. }
  30614. }
  30615. return animation;
  30616. };
  30617. Animation.AppendSerializedAnimations = function (source, destination) {
  30618. if (source.animations) {
  30619. destination.animations = [];
  30620. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30621. var animation = source.animations[animationIndex];
  30622. destination.animations.push(animation.serialize());
  30623. }
  30624. }
  30625. };
  30626. return Animation;
  30627. }());
  30628. // Statics
  30629. Animation._ANIMATIONTYPE_FLOAT = 0;
  30630. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30631. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30632. Animation._ANIMATIONTYPE_MATRIX = 3;
  30633. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30634. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30635. Animation._ANIMATIONTYPE_SIZE = 6;
  30636. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30637. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30638. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30639. BABYLON.Animation = Animation;
  30640. })(BABYLON || (BABYLON = {}));
  30641. //# sourceMappingURL=babylon.animation.js.map
  30642. var BABYLON;
  30643. (function (BABYLON) {
  30644. var Animatable = (function () {
  30645. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30646. if (fromFrame === void 0) { fromFrame = 0; }
  30647. if (toFrame === void 0) { toFrame = 100; }
  30648. if (loopAnimation === void 0) { loopAnimation = false; }
  30649. if (speedRatio === void 0) { speedRatio = 1.0; }
  30650. this.target = target;
  30651. this.fromFrame = fromFrame;
  30652. this.toFrame = toFrame;
  30653. this.loopAnimation = loopAnimation;
  30654. this.speedRatio = speedRatio;
  30655. this.onAnimationEnd = onAnimationEnd;
  30656. this._animations = new Array();
  30657. this._paused = false;
  30658. this.animationStarted = false;
  30659. if (animations) {
  30660. this.appendAnimations(target, animations);
  30661. }
  30662. this._scene = scene;
  30663. scene._activeAnimatables.push(this);
  30664. }
  30665. // Methods
  30666. Animatable.prototype.getAnimations = function () {
  30667. return this._animations;
  30668. };
  30669. Animatable.prototype.appendAnimations = function (target, animations) {
  30670. for (var index = 0; index < animations.length; index++) {
  30671. var animation = animations[index];
  30672. animation._target = target;
  30673. this._animations.push(animation);
  30674. }
  30675. };
  30676. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30677. var animations = this._animations;
  30678. for (var index = 0; index < animations.length; index++) {
  30679. if (animations[index].targetProperty === property) {
  30680. return animations[index];
  30681. }
  30682. }
  30683. return null;
  30684. };
  30685. Animatable.prototype.reset = function () {
  30686. var animations = this._animations;
  30687. for (var index = 0; index < animations.length; index++) {
  30688. animations[index].reset();
  30689. }
  30690. this._localDelayOffset = null;
  30691. this._pausedDelay = null;
  30692. };
  30693. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30694. var animations = this._animations;
  30695. for (var index = 0; index < animations.length; index++) {
  30696. animations[index].enableBlending = true;
  30697. animations[index].blendingSpeed = blendingSpeed;
  30698. }
  30699. };
  30700. Animatable.prototype.disableBlending = function () {
  30701. var animations = this._animations;
  30702. for (var index = 0; index < animations.length; index++) {
  30703. animations[index].enableBlending = false;
  30704. }
  30705. };
  30706. Animatable.prototype.goToFrame = function (frame) {
  30707. var animations = this._animations;
  30708. if (animations[0]) {
  30709. var fps = animations[0].framePerSecond;
  30710. var currentFrame = animations[0].currentFrame;
  30711. var adjustTime = frame - currentFrame;
  30712. var delay = adjustTime * 1000 / fps;
  30713. this._localDelayOffset -= delay;
  30714. }
  30715. for (var index = 0; index < animations.length; index++) {
  30716. animations[index].goToFrame(frame);
  30717. }
  30718. };
  30719. Animatable.prototype.pause = function () {
  30720. if (this._paused) {
  30721. return;
  30722. }
  30723. this._paused = true;
  30724. };
  30725. Animatable.prototype.restart = function () {
  30726. this._paused = false;
  30727. };
  30728. Animatable.prototype.stop = function (animationName) {
  30729. if (animationName) {
  30730. var idx = this._scene._activeAnimatables.indexOf(this);
  30731. if (idx > -1) {
  30732. var animations = this._animations;
  30733. var numberOfAnimationsStopped = 0;
  30734. for (var index = animations.length - 1; index >= 0; index--) {
  30735. if (typeof animationName === "string" && animations[index].name != animationName) {
  30736. continue;
  30737. }
  30738. animations[index].reset();
  30739. animations.splice(index, 1);
  30740. numberOfAnimationsStopped++;
  30741. }
  30742. if (animations.length == numberOfAnimationsStopped) {
  30743. this._scene._activeAnimatables.splice(idx, 1);
  30744. if (this.onAnimationEnd) {
  30745. this.onAnimationEnd();
  30746. }
  30747. }
  30748. }
  30749. }
  30750. else {
  30751. var index = this._scene._activeAnimatables.indexOf(this);
  30752. if (index > -1) {
  30753. this._scene._activeAnimatables.splice(index, 1);
  30754. var animations = this._animations;
  30755. for (var index = 0; index < animations.length; index++) {
  30756. animations[index].reset();
  30757. }
  30758. if (this.onAnimationEnd) {
  30759. this.onAnimationEnd();
  30760. }
  30761. }
  30762. }
  30763. };
  30764. Animatable.prototype._animate = function (delay) {
  30765. if (this._paused) {
  30766. this.animationStarted = false;
  30767. if (!this._pausedDelay) {
  30768. this._pausedDelay = delay;
  30769. }
  30770. return true;
  30771. }
  30772. if (!this._localDelayOffset) {
  30773. this._localDelayOffset = delay;
  30774. }
  30775. else if (this._pausedDelay) {
  30776. this._localDelayOffset += delay - this._pausedDelay;
  30777. this._pausedDelay = null;
  30778. }
  30779. // Animating
  30780. var running = false;
  30781. var animations = this._animations;
  30782. var index;
  30783. for (index = 0; index < animations.length; index++) {
  30784. var animation = animations[index];
  30785. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30786. running = running || isRunning;
  30787. }
  30788. this.animationStarted = running;
  30789. if (!running) {
  30790. // Remove from active animatables
  30791. index = this._scene._activeAnimatables.indexOf(this);
  30792. this._scene._activeAnimatables.splice(index, 1);
  30793. }
  30794. if (!running && this.onAnimationEnd) {
  30795. this.onAnimationEnd();
  30796. this.onAnimationEnd = null;
  30797. }
  30798. return running;
  30799. };
  30800. return Animatable;
  30801. }());
  30802. BABYLON.Animatable = Animatable;
  30803. })(BABYLON || (BABYLON = {}));
  30804. //# sourceMappingURL=babylon.animatable.js.map
  30805. var BABYLON;
  30806. (function (BABYLON) {
  30807. var EasingFunction = (function () {
  30808. function EasingFunction() {
  30809. // Properties
  30810. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30811. }
  30812. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30813. get: function () {
  30814. return EasingFunction._EASINGMODE_EASEIN;
  30815. },
  30816. enumerable: true,
  30817. configurable: true
  30818. });
  30819. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30820. get: function () {
  30821. return EasingFunction._EASINGMODE_EASEOUT;
  30822. },
  30823. enumerable: true,
  30824. configurable: true
  30825. });
  30826. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30827. get: function () {
  30828. return EasingFunction._EASINGMODE_EASEINOUT;
  30829. },
  30830. enumerable: true,
  30831. configurable: true
  30832. });
  30833. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30834. var n = Math.min(Math.max(easingMode, 0), 2);
  30835. this._easingMode = n;
  30836. };
  30837. EasingFunction.prototype.getEasingMode = function () {
  30838. return this._easingMode;
  30839. };
  30840. EasingFunction.prototype.easeInCore = function (gradient) {
  30841. throw new Error('You must implement this method');
  30842. };
  30843. EasingFunction.prototype.ease = function (gradient) {
  30844. switch (this._easingMode) {
  30845. case EasingFunction.EASINGMODE_EASEIN:
  30846. return this.easeInCore(gradient);
  30847. case EasingFunction.EASINGMODE_EASEOUT:
  30848. return (1 - this.easeInCore(1 - gradient));
  30849. }
  30850. if (gradient >= 0.5) {
  30851. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30852. }
  30853. return (this.easeInCore(gradient * 2) * 0.5);
  30854. };
  30855. return EasingFunction;
  30856. }());
  30857. //Statics
  30858. EasingFunction._EASINGMODE_EASEIN = 0;
  30859. EasingFunction._EASINGMODE_EASEOUT = 1;
  30860. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30861. BABYLON.EasingFunction = EasingFunction;
  30862. var CircleEase = (function (_super) {
  30863. __extends(CircleEase, _super);
  30864. function CircleEase() {
  30865. return _super !== null && _super.apply(this, arguments) || this;
  30866. }
  30867. CircleEase.prototype.easeInCore = function (gradient) {
  30868. gradient = Math.max(0, Math.min(1, gradient));
  30869. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30870. };
  30871. return CircleEase;
  30872. }(EasingFunction));
  30873. BABYLON.CircleEase = CircleEase;
  30874. var BackEase = (function (_super) {
  30875. __extends(BackEase, _super);
  30876. function BackEase(amplitude) {
  30877. if (amplitude === void 0) { amplitude = 1; }
  30878. var _this = _super.call(this) || this;
  30879. _this.amplitude = amplitude;
  30880. return _this;
  30881. }
  30882. BackEase.prototype.easeInCore = function (gradient) {
  30883. var num = Math.max(0, this.amplitude);
  30884. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30885. };
  30886. return BackEase;
  30887. }(EasingFunction));
  30888. BABYLON.BackEase = BackEase;
  30889. var BounceEase = (function (_super) {
  30890. __extends(BounceEase, _super);
  30891. function BounceEase(bounces, bounciness) {
  30892. if (bounces === void 0) { bounces = 3; }
  30893. if (bounciness === void 0) { bounciness = 2; }
  30894. var _this = _super.call(this) || this;
  30895. _this.bounces = bounces;
  30896. _this.bounciness = bounciness;
  30897. return _this;
  30898. }
  30899. BounceEase.prototype.easeInCore = function (gradient) {
  30900. var y = Math.max(0.0, this.bounces);
  30901. var bounciness = this.bounciness;
  30902. if (bounciness <= 1.0) {
  30903. bounciness = 1.001;
  30904. }
  30905. var num9 = Math.pow(bounciness, y);
  30906. var num5 = 1.0 - bounciness;
  30907. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30908. var num15 = gradient * num4;
  30909. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30910. var num3 = Math.floor(num65);
  30911. var num13 = num3 + 1.0;
  30912. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30913. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30914. var num7 = (num8 + num12) * 0.5;
  30915. var num6 = gradient - num7;
  30916. var num2 = num7 - num8;
  30917. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30918. };
  30919. return BounceEase;
  30920. }(EasingFunction));
  30921. BABYLON.BounceEase = BounceEase;
  30922. var CubicEase = (function (_super) {
  30923. __extends(CubicEase, _super);
  30924. function CubicEase() {
  30925. return _super !== null && _super.apply(this, arguments) || this;
  30926. }
  30927. CubicEase.prototype.easeInCore = function (gradient) {
  30928. return (gradient * gradient * gradient);
  30929. };
  30930. return CubicEase;
  30931. }(EasingFunction));
  30932. BABYLON.CubicEase = CubicEase;
  30933. var ElasticEase = (function (_super) {
  30934. __extends(ElasticEase, _super);
  30935. function ElasticEase(oscillations, springiness) {
  30936. if (oscillations === void 0) { oscillations = 3; }
  30937. if (springiness === void 0) { springiness = 3; }
  30938. var _this = _super.call(this) || this;
  30939. _this.oscillations = oscillations;
  30940. _this.springiness = springiness;
  30941. return _this;
  30942. }
  30943. ElasticEase.prototype.easeInCore = function (gradient) {
  30944. var num2;
  30945. var num3 = Math.max(0.0, this.oscillations);
  30946. var num = Math.max(0.0, this.springiness);
  30947. if (num == 0) {
  30948. num2 = gradient;
  30949. }
  30950. else {
  30951. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30952. }
  30953. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30954. };
  30955. return ElasticEase;
  30956. }(EasingFunction));
  30957. BABYLON.ElasticEase = ElasticEase;
  30958. var ExponentialEase = (function (_super) {
  30959. __extends(ExponentialEase, _super);
  30960. function ExponentialEase(exponent) {
  30961. if (exponent === void 0) { exponent = 2; }
  30962. var _this = _super.call(this) || this;
  30963. _this.exponent = exponent;
  30964. return _this;
  30965. }
  30966. ExponentialEase.prototype.easeInCore = function (gradient) {
  30967. if (this.exponent <= 0) {
  30968. return gradient;
  30969. }
  30970. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30971. };
  30972. return ExponentialEase;
  30973. }(EasingFunction));
  30974. BABYLON.ExponentialEase = ExponentialEase;
  30975. var PowerEase = (function (_super) {
  30976. __extends(PowerEase, _super);
  30977. function PowerEase(power) {
  30978. if (power === void 0) { power = 2; }
  30979. var _this = _super.call(this) || this;
  30980. _this.power = power;
  30981. return _this;
  30982. }
  30983. PowerEase.prototype.easeInCore = function (gradient) {
  30984. var y = Math.max(0.0, this.power);
  30985. return Math.pow(gradient, y);
  30986. };
  30987. return PowerEase;
  30988. }(EasingFunction));
  30989. BABYLON.PowerEase = PowerEase;
  30990. var QuadraticEase = (function (_super) {
  30991. __extends(QuadraticEase, _super);
  30992. function QuadraticEase() {
  30993. return _super !== null && _super.apply(this, arguments) || this;
  30994. }
  30995. QuadraticEase.prototype.easeInCore = function (gradient) {
  30996. return (gradient * gradient);
  30997. };
  30998. return QuadraticEase;
  30999. }(EasingFunction));
  31000. BABYLON.QuadraticEase = QuadraticEase;
  31001. var QuarticEase = (function (_super) {
  31002. __extends(QuarticEase, _super);
  31003. function QuarticEase() {
  31004. return _super !== null && _super.apply(this, arguments) || this;
  31005. }
  31006. QuarticEase.prototype.easeInCore = function (gradient) {
  31007. return (gradient * gradient * gradient * gradient);
  31008. };
  31009. return QuarticEase;
  31010. }(EasingFunction));
  31011. BABYLON.QuarticEase = QuarticEase;
  31012. var QuinticEase = (function (_super) {
  31013. __extends(QuinticEase, _super);
  31014. function QuinticEase() {
  31015. return _super !== null && _super.apply(this, arguments) || this;
  31016. }
  31017. QuinticEase.prototype.easeInCore = function (gradient) {
  31018. return (gradient * gradient * gradient * gradient * gradient);
  31019. };
  31020. return QuinticEase;
  31021. }(EasingFunction));
  31022. BABYLON.QuinticEase = QuinticEase;
  31023. var SineEase = (function (_super) {
  31024. __extends(SineEase, _super);
  31025. function SineEase() {
  31026. return _super !== null && _super.apply(this, arguments) || this;
  31027. }
  31028. SineEase.prototype.easeInCore = function (gradient) {
  31029. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31030. };
  31031. return SineEase;
  31032. }(EasingFunction));
  31033. BABYLON.SineEase = SineEase;
  31034. var BezierCurveEase = (function (_super) {
  31035. __extends(BezierCurveEase, _super);
  31036. function BezierCurveEase(x1, y1, x2, y2) {
  31037. if (x1 === void 0) { x1 = 0; }
  31038. if (y1 === void 0) { y1 = 0; }
  31039. if (x2 === void 0) { x2 = 1; }
  31040. if (y2 === void 0) { y2 = 1; }
  31041. var _this = _super.call(this) || this;
  31042. _this.x1 = x1;
  31043. _this.y1 = y1;
  31044. _this.x2 = x2;
  31045. _this.y2 = y2;
  31046. return _this;
  31047. }
  31048. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31049. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31050. };
  31051. return BezierCurveEase;
  31052. }(EasingFunction));
  31053. BABYLON.BezierCurveEase = BezierCurveEase;
  31054. })(BABYLON || (BABYLON = {}));
  31055. //# sourceMappingURL=babylon.easing.js.map
  31056. var BABYLON;
  31057. (function (BABYLON) {
  31058. var Bone = (function (_super) {
  31059. __extends(Bone, _super);
  31060. function Bone(name, skeleton, parentBone, matrix, restPose) {
  31061. var _this = _super.call(this, name, skeleton.getScene()) || this;
  31062. _this.name = name;
  31063. _this.children = new Array();
  31064. _this.animations = new Array();
  31065. _this._worldTransform = new BABYLON.Matrix();
  31066. _this._absoluteTransform = new BABYLON.Matrix();
  31067. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  31068. _this._scaleMatrix = BABYLON.Matrix.Identity();
  31069. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  31070. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  31071. _this._scalingDeterminant = 1;
  31072. _this._syncScaleVector = function () {
  31073. var lm = this.getLocalMatrix();
  31074. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  31075. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  31076. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  31077. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  31078. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  31079. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  31080. this._scaleVector.x = xs * Math.sqrt(xsq);
  31081. this._scaleVector.y = ys * Math.sqrt(ysq);
  31082. this._scaleVector.z = zs * Math.sqrt(zsq);
  31083. if (this._parent) {
  31084. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  31085. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  31086. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  31087. }
  31088. 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);
  31089. };
  31090. _this._skeleton = skeleton;
  31091. _this._matrix = matrix;
  31092. _this._baseMatrix = matrix;
  31093. _this._restPose = restPose ? restPose : matrix.clone();
  31094. skeleton.bones.push(_this);
  31095. if (parentBone) {
  31096. _this._parent = parentBone;
  31097. parentBone.children.push(_this);
  31098. }
  31099. else {
  31100. _this._parent = null;
  31101. }
  31102. _this._updateDifferenceMatrix();
  31103. if (_this.getAbsoluteTransform().determinant() < 0) {
  31104. _this._scalingDeterminant *= -1;
  31105. }
  31106. return _this;
  31107. }
  31108. // Members
  31109. Bone.prototype.getParent = function () {
  31110. return this._parent;
  31111. };
  31112. Bone.prototype.getLocalMatrix = function () {
  31113. return this._matrix;
  31114. };
  31115. Bone.prototype.getBaseMatrix = function () {
  31116. return this._baseMatrix;
  31117. };
  31118. Bone.prototype.getRestPose = function () {
  31119. return this._restPose;
  31120. };
  31121. Bone.prototype.returnToRest = function () {
  31122. this.updateMatrix(this._restPose.clone());
  31123. };
  31124. Bone.prototype.getWorldMatrix = function () {
  31125. return this._worldTransform;
  31126. };
  31127. Bone.prototype.getInvertedAbsoluteTransform = function () {
  31128. return this._invertedAbsoluteTransform;
  31129. };
  31130. Bone.prototype.getAbsoluteTransform = function () {
  31131. return this._absoluteTransform;
  31132. };
  31133. // Methods
  31134. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  31135. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  31136. this._baseMatrix = matrix.clone();
  31137. this._matrix = matrix.clone();
  31138. this._skeleton._markAsDirty();
  31139. if (updateDifferenceMatrix) {
  31140. this._updateDifferenceMatrix();
  31141. }
  31142. };
  31143. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  31144. if (!rootMatrix) {
  31145. rootMatrix = this._baseMatrix;
  31146. }
  31147. if (this._parent) {
  31148. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31149. }
  31150. else {
  31151. this._absoluteTransform.copyFrom(rootMatrix);
  31152. }
  31153. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  31154. for (var index = 0; index < this.children.length; index++) {
  31155. this.children[index]._updateDifferenceMatrix();
  31156. }
  31157. };
  31158. Bone.prototype.markAsDirty = function () {
  31159. this._currentRenderId++;
  31160. this._skeleton._markAsDirty();
  31161. };
  31162. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  31163. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31164. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  31165. // all animation may be coming from a library skeleton, so may need to create animation
  31166. if (this.animations.length === 0) {
  31167. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  31168. this.animations[0].setKeys([]);
  31169. }
  31170. // get animation info / verify there is such a range from the source bone
  31171. var sourceRange = source.animations[0].getRange(rangeName);
  31172. if (!sourceRange) {
  31173. return false;
  31174. }
  31175. var from = sourceRange.from;
  31176. var to = sourceRange.to;
  31177. var sourceKeys = source.animations[0].getKeys();
  31178. // rescaling prep
  31179. var sourceBoneLength = source.length;
  31180. var sourceParent = source.getParent();
  31181. var parent = this.getParent();
  31182. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  31183. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  31184. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  31185. var destKeys = this.animations[0].getKeys();
  31186. // loop vars declaration
  31187. var orig;
  31188. var origTranslation;
  31189. var mat;
  31190. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  31191. orig = sourceKeys[key];
  31192. if (orig.frame >= from && orig.frame <= to) {
  31193. if (rescaleAsRequired) {
  31194. mat = orig.value.clone();
  31195. // scale based on parent ratio, when bone has parent
  31196. if (parentScalingReqd) {
  31197. origTranslation = mat.getTranslation();
  31198. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  31199. }
  31200. else if (dimensionsScalingReqd) {
  31201. origTranslation = mat.getTranslation();
  31202. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  31203. }
  31204. else {
  31205. mat = orig.value;
  31206. }
  31207. }
  31208. else {
  31209. mat = orig.value;
  31210. }
  31211. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  31212. }
  31213. }
  31214. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  31215. return true;
  31216. };
  31217. Bone.prototype.translate = function (vec, space, mesh) {
  31218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31219. var lm = this.getLocalMatrix();
  31220. if (space == BABYLON.Space.LOCAL) {
  31221. lm.m[12] += vec.x;
  31222. lm.m[13] += vec.y;
  31223. lm.m[14] += vec.z;
  31224. }
  31225. else {
  31226. this._skeleton.computeAbsoluteTransforms();
  31227. var tmat = BABYLON.Tmp.Matrix[0];
  31228. var tvec = BABYLON.Tmp.Vector3[0];
  31229. if (mesh) {
  31230. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31231. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31232. }
  31233. else {
  31234. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31235. }
  31236. tmat.m[12] = 0;
  31237. tmat.m[13] = 0;
  31238. tmat.m[14] = 0;
  31239. tmat.invert();
  31240. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  31241. lm.m[12] += tvec.x;
  31242. lm.m[13] += tvec.y;
  31243. lm.m[14] += tvec.z;
  31244. }
  31245. this.markAsDirty();
  31246. };
  31247. Bone.prototype.setPosition = function (position, space, mesh) {
  31248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31249. var lm = this.getLocalMatrix();
  31250. if (space == BABYLON.Space.LOCAL) {
  31251. lm.m[12] = position.x;
  31252. lm.m[13] = position.y;
  31253. lm.m[14] = position.z;
  31254. }
  31255. else {
  31256. this._skeleton.computeAbsoluteTransforms();
  31257. var tmat = BABYLON.Tmp.Matrix[0];
  31258. var vec = BABYLON.Tmp.Vector3[0];
  31259. if (mesh) {
  31260. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31261. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31262. }
  31263. else {
  31264. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31265. }
  31266. tmat.invert();
  31267. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  31268. lm.m[12] = vec.x;
  31269. lm.m[13] = vec.y;
  31270. lm.m[14] = vec.z;
  31271. }
  31272. this.markAsDirty();
  31273. };
  31274. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  31275. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  31276. };
  31277. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  31278. if (scaleChildren === void 0) { scaleChildren = false; }
  31279. if (this.animations[0] && !this.animations[0].isStopped()) {
  31280. if (!scaleChildren) {
  31281. this._negateScaleChildren.x = 1 / x;
  31282. this._negateScaleChildren.y = 1 / y;
  31283. this._negateScaleChildren.z = 1 / z;
  31284. }
  31285. this._syncScaleVector();
  31286. }
  31287. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  31288. };
  31289. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  31290. if (scaleChildren === void 0) { scaleChildren = false; }
  31291. var locMat = this.getLocalMatrix();
  31292. var origLocMat = BABYLON.Tmp.Matrix[0];
  31293. origLocMat.copyFrom(locMat);
  31294. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  31295. origLocMatInv.copyFrom(origLocMat);
  31296. origLocMatInv.invert();
  31297. var scaleMat = BABYLON.Tmp.Matrix[2];
  31298. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  31299. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  31300. this._scaleVector.x *= x;
  31301. this._scaleVector.y *= y;
  31302. this._scaleVector.z *= z;
  31303. locMat.multiplyToRef(origLocMatInv, locMat);
  31304. locMat.multiplyToRef(scaleMat, locMat);
  31305. locMat.multiplyToRef(origLocMat, locMat);
  31306. var parent = this.getParent();
  31307. if (parent) {
  31308. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  31309. }
  31310. else {
  31311. this.getAbsoluteTransform().copyFrom(locMat);
  31312. }
  31313. var len = this.children.length;
  31314. scaleMat.invert();
  31315. for (var i = 0; i < len; i++) {
  31316. var child = this.children[i];
  31317. var cm = child.getLocalMatrix();
  31318. cm.multiplyToRef(scaleMat, cm);
  31319. var lm = child.getLocalMatrix();
  31320. lm.m[12] *= x;
  31321. lm.m[13] *= y;
  31322. lm.m[14] *= z;
  31323. }
  31324. this.computeAbsoluteTransforms();
  31325. if (scaleChildren) {
  31326. for (var i = 0; i < len; i++) {
  31327. this.children[i].scale(x, y, z, scaleChildren);
  31328. }
  31329. }
  31330. this.markAsDirty();
  31331. };
  31332. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  31333. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31334. var rotMat = BABYLON.Tmp.Matrix[0];
  31335. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  31336. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31337. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31338. rotMatInv.multiplyToRef(rotMat, rotMat);
  31339. this._rotateWithMatrix(rotMat, space, mesh);
  31340. };
  31341. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  31342. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31343. var rmat = BABYLON.Tmp.Matrix[0];
  31344. rmat.m[12] = 0;
  31345. rmat.m[13] = 0;
  31346. rmat.m[14] = 0;
  31347. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  31348. this._rotateWithMatrix(rmat, space, mesh);
  31349. };
  31350. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  31351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31352. var rotMat = BABYLON.Tmp.Matrix[0];
  31353. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  31354. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31355. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31356. rotMatInv.multiplyToRef(rotMat, rotMat);
  31357. this._rotateWithMatrix(rotMat, space, mesh);
  31358. };
  31359. Bone.prototype.setRotation = function (rotation, space, mesh) {
  31360. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31361. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  31362. };
  31363. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  31364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31365. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31366. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31367. var rotMat = BABYLON.Tmp.Matrix[1];
  31368. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  31369. rotMatInv.multiplyToRef(rotMat, rotMat);
  31370. this._rotateWithMatrix(rotMat, space, mesh);
  31371. };
  31372. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  31373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31374. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31375. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31376. var rotMat2 = BABYLON.Tmp.Matrix[1];
  31377. rotMat2.copyFrom(rotMat);
  31378. rotMatInv.multiplyToRef(rotMat, rotMat2);
  31379. this._rotateWithMatrix(rotMat2, space, mesh);
  31380. };
  31381. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  31382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31383. var lmat = this.getLocalMatrix();
  31384. var lx = lmat.m[12];
  31385. var ly = lmat.m[13];
  31386. var lz = lmat.m[14];
  31387. var parent = this.getParent();
  31388. var parentScale = BABYLON.Tmp.Matrix[3];
  31389. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  31390. if (parent) {
  31391. if (space == BABYLON.Space.WORLD) {
  31392. if (mesh) {
  31393. parentScale.copyFrom(mesh.getWorldMatrix());
  31394. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  31395. }
  31396. else {
  31397. parentScale.copyFrom(parent.getAbsoluteTransform());
  31398. }
  31399. }
  31400. else {
  31401. parentScale = parent._scaleMatrix;
  31402. }
  31403. parentScaleInv.copyFrom(parentScale);
  31404. parentScaleInv.invert();
  31405. lmat.multiplyToRef(parentScale, lmat);
  31406. lmat.multiplyToRef(rmat, lmat);
  31407. lmat.multiplyToRef(parentScaleInv, lmat);
  31408. }
  31409. else {
  31410. if (space == BABYLON.Space.WORLD && mesh) {
  31411. parentScale.copyFrom(mesh.getWorldMatrix());
  31412. parentScaleInv.copyFrom(parentScale);
  31413. parentScaleInv.invert();
  31414. lmat.multiplyToRef(parentScale, lmat);
  31415. lmat.multiplyToRef(rmat, lmat);
  31416. lmat.multiplyToRef(parentScaleInv, lmat);
  31417. }
  31418. else {
  31419. lmat.multiplyToRef(rmat, lmat);
  31420. }
  31421. }
  31422. lmat.m[12] = lx;
  31423. lmat.m[13] = ly;
  31424. lmat.m[14] = lz;
  31425. this.computeAbsoluteTransforms();
  31426. this.markAsDirty();
  31427. };
  31428. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  31429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31430. if (space == BABYLON.Space.WORLD) {
  31431. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31432. scaleMatrix.copyFrom(this._scaleMatrix);
  31433. rotMatInv.copyFrom(this.getAbsoluteTransform());
  31434. if (mesh) {
  31435. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  31436. var meshScale = BABYLON.Tmp.Matrix[3];
  31437. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  31438. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  31439. }
  31440. rotMatInv.invert();
  31441. scaleMatrix.m[0] *= this._scalingDeterminant;
  31442. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31443. }
  31444. else {
  31445. rotMatInv.copyFrom(this.getLocalMatrix());
  31446. rotMatInv.invert();
  31447. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31448. scaleMatrix.copyFrom(this._scaleMatrix);
  31449. if (this._parent) {
  31450. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  31451. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  31452. pscaleMatrix.invert();
  31453. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  31454. }
  31455. else {
  31456. scaleMatrix.m[0] *= this._scalingDeterminant;
  31457. }
  31458. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31459. }
  31460. };
  31461. Bone.prototype.getScale = function () {
  31462. return this._scaleVector.clone();
  31463. };
  31464. Bone.prototype.getScaleToRef = function (result) {
  31465. result.copyFrom(this._scaleVector);
  31466. };
  31467. Bone.prototype.getPosition = function (space, mesh) {
  31468. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31469. var pos = BABYLON.Vector3.Zero();
  31470. this.getPositionToRef(space, mesh, pos);
  31471. return pos;
  31472. };
  31473. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  31474. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31475. if (space == BABYLON.Space.LOCAL) {
  31476. var lm = this.getLocalMatrix();
  31477. result.x = lm.m[12];
  31478. result.y = lm.m[13];
  31479. result.z = lm.m[14];
  31480. }
  31481. else {
  31482. this._skeleton.computeAbsoluteTransforms();
  31483. var tmat = BABYLON.Tmp.Matrix[0];
  31484. if (mesh) {
  31485. tmat.copyFrom(this.getAbsoluteTransform());
  31486. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31487. }
  31488. else {
  31489. tmat = this.getAbsoluteTransform();
  31490. }
  31491. result.x = tmat.m[12];
  31492. result.y = tmat.m[13];
  31493. result.z = tmat.m[14];
  31494. }
  31495. };
  31496. Bone.prototype.getAbsolutePosition = function (mesh) {
  31497. var pos = BABYLON.Vector3.Zero();
  31498. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  31499. return pos;
  31500. };
  31501. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  31502. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  31503. };
  31504. Bone.prototype.computeAbsoluteTransforms = function () {
  31505. if (this._parent) {
  31506. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31507. }
  31508. else {
  31509. this._absoluteTransform.copyFrom(this._matrix);
  31510. var poseMatrix = this._skeleton.getPoseMatrix();
  31511. if (poseMatrix) {
  31512. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  31513. }
  31514. }
  31515. var children = this.children;
  31516. var len = children.length;
  31517. for (var i = 0; i < len; i++) {
  31518. children[i].computeAbsoluteTransforms();
  31519. }
  31520. };
  31521. Bone.prototype.getDirection = function (localAxis, mesh) {
  31522. var result = BABYLON.Vector3.Zero();
  31523. this.getDirectionToRef(localAxis, mesh, result);
  31524. return result;
  31525. };
  31526. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  31527. this._skeleton.computeAbsoluteTransforms();
  31528. var mat = BABYLON.Tmp.Matrix[0];
  31529. mat.copyFrom(this.getAbsoluteTransform());
  31530. if (mesh) {
  31531. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31532. }
  31533. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  31534. result.normalize();
  31535. };
  31536. Bone.prototype.getRotation = function (space, mesh) {
  31537. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31538. var result = BABYLON.Vector3.Zero();
  31539. this.getRotationToRef(space, mesh, result);
  31540. return result;
  31541. };
  31542. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  31543. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31544. var quat = BABYLON.Tmp.Quaternion[0];
  31545. this.getRotationQuaternionToRef(space, mesh, quat);
  31546. quat.toEulerAnglesToRef(result);
  31547. };
  31548. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  31549. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31550. var result = BABYLON.Quaternion.Identity();
  31551. this.getRotationQuaternionToRef(space, mesh, result);
  31552. return result;
  31553. };
  31554. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  31555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31556. if (space == BABYLON.Space.LOCAL) {
  31557. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31558. }
  31559. else {
  31560. var mat = BABYLON.Tmp.Matrix[0];
  31561. var amat = this.getAbsoluteTransform();
  31562. if (mesh) {
  31563. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31564. }
  31565. else {
  31566. mat.copyFrom(amat);
  31567. }
  31568. mat.m[0] *= this._scalingDeterminant;
  31569. mat.m[1] *= this._scalingDeterminant;
  31570. mat.m[2] *= this._scalingDeterminant;
  31571. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31572. }
  31573. };
  31574. Bone.prototype.getRotationMatrix = function (space, mesh) {
  31575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31576. var result = BABYLON.Matrix.Identity();
  31577. this.getRotationMatrixToRef(space, mesh, result);
  31578. return result;
  31579. };
  31580. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  31581. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31582. if (space == BABYLON.Space.LOCAL) {
  31583. this.getLocalMatrix().getRotationMatrixToRef(result);
  31584. }
  31585. else {
  31586. var mat = BABYLON.Tmp.Matrix[0];
  31587. var amat = this.getAbsoluteTransform();
  31588. if (mesh) {
  31589. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31590. }
  31591. else {
  31592. mat.copyFrom(amat);
  31593. }
  31594. mat.m[0] *= this._scalingDeterminant;
  31595. mat.m[1] *= this._scalingDeterminant;
  31596. mat.m[2] *= this._scalingDeterminant;
  31597. mat.getRotationMatrixToRef(result);
  31598. }
  31599. };
  31600. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  31601. var result = BABYLON.Vector3.Zero();
  31602. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  31603. return result;
  31604. };
  31605. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  31606. this._skeleton.computeAbsoluteTransforms();
  31607. var tmat = BABYLON.Tmp.Matrix[0];
  31608. if (mesh) {
  31609. tmat.copyFrom(this.getAbsoluteTransform());
  31610. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31611. }
  31612. else {
  31613. tmat = this.getAbsoluteTransform();
  31614. }
  31615. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31616. };
  31617. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  31618. var result = BABYLON.Vector3.Zero();
  31619. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  31620. return result;
  31621. };
  31622. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  31623. this._skeleton.computeAbsoluteTransforms();
  31624. var tmat = BABYLON.Tmp.Matrix[0];
  31625. tmat.copyFrom(this.getAbsoluteTransform());
  31626. if (mesh) {
  31627. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31628. }
  31629. tmat.invert();
  31630. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31631. };
  31632. return Bone;
  31633. }(BABYLON.Node));
  31634. BABYLON.Bone = Bone;
  31635. })(BABYLON || (BABYLON = {}));
  31636. //# sourceMappingURL=babylon.bone.js.map
  31637. var BABYLON;
  31638. (function (BABYLON) {
  31639. var BoneIKController = (function () {
  31640. function BoneIKController(mesh, bone, options) {
  31641. this.targetPosition = BABYLON.Vector3.Zero();
  31642. this.poleTargetPosition = BABYLON.Vector3.Zero();
  31643. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  31644. this.poleAngle = 0;
  31645. this.slerpAmount = 1;
  31646. this._bone1Quat = BABYLON.Quaternion.Identity();
  31647. this._bone1Mat = BABYLON.Matrix.Identity();
  31648. this._bone2Ang = Math.PI;
  31649. this._maxAngle = Math.PI;
  31650. this._tmpVec1 = BABYLON.Vector3.Zero();
  31651. this._tmpVec2 = BABYLON.Vector3.Zero();
  31652. this._tmpVec3 = BABYLON.Vector3.Zero();
  31653. this._tmpVec4 = BABYLON.Vector3.Zero();
  31654. this._tmpVec5 = BABYLON.Vector3.Zero();
  31655. this._tmpMat1 = BABYLON.Matrix.Identity();
  31656. this._tmpMat2 = BABYLON.Matrix.Identity();
  31657. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  31658. this._rightHandedSystem = false;
  31659. this._bendAxis = BABYLON.Vector3.Right();
  31660. this._slerping = false;
  31661. this._bone2 = bone;
  31662. this._bone1 = bone.getParent();
  31663. this.mesh = mesh;
  31664. if (bone.getAbsoluteTransform().determinant() > 0) {
  31665. this._rightHandedSystem = true;
  31666. this._bendAxis.x = 0;
  31667. this._bendAxis.y = 0;
  31668. this._bendAxis.z = 1;
  31669. }
  31670. if (this._bone1.length) {
  31671. var boneScale1 = this._bone1.getScale();
  31672. var boneScale2 = this._bone2.getScale();
  31673. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  31674. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  31675. }
  31676. else if (this._bone1.children[0]) {
  31677. mesh.computeWorldMatrix(true);
  31678. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  31679. var pos2 = this._bone2.getAbsolutePosition(mesh);
  31680. var pos3 = this._bone1.getAbsolutePosition(mesh);
  31681. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  31682. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  31683. }
  31684. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  31685. this.maxAngle = Math.PI;
  31686. if (options) {
  31687. if (options.targetMesh) {
  31688. this.targetMesh = options.targetMesh;
  31689. this.targetMesh.computeWorldMatrix(true);
  31690. }
  31691. if (options.poleTargetMesh) {
  31692. this.poleTargetMesh = options.poleTargetMesh;
  31693. this.poleTargetMesh.computeWorldMatrix(true);
  31694. }
  31695. else if (options.poleTargetBone) {
  31696. this.poleTargetBone = options.poleTargetBone;
  31697. }
  31698. else if (this._bone1.getParent()) {
  31699. this.poleTargetBone = this._bone1.getParent();
  31700. }
  31701. if (options.poleTargetLocalOffset) {
  31702. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  31703. }
  31704. if (options.poleAngle) {
  31705. this.poleAngle = options.poleAngle;
  31706. }
  31707. if (options.bendAxis) {
  31708. this._bendAxis.copyFrom(options.bendAxis);
  31709. }
  31710. if (options.maxAngle) {
  31711. this.maxAngle = options.maxAngle;
  31712. }
  31713. if (options.slerpAmount) {
  31714. this.slerpAmount = options.slerpAmount;
  31715. }
  31716. }
  31717. }
  31718. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  31719. get: function () {
  31720. return this._maxAngle;
  31721. },
  31722. set: function (value) {
  31723. this._setMaxAngle(value);
  31724. },
  31725. enumerable: true,
  31726. configurable: true
  31727. });
  31728. BoneIKController.prototype._setMaxAngle = function (ang) {
  31729. if (ang < 0) {
  31730. ang = 0;
  31731. }
  31732. if (ang > Math.PI || ang == undefined) {
  31733. ang = Math.PI;
  31734. }
  31735. this._maxAngle = ang;
  31736. var a = this._bone1Length;
  31737. var b = this._bone2Length;
  31738. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  31739. };
  31740. BoneIKController.prototype.update = function () {
  31741. var bone1 = this._bone1;
  31742. var target = this.targetPosition;
  31743. var poleTarget = this.poleTargetPosition;
  31744. var mat1 = this._tmpMat1;
  31745. var mat2 = this._tmpMat2;
  31746. if (this.targetMesh) {
  31747. target.copyFrom(this.targetMesh.getAbsolutePosition());
  31748. }
  31749. if (this.poleTargetBone) {
  31750. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  31751. }
  31752. else if (this.poleTargetMesh) {
  31753. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  31754. }
  31755. var bonePos = this._tmpVec1;
  31756. var zaxis = this._tmpVec2;
  31757. var xaxis = this._tmpVec3;
  31758. var yaxis = this._tmpVec4;
  31759. var upAxis = this._tmpVec5;
  31760. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  31761. poleTarget.subtractToRef(bonePos, upAxis);
  31762. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  31763. upAxis.y = 1;
  31764. }
  31765. else {
  31766. upAxis.normalize();
  31767. }
  31768. target.subtractToRef(bonePos, yaxis);
  31769. yaxis.normalize();
  31770. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  31771. zaxis.normalize();
  31772. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  31773. xaxis.normalize();
  31774. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31775. var a = this._bone1Length;
  31776. var b = this._bone2Length;
  31777. var c = BABYLON.Vector3.Distance(bonePos, target);
  31778. if (this._maxReach > 0) {
  31779. c = Math.min(this._maxReach, c);
  31780. }
  31781. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31782. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31783. if (acosa > 1) {
  31784. acosa = 1;
  31785. }
  31786. if (acosb > 1) {
  31787. acosb = 1;
  31788. }
  31789. if (acosa < -1) {
  31790. acosa = -1;
  31791. }
  31792. if (acosb < -1) {
  31793. acosb = -1;
  31794. }
  31795. var angA = Math.acos(acosa);
  31796. var angB = Math.acos(acosb);
  31797. var angC = -angA - angB;
  31798. if (this._rightHandedSystem) {
  31799. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31800. mat2.multiplyToRef(mat1, mat1);
  31801. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31802. mat2.multiplyToRef(mat1, mat1);
  31803. }
  31804. else {
  31805. this._tmpVec1.copyFrom(this._bendAxis);
  31806. this._tmpVec1.x *= -1;
  31807. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31808. mat2.multiplyToRef(mat1, mat1);
  31809. }
  31810. if (this.poleAngle) {
  31811. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31812. mat1.multiplyToRef(mat2, mat1);
  31813. }
  31814. if (this.slerpAmount < 1) {
  31815. if (!this._slerping) {
  31816. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31817. }
  31818. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31819. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31820. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31821. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31822. this._slerping = true;
  31823. }
  31824. else {
  31825. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31826. this._bone1Mat.copyFrom(mat1);
  31827. this._slerping = false;
  31828. }
  31829. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31830. this._bone2Ang = angC;
  31831. };
  31832. return BoneIKController;
  31833. }());
  31834. BABYLON.BoneIKController = BoneIKController;
  31835. })(BABYLON || (BABYLON = {}));
  31836. //# sourceMappingURL=babylon.boneIKController.js.map
  31837. var BABYLON;
  31838. (function (BABYLON) {
  31839. var BoneLookController = (function () {
  31840. function BoneLookController(mesh, bone, target, options) {
  31841. this.upAxis = BABYLON.Vector3.Up();
  31842. this.adjustYaw = 0;
  31843. this.adjustPitch = 0;
  31844. this.adjustRoll = 0;
  31845. this._tmpVec1 = BABYLON.Vector3.Zero();
  31846. this._tmpVec2 = BABYLON.Vector3.Zero();
  31847. this._tmpVec3 = BABYLON.Vector3.Zero();
  31848. this._tmpVec4 = BABYLON.Vector3.Zero();
  31849. this._tmpMat1 = BABYLON.Matrix.Identity();
  31850. this._tmpMat2 = BABYLON.Matrix.Identity();
  31851. this.mesh = mesh;
  31852. this.bone = bone;
  31853. this.target = target;
  31854. if (options) {
  31855. if (options.adjustYaw) {
  31856. this.adjustYaw = options.adjustYaw;
  31857. }
  31858. if (options.adjustPitch) {
  31859. this.adjustPitch = options.adjustPitch;
  31860. }
  31861. if (options.adjustRoll) {
  31862. this.adjustRoll = options.adjustRoll;
  31863. }
  31864. }
  31865. }
  31866. BoneLookController.prototype.update = function () {
  31867. var bone = this.bone;
  31868. var target = this.target;
  31869. var bonePos = this._tmpVec1;
  31870. var zaxis = this._tmpVec2;
  31871. var xaxis = this._tmpVec3;
  31872. var yaxis = this._tmpVec4;
  31873. var mat1 = this._tmpMat1;
  31874. var mat2 = this._tmpMat2;
  31875. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31876. target.subtractToRef(bonePos, zaxis);
  31877. zaxis.normalize();
  31878. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31879. xaxis.normalize();
  31880. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31881. yaxis.normalize();
  31882. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31883. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31884. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31885. mat2.multiplyToRef(mat1, mat1);
  31886. }
  31887. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31888. };
  31889. return BoneLookController;
  31890. }());
  31891. BABYLON.BoneLookController = BoneLookController;
  31892. })(BABYLON || (BABYLON = {}));
  31893. //# sourceMappingURL=babylon.boneLookController.js.map
  31894. var BABYLON;
  31895. (function (BABYLON) {
  31896. var Skeleton = (function () {
  31897. function Skeleton(name, id, scene) {
  31898. this.name = name;
  31899. this.id = id;
  31900. this.bones = new Array();
  31901. this.needInitialSkinMatrix = false;
  31902. this._isDirty = true;
  31903. this._meshesWithPoseMatrix = new Array();
  31904. this._identity = BABYLON.Matrix.Identity();
  31905. this._ranges = {};
  31906. this._lastAbsoluteTransformsUpdateId = -1;
  31907. this.bones = [];
  31908. this._scene = scene;
  31909. scene.skeletons.push(this);
  31910. //make sure it will recalculate the matrix next time prepare is called.
  31911. this._isDirty = true;
  31912. }
  31913. // Members
  31914. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31915. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31916. return mesh._bonesTransformMatrices;
  31917. }
  31918. if (!this._transformMatrices) {
  31919. this.prepare();
  31920. }
  31921. return this._transformMatrices;
  31922. };
  31923. Skeleton.prototype.getScene = function () {
  31924. return this._scene;
  31925. };
  31926. // Methods
  31927. /**
  31928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31929. */
  31930. Skeleton.prototype.toString = function (fullDetails) {
  31931. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31932. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31933. if (fullDetails) {
  31934. ret += ", Ranges: {";
  31935. var first = true;
  31936. for (var name_1 in this._ranges) {
  31937. if (first) {
  31938. ret += ", ";
  31939. first = false;
  31940. }
  31941. ret += name_1;
  31942. }
  31943. ret += "}";
  31944. }
  31945. return ret;
  31946. };
  31947. /**
  31948. * Get bone's index searching by name
  31949. * @param {string} name is bone's name to search for
  31950. * @return {number} Indice of the bone. Returns -1 if not found
  31951. */
  31952. Skeleton.prototype.getBoneIndexByName = function (name) {
  31953. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31954. if (this.bones[boneIndex].name === name) {
  31955. return boneIndex;
  31956. }
  31957. }
  31958. return -1;
  31959. };
  31960. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31961. // check name not already in use
  31962. if (!this._ranges[name]) {
  31963. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31964. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31965. if (this.bones[i].animations[0]) {
  31966. this.bones[i].animations[0].createRange(name, from, to);
  31967. }
  31968. }
  31969. }
  31970. };
  31971. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31972. if (deleteFrames === void 0) { deleteFrames = true; }
  31973. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31974. if (this.bones[i].animations[0]) {
  31975. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31976. }
  31977. }
  31978. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31979. };
  31980. Skeleton.prototype.getAnimationRange = function (name) {
  31981. return this._ranges[name];
  31982. };
  31983. /**
  31984. * Returns as an Array, all AnimationRanges defined on this skeleton
  31985. */
  31986. Skeleton.prototype.getAnimationRanges = function () {
  31987. var animationRanges = [];
  31988. var name;
  31989. var i = 0;
  31990. for (name in this._ranges) {
  31991. animationRanges[i] = this._ranges[name];
  31992. i++;
  31993. }
  31994. return animationRanges;
  31995. };
  31996. /**
  31997. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31998. */
  31999. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  32000. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  32001. if (this._ranges[name] || !source.getAnimationRange(name)) {
  32002. return false;
  32003. }
  32004. var ret = true;
  32005. var frameOffset = this._getHighestAnimationFrame() + 1;
  32006. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  32007. var boneDict = {};
  32008. var sourceBones = source.bones;
  32009. var nBones;
  32010. var i;
  32011. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  32012. boneDict[sourceBones[i].name] = sourceBones[i];
  32013. }
  32014. if (this.bones.length !== sourceBones.length) {
  32015. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  32016. ret = false;
  32017. }
  32018. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  32019. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  32020. var boneName = this.bones[i].name;
  32021. var sourceBone = boneDict[boneName];
  32022. if (sourceBone) {
  32023. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  32024. }
  32025. else {
  32026. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  32027. ret = false;
  32028. }
  32029. }
  32030. // do not call createAnimationRange(), since it also is done to bones, which was already done
  32031. var range = source.getAnimationRange(name);
  32032. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  32033. return ret;
  32034. };
  32035. Skeleton.prototype.returnToRest = function () {
  32036. for (var index = 0; index < this.bones.length; index++) {
  32037. this.bones[index].returnToRest();
  32038. }
  32039. };
  32040. Skeleton.prototype._getHighestAnimationFrame = function () {
  32041. var ret = 0;
  32042. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  32043. if (this.bones[i].animations[0]) {
  32044. var highest = this.bones[i].animations[0].getHighestFrame();
  32045. if (ret < highest) {
  32046. ret = highest;
  32047. }
  32048. }
  32049. }
  32050. return ret;
  32051. };
  32052. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  32053. var range = this.getAnimationRange(name);
  32054. if (!range) {
  32055. return null;
  32056. }
  32057. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  32058. };
  32059. Skeleton.prototype._markAsDirty = function () {
  32060. this._isDirty = true;
  32061. };
  32062. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  32063. this._meshesWithPoseMatrix.push(mesh);
  32064. };
  32065. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  32066. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  32067. if (index > -1) {
  32068. this._meshesWithPoseMatrix.splice(index, 1);
  32069. }
  32070. };
  32071. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  32072. for (var index = 0; index < this.bones.length; index++) {
  32073. var bone = this.bones[index];
  32074. var parentBone = bone.getParent();
  32075. if (parentBone) {
  32076. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  32077. }
  32078. else {
  32079. if (initialSkinMatrix) {
  32080. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  32081. }
  32082. else {
  32083. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  32084. }
  32085. }
  32086. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  32087. }
  32088. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  32089. };
  32090. Skeleton.prototype.prepare = function () {
  32091. if (!this._isDirty) {
  32092. return;
  32093. }
  32094. if (this.needInitialSkinMatrix) {
  32095. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  32096. var mesh = this._meshesWithPoseMatrix[index];
  32097. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  32098. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  32099. }
  32100. var poseMatrix = mesh.getPoseMatrix();
  32101. // Prepare bones
  32102. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  32103. var bone = this.bones[boneIndex];
  32104. if (!bone.getParent()) {
  32105. var matrix = bone.getBaseMatrix();
  32106. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  32107. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  32108. }
  32109. }
  32110. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  32111. }
  32112. }
  32113. else {
  32114. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  32115. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  32116. }
  32117. this._computeTransformMatrices(this._transformMatrices, null);
  32118. }
  32119. this._isDirty = false;
  32120. this._scene._activeBones.addCount(this.bones.length, false);
  32121. };
  32122. Skeleton.prototype.getAnimatables = function () {
  32123. if (!this._animatables || this._animatables.length !== this.bones.length) {
  32124. this._animatables = [];
  32125. for (var index = 0; index < this.bones.length; index++) {
  32126. this._animatables.push(this.bones[index]);
  32127. }
  32128. }
  32129. return this._animatables;
  32130. };
  32131. Skeleton.prototype.clone = function (name, id) {
  32132. var result = new Skeleton(name, id || name, this._scene);
  32133. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32134. for (var index = 0; index < this.bones.length; index++) {
  32135. var source = this.bones[index];
  32136. var parentBone = null;
  32137. if (source.getParent()) {
  32138. var parentIndex = this.bones.indexOf(source.getParent());
  32139. parentBone = result.bones[parentIndex];
  32140. }
  32141. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  32142. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  32143. }
  32144. if (this._ranges) {
  32145. result._ranges = {};
  32146. for (var rangeName in this._ranges) {
  32147. result._ranges[rangeName] = this._ranges[rangeName].clone();
  32148. }
  32149. }
  32150. this._isDirty = true;
  32151. return result;
  32152. };
  32153. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  32154. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  32155. this.bones.forEach(function (bone) {
  32156. bone.animations.forEach(function (animation) {
  32157. animation.enableBlending = true;
  32158. animation.blendingSpeed = blendingSpeed;
  32159. });
  32160. });
  32161. };
  32162. Skeleton.prototype.dispose = function () {
  32163. this._meshesWithPoseMatrix = [];
  32164. // Animations
  32165. this.getScene().stopAnimation(this);
  32166. // Remove from scene
  32167. this.getScene().removeSkeleton(this);
  32168. };
  32169. Skeleton.prototype.serialize = function () {
  32170. var serializationObject = {};
  32171. serializationObject.name = this.name;
  32172. serializationObject.id = this.id;
  32173. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  32174. serializationObject.bones = [];
  32175. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32176. for (var index = 0; index < this.bones.length; index++) {
  32177. var bone = this.bones[index];
  32178. var serializedBone = {
  32179. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  32180. name: bone.name,
  32181. matrix: bone.getLocalMatrix().toArray(),
  32182. rest: bone.getRestPose().toArray()
  32183. };
  32184. serializationObject.bones.push(serializedBone);
  32185. if (bone.length) {
  32186. serializedBone.length = bone.length;
  32187. }
  32188. if (bone.animations && bone.animations.length > 0) {
  32189. serializedBone.animation = bone.animations[0].serialize();
  32190. }
  32191. serializationObject.ranges = [];
  32192. for (var name in this._ranges) {
  32193. var range = {};
  32194. range.name = name;
  32195. range.from = this._ranges[name].from;
  32196. range.to = this._ranges[name].to;
  32197. serializationObject.ranges.push(range);
  32198. }
  32199. }
  32200. return serializationObject;
  32201. };
  32202. Skeleton.Parse = function (parsedSkeleton, scene) {
  32203. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  32204. if (parsedSkeleton.dimensionsAtRest) {
  32205. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  32206. }
  32207. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  32208. var index;
  32209. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  32210. var parsedBone = parsedSkeleton.bones[index];
  32211. var parentBone = null;
  32212. if (parsedBone.parentBoneIndex > -1) {
  32213. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  32214. }
  32215. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  32216. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  32217. if (parsedBone.length) {
  32218. bone.length = parsedBone.length;
  32219. }
  32220. if (parsedBone.animation) {
  32221. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  32222. }
  32223. }
  32224. // placed after bones, so createAnimationRange can cascade down
  32225. if (parsedSkeleton.ranges) {
  32226. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  32227. var data = parsedSkeleton.ranges[index];
  32228. skeleton.createAnimationRange(data.name, data.from, data.to);
  32229. }
  32230. }
  32231. return skeleton;
  32232. };
  32233. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  32234. if (forceUpdate === void 0) { forceUpdate = false; }
  32235. var renderId = this._scene.getRenderId();
  32236. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  32237. this.bones[0].computeAbsoluteTransforms();
  32238. this._lastAbsoluteTransformsUpdateId = renderId;
  32239. }
  32240. };
  32241. Skeleton.prototype.getPoseMatrix = function () {
  32242. var poseMatrix;
  32243. if (this._meshesWithPoseMatrix.length > 0) {
  32244. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  32245. }
  32246. return poseMatrix;
  32247. };
  32248. return Skeleton;
  32249. }());
  32250. BABYLON.Skeleton = Skeleton;
  32251. })(BABYLON || (BABYLON = {}));
  32252. //# sourceMappingURL=babylon.skeleton.js.map
  32253. var BABYLON;
  32254. (function (BABYLON) {
  32255. var PostProcess = (function () {
  32256. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  32257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32258. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32259. this.name = name;
  32260. this.width = -1;
  32261. this.height = -1;
  32262. /*
  32263. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32264. Can only be used on a single postprocess or on the last one of a chain.
  32265. */
  32266. this.enablePixelPerfectMode = false;
  32267. this._reusable = false;
  32268. this._textures = new BABYLON.SmartArray(2);
  32269. this._currentRenderTextureInd = 0;
  32270. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32271. // Events
  32272. /**
  32273. * An event triggered when the postprocess is activated.
  32274. * @type {BABYLON.Observable}
  32275. */
  32276. this.onActivateObservable = new BABYLON.Observable();
  32277. /**
  32278. * An event triggered when the postprocess changes its size.
  32279. * @type {BABYLON.Observable}
  32280. */
  32281. this.onSizeChangedObservable = new BABYLON.Observable();
  32282. /**
  32283. * An event triggered when the postprocess applies its effect.
  32284. * @type {BABYLON.Observable}
  32285. */
  32286. this.onApplyObservable = new BABYLON.Observable();
  32287. /**
  32288. * An event triggered before rendering the postprocess
  32289. * @type {BABYLON.Observable}
  32290. */
  32291. this.onBeforeRenderObservable = new BABYLON.Observable();
  32292. /**
  32293. * An event triggered after rendering the postprocess
  32294. * @type {BABYLON.Observable}
  32295. */
  32296. this.onAfterRenderObservable = new BABYLON.Observable();
  32297. if (camera != null) {
  32298. this._camera = camera;
  32299. this._scene = camera.getScene();
  32300. camera.attachPostProcess(this);
  32301. this._engine = this._scene.getEngine();
  32302. }
  32303. else {
  32304. this._engine = engine;
  32305. }
  32306. this._options = options;
  32307. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32308. this._reusable = reusable || false;
  32309. this._textureType = textureType;
  32310. this._samplers = samplers || [];
  32311. this._samplers.push("textureSampler");
  32312. this._fragmentUrl = fragmentUrl;
  32313. this._parameters = parameters || [];
  32314. this._parameters.push("scale");
  32315. this.updateEffect(defines);
  32316. }
  32317. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32318. set: function (callback) {
  32319. if (this._onActivateObserver) {
  32320. this.onActivateObservable.remove(this._onActivateObserver);
  32321. }
  32322. this._onActivateObserver = this.onActivateObservable.add(callback);
  32323. },
  32324. enumerable: true,
  32325. configurable: true
  32326. });
  32327. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32328. set: function (callback) {
  32329. if (this._onSizeChangedObserver) {
  32330. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32331. }
  32332. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32333. },
  32334. enumerable: true,
  32335. configurable: true
  32336. });
  32337. Object.defineProperty(PostProcess.prototype, "onApply", {
  32338. set: function (callback) {
  32339. if (this._onApplyObserver) {
  32340. this.onApplyObservable.remove(this._onApplyObserver);
  32341. }
  32342. this._onApplyObserver = this.onApplyObservable.add(callback);
  32343. },
  32344. enumerable: true,
  32345. configurable: true
  32346. });
  32347. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32348. set: function (callback) {
  32349. if (this._onBeforeRenderObserver) {
  32350. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32351. }
  32352. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32353. },
  32354. enumerable: true,
  32355. configurable: true
  32356. });
  32357. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32358. set: function (callback) {
  32359. if (this._onAfterRenderObserver) {
  32360. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32361. }
  32362. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32363. },
  32364. enumerable: true,
  32365. configurable: true
  32366. });
  32367. PostProcess.prototype.updateEffect = function (defines) {
  32368. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  32369. };
  32370. PostProcess.prototype.isReusable = function () {
  32371. return this._reusable;
  32372. };
  32373. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32374. PostProcess.prototype.markTextureDirty = function () {
  32375. this.width = -1;
  32376. };
  32377. PostProcess.prototype.activate = function (camera, sourceTexture) {
  32378. camera = camera || this._camera;
  32379. var scene = camera.getScene();
  32380. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32381. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32382. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32383. var desiredWidth = this._options.width || requiredWidth;
  32384. var desiredHeight = this._options.height || requiredHeight;
  32385. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32386. if (!this._options.width) {
  32387. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  32388. }
  32389. if (!this._options.height) {
  32390. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  32391. }
  32392. }
  32393. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32394. if (this._textures.length > 0) {
  32395. for (var i = 0; i < this._textures.length; i++) {
  32396. this._engine._releaseTexture(this._textures.data[i]);
  32397. }
  32398. this._textures.reset();
  32399. }
  32400. this.width = desiredWidth;
  32401. this.height = desiredHeight;
  32402. var textureSize = { width: this.width, height: this.height };
  32403. var textureOptions = {
  32404. generateMipMaps: false,
  32405. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  32406. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  32407. samplingMode: this.renderTargetSamplingMode,
  32408. type: this._textureType
  32409. };
  32410. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32411. if (this._reusable) {
  32412. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32413. }
  32414. this.onSizeChangedObservable.notifyObservers(this);
  32415. }
  32416. if (this.enablePixelPerfectMode) {
  32417. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32418. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  32419. }
  32420. else {
  32421. this._scaleRatio.copyFromFloats(1, 1);
  32422. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  32423. }
  32424. this.onActivateObservable.notifyObservers(camera);
  32425. // Clear
  32426. if (this.clearColor) {
  32427. this._engine.clear(this.clearColor, true, true, true);
  32428. }
  32429. else {
  32430. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  32431. }
  32432. if (this._reusable) {
  32433. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32434. }
  32435. };
  32436. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32437. get: function () {
  32438. return this._effect.isSupported;
  32439. },
  32440. enumerable: true,
  32441. configurable: true
  32442. });
  32443. PostProcess.prototype.apply = function () {
  32444. // Check
  32445. if (!this._effect.isReady())
  32446. return null;
  32447. // States
  32448. this._engine.enableEffect(this._effect);
  32449. this._engine.setState(false);
  32450. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32451. this._engine.setDepthBuffer(false);
  32452. this._engine.setDepthWrite(false);
  32453. // Texture
  32454. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  32455. // Parameters
  32456. this._effect.setVector2("scale", this._scaleRatio);
  32457. this.onApplyObservable.notifyObservers(this._effect);
  32458. return this._effect;
  32459. };
  32460. PostProcess.prototype.dispose = function (camera) {
  32461. camera = camera || this._camera;
  32462. if (this._textures.length > 0) {
  32463. for (var i = 0; i < this._textures.length; i++) {
  32464. this._engine._releaseTexture(this._textures.data[i]);
  32465. }
  32466. this._textures.reset();
  32467. }
  32468. if (!camera) {
  32469. return;
  32470. }
  32471. camera.detachPostProcess(this);
  32472. var index = camera._postProcesses.indexOf(this);
  32473. if (index === 0 && camera._postProcesses.length > 0) {
  32474. this._camera._postProcesses[0].markTextureDirty();
  32475. }
  32476. this.onActivateObservable.clear();
  32477. this.onAfterRenderObservable.clear();
  32478. this.onApplyObservable.clear();
  32479. this.onBeforeRenderObservable.clear();
  32480. this.onSizeChangedObservable.clear();
  32481. };
  32482. return PostProcess;
  32483. }());
  32484. BABYLON.PostProcess = PostProcess;
  32485. })(BABYLON || (BABYLON = {}));
  32486. //# sourceMappingURL=babylon.postProcess.js.map
  32487. var BABYLON;
  32488. (function (BABYLON) {
  32489. var PostProcessManager = (function () {
  32490. function PostProcessManager(scene) {
  32491. this._vertexBuffers = {};
  32492. this._scene = scene;
  32493. }
  32494. PostProcessManager.prototype._prepareBuffers = function () {
  32495. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32496. return;
  32497. }
  32498. // VBO
  32499. var vertices = [];
  32500. vertices.push(1, 1);
  32501. vertices.push(-1, 1);
  32502. vertices.push(-1, -1);
  32503. vertices.push(1, -1);
  32504. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32505. // Indices
  32506. var indices = [];
  32507. indices.push(0);
  32508. indices.push(1);
  32509. indices.push(2);
  32510. indices.push(0);
  32511. indices.push(2);
  32512. indices.push(3);
  32513. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32514. };
  32515. // Methods
  32516. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  32517. var postProcesses = this._scene.activeCamera._postProcesses;
  32518. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32519. return false;
  32520. }
  32521. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  32522. return true;
  32523. };
  32524. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  32525. var engine = this._scene.getEngine();
  32526. for (var index = 0; index < postProcesses.length; index++) {
  32527. if (index < postProcesses.length - 1) {
  32528. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32529. }
  32530. else {
  32531. if (targetTexture) {
  32532. engine.bindFramebuffer(targetTexture);
  32533. }
  32534. else {
  32535. engine.restoreDefaultFramebuffer();
  32536. }
  32537. }
  32538. var pp = postProcesses[index];
  32539. var effect = pp.apply();
  32540. if (effect) {
  32541. pp.onBeforeRenderObservable.notifyObservers(effect);
  32542. // VBOs
  32543. this._prepareBuffers();
  32544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32545. // Draw order
  32546. engine.draw(true, 0, 6);
  32547. pp.onAfterRenderObservable.notifyObservers(effect);
  32548. }
  32549. }
  32550. // Restore depth buffer
  32551. engine.setDepthBuffer(true);
  32552. engine.setDepthWrite(true);
  32553. };
  32554. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  32555. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  32556. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32557. return;
  32558. }
  32559. var engine = this._scene.getEngine();
  32560. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32561. if (index < len - 1) {
  32562. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32563. }
  32564. else {
  32565. if (targetTexture) {
  32566. engine.bindFramebuffer(targetTexture, faceIndex);
  32567. }
  32568. else {
  32569. engine.restoreDefaultFramebuffer();
  32570. }
  32571. }
  32572. if (doNotPresent) {
  32573. break;
  32574. }
  32575. var pp = postProcesses[index];
  32576. var effect = pp.apply();
  32577. if (effect) {
  32578. pp.onBeforeRenderObservable.notifyObservers(effect);
  32579. // VBOs
  32580. this._prepareBuffers();
  32581. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32582. // Draw order
  32583. engine.draw(true, 0, 6);
  32584. pp.onAfterRenderObservable.notifyObservers(effect);
  32585. }
  32586. }
  32587. // Restore depth buffer
  32588. engine.setDepthBuffer(true);
  32589. engine.setDepthWrite(true);
  32590. };
  32591. PostProcessManager.prototype.dispose = function () {
  32592. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32593. if (buffer) {
  32594. buffer.dispose();
  32595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32596. }
  32597. if (this._indexBuffer) {
  32598. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32599. this._indexBuffer = null;
  32600. }
  32601. };
  32602. return PostProcessManager;
  32603. }());
  32604. BABYLON.PostProcessManager = PostProcessManager;
  32605. })(BABYLON || (BABYLON = {}));
  32606. //# sourceMappingURL=babylon.postProcessManager.js.map
  32607. var BABYLON;
  32608. (function (BABYLON) {
  32609. var PassPostProcess = (function (_super) {
  32610. __extends(PassPostProcess, _super);
  32611. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  32612. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  32613. }
  32614. return PassPostProcess;
  32615. }(BABYLON.PostProcess));
  32616. BABYLON.PassPostProcess = PassPostProcess;
  32617. })(BABYLON || (BABYLON = {}));
  32618. //# sourceMappingURL=babylon.passPostProcess.js.map
  32619. var BABYLON;
  32620. (function (BABYLON) {
  32621. /**
  32622. * This is a holder class for the physics joint created by the physics plugin.
  32623. * It holds a set of functions to control the underlying joint.
  32624. */
  32625. var PhysicsJoint = (function () {
  32626. function PhysicsJoint(type, jointData) {
  32627. this.type = type;
  32628. this.jointData = jointData;
  32629. jointData.nativeParams = jointData.nativeParams || {};
  32630. }
  32631. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  32632. get: function () {
  32633. return this._physicsJoint;
  32634. },
  32635. set: function (newJoint) {
  32636. if (this._physicsJoint) {
  32637. }
  32638. this._physicsJoint = newJoint;
  32639. },
  32640. enumerable: true,
  32641. configurable: true
  32642. });
  32643. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  32644. set: function (physicsPlugin) {
  32645. this._physicsPlugin = physicsPlugin;
  32646. },
  32647. enumerable: true,
  32648. configurable: true
  32649. });
  32650. /**
  32651. * Execute a function that is physics-plugin specific.
  32652. * @param {Function} func the function that will be executed.
  32653. * It accepts two parameters: the physics world and the physics joint.
  32654. */
  32655. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  32656. func(this._physicsPlugin.world, this._physicsJoint);
  32657. };
  32658. return PhysicsJoint;
  32659. }());
  32660. //TODO check if the native joints are the same
  32661. //Joint Types
  32662. PhysicsJoint.DistanceJoint = 0;
  32663. PhysicsJoint.HingeJoint = 1;
  32664. PhysicsJoint.BallAndSocketJoint = 2;
  32665. PhysicsJoint.WheelJoint = 3;
  32666. PhysicsJoint.SliderJoint = 4;
  32667. //OIMO
  32668. PhysicsJoint.PrismaticJoint = 5;
  32669. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  32670. PhysicsJoint.UniversalJoint = 6;
  32671. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  32672. //Cannon
  32673. //Similar to a Ball-Joint. Different in params
  32674. PhysicsJoint.PointToPointJoint = 8;
  32675. //Cannon only at the moment
  32676. PhysicsJoint.SpringJoint = 9;
  32677. PhysicsJoint.LockJoint = 10;
  32678. BABYLON.PhysicsJoint = PhysicsJoint;
  32679. /**
  32680. * A class representing a physics distance joint.
  32681. */
  32682. var DistanceJoint = (function (_super) {
  32683. __extends(DistanceJoint, _super);
  32684. function DistanceJoint(jointData) {
  32685. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  32686. }
  32687. /**
  32688. * Update the predefined distance.
  32689. */
  32690. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  32691. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  32692. };
  32693. return DistanceJoint;
  32694. }(PhysicsJoint));
  32695. BABYLON.DistanceJoint = DistanceJoint;
  32696. var MotorEnabledJoint = (function (_super) {
  32697. __extends(MotorEnabledJoint, _super);
  32698. function MotorEnabledJoint(type, jointData) {
  32699. return _super.call(this, type, jointData) || this;
  32700. }
  32701. /**
  32702. * Set the motor values.
  32703. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32704. * @param {number} force the force to apply
  32705. * @param {number} maxForce max force for this motor.
  32706. */
  32707. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  32708. this._physicsPlugin.setMotor(this, force, maxForce);
  32709. };
  32710. /**
  32711. * Set the motor's limits.
  32712. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32713. */
  32714. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32715. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32716. };
  32717. return MotorEnabledJoint;
  32718. }(PhysicsJoint));
  32719. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  32720. /**
  32721. * This class represents a single hinge physics joint
  32722. */
  32723. var HingeJoint = (function (_super) {
  32724. __extends(HingeJoint, _super);
  32725. function HingeJoint(jointData) {
  32726. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  32727. }
  32728. /**
  32729. * Set the motor values.
  32730. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32731. * @param {number} force the force to apply
  32732. * @param {number} maxForce max force for this motor.
  32733. */
  32734. HingeJoint.prototype.setMotor = function (force, maxForce) {
  32735. this._physicsPlugin.setMotor(this, force, maxForce);
  32736. };
  32737. /**
  32738. * Set the motor's limits.
  32739. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32740. */
  32741. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32742. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32743. };
  32744. return HingeJoint;
  32745. }(MotorEnabledJoint));
  32746. BABYLON.HingeJoint = HingeJoint;
  32747. /**
  32748. * This class represents a dual hinge physics joint (same as wheel joint)
  32749. */
  32750. var Hinge2Joint = (function (_super) {
  32751. __extends(Hinge2Joint, _super);
  32752. function Hinge2Joint(jointData) {
  32753. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  32754. }
  32755. /**
  32756. * Set the motor values.
  32757. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32758. * @param {number} force the force to apply
  32759. * @param {number} maxForce max force for this motor.
  32760. * @param {motorIndex} the motor's index, 0 or 1.
  32761. */
  32762. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  32763. if (motorIndex === void 0) { motorIndex = 0; }
  32764. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  32765. };
  32766. /**
  32767. * Set the motor limits.
  32768. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32769. * @param {number} upperLimit the upper limit
  32770. * @param {number} lowerLimit lower limit
  32771. * @param {motorIndex} the motor's index, 0 or 1.
  32772. */
  32773. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  32774. if (motorIndex === void 0) { motorIndex = 0; }
  32775. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  32776. };
  32777. return Hinge2Joint;
  32778. }(MotorEnabledJoint));
  32779. BABYLON.Hinge2Joint = Hinge2Joint;
  32780. })(BABYLON || (BABYLON = {}));
  32781. //# sourceMappingURL=babylon.physicsJoint.js.map
  32782. var BABYLON;
  32783. (function (BABYLON) {
  32784. var PhysicsImpostor = (function () {
  32785. function PhysicsImpostor(object, type, _options, _scene) {
  32786. if (_options === void 0) { _options = { mass: 0 }; }
  32787. var _this = this;
  32788. this.object = object;
  32789. this.type = type;
  32790. this._options = _options;
  32791. this._scene = _scene;
  32792. this._bodyUpdateRequired = false;
  32793. this._onBeforePhysicsStepCallbacks = new Array();
  32794. this._onAfterPhysicsStepCallbacks = new Array();
  32795. this._onPhysicsCollideCallbacks = [];
  32796. this._deltaPosition = BABYLON.Vector3.Zero();
  32797. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32798. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32799. /**
  32800. * this function is executed by the physics engine.
  32801. */
  32802. this.beforeStep = function () {
  32803. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32804. //conjugate deltaRotation
  32805. if (_this._deltaRotationConjugated) {
  32806. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32807. }
  32808. else {
  32809. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32810. }
  32811. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32812. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32813. func(_this);
  32814. });
  32815. };
  32816. /**
  32817. * this function is executed by the physics engine.
  32818. */
  32819. this.afterStep = function () {
  32820. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32821. func(_this);
  32822. });
  32823. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32824. _this.object.position.addInPlace(_this._deltaPosition);
  32825. if (_this._deltaRotation) {
  32826. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32827. }
  32828. };
  32829. /**
  32830. * Legacy collision detection event support
  32831. */
  32832. this.onCollideEvent = null;
  32833. //event and body object due to cannon's event-based architecture.
  32834. this.onCollide = function (e) {
  32835. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  32836. return;
  32837. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32838. if (otherImpostor) {
  32839. // Legacy collision detection event support
  32840. if (_this.onCollideEvent) {
  32841. _this.onCollideEvent(_this, otherImpostor);
  32842. }
  32843. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32844. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  32845. }).forEach(function (obj) {
  32846. obj.callback(_this, otherImpostor);
  32847. });
  32848. }
  32849. };
  32850. //sanity check!
  32851. if (!this.object) {
  32852. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32853. return;
  32854. }
  32855. //legacy support for old syntax.
  32856. if (!this._scene && object.getScene) {
  32857. this._scene = object.getScene();
  32858. }
  32859. this._physicsEngine = this._scene.getPhysicsEngine();
  32860. if (!this._physicsEngine) {
  32861. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32862. }
  32863. else {
  32864. //set the object's quaternion, if not set
  32865. if (!this.object.rotationQuaternion) {
  32866. if (this.object.rotation) {
  32867. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32868. }
  32869. else {
  32870. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32871. }
  32872. }
  32873. //default options params
  32874. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32875. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32876. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32877. this._joints = [];
  32878. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32879. if (!this.object.parent) {
  32880. this._init();
  32881. }
  32882. }
  32883. }
  32884. /**
  32885. * This function will completly initialize this impostor.
  32886. * It will create a new body - but only if this mesh has no parent.
  32887. * If it has, this impostor will not be used other than to define the impostor
  32888. * of the child mesh.
  32889. */
  32890. PhysicsImpostor.prototype._init = function () {
  32891. this._physicsEngine.removeImpostor(this);
  32892. this.physicsBody = null;
  32893. this._parent = this._parent || this._getPhysicsParent();
  32894. if (!this.parent) {
  32895. this._physicsEngine.addImpostor(this);
  32896. }
  32897. };
  32898. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32899. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32900. var parentMesh = this.object.parent;
  32901. return parentMesh.physicsImpostor;
  32902. }
  32903. return;
  32904. };
  32905. /**
  32906. * Should a new body be generated.
  32907. */
  32908. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32909. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32910. };
  32911. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32912. this.forceUpdate();
  32913. };
  32914. /**
  32915. * Force a regeneration of this or the parent's impostor's body.
  32916. * Use under cautious - This will remove all joints already implemented.
  32917. */
  32918. PhysicsImpostor.prototype.forceUpdate = function () {
  32919. this._init();
  32920. if (this.parent) {
  32921. this.parent.forceUpdate();
  32922. }
  32923. };
  32924. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32925. /*public get mesh(): AbstractMesh {
  32926. return this._mesh;
  32927. }*/
  32928. /**
  32929. * Gets the body that holds this impostor. Either its own, or its parent.
  32930. */
  32931. get: function () {
  32932. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32933. },
  32934. /**
  32935. * Set the physics body. Used mainly by the physics engine/plugin
  32936. */
  32937. set: function (physicsBody) {
  32938. if (this._physicsBody) {
  32939. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32940. }
  32941. this._physicsBody = physicsBody;
  32942. this.resetUpdateFlags();
  32943. },
  32944. enumerable: true,
  32945. configurable: true
  32946. });
  32947. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32948. get: function () {
  32949. return this._parent;
  32950. },
  32951. set: function (value) {
  32952. this._parent = value;
  32953. },
  32954. enumerable: true,
  32955. configurable: true
  32956. });
  32957. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32958. this._bodyUpdateRequired = false;
  32959. };
  32960. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32961. if (this.object.getBoundingInfo) {
  32962. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32963. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32964. }
  32965. else {
  32966. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32967. }
  32968. };
  32969. PhysicsImpostor.prototype.getObjectCenter = function () {
  32970. if (this.object.getBoundingInfo) {
  32971. return this.object.getBoundingInfo().boundingBox.center;
  32972. }
  32973. else {
  32974. return this.object.position;
  32975. }
  32976. };
  32977. /**
  32978. * Get a specific parametes from the options parameter.
  32979. */
  32980. PhysicsImpostor.prototype.getParam = function (paramName) {
  32981. return this._options[paramName];
  32982. };
  32983. /**
  32984. * Sets a specific parameter in the options given to the physics plugin
  32985. */
  32986. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32987. this._options[paramName] = value;
  32988. this._bodyUpdateRequired = true;
  32989. };
  32990. /**
  32991. * Specifically change the body's mass option. Won't recreate the physics body object
  32992. */
  32993. PhysicsImpostor.prototype.setMass = function (mass) {
  32994. if (this.getParam("mass") !== mass) {
  32995. this.setParam("mass", mass);
  32996. }
  32997. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32998. };
  32999. PhysicsImpostor.prototype.getLinearVelocity = function () {
  33000. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  33001. };
  33002. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  33003. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  33004. };
  33005. PhysicsImpostor.prototype.getAngularVelocity = function () {
  33006. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  33007. };
  33008. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  33009. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  33010. };
  33011. /**
  33012. * Execute a function with the physics plugin native code.
  33013. * Provide a function the will have two variables - the world object and the physics body object.
  33014. */
  33015. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  33016. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  33017. };
  33018. /**
  33019. * Register a function that will be executed before the physics world is stepping forward.
  33020. */
  33021. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  33022. this._onBeforePhysicsStepCallbacks.push(func);
  33023. };
  33024. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  33025. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  33026. if (index > -1) {
  33027. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  33028. }
  33029. else {
  33030. BABYLON.Tools.Warn("Function to remove was not found");
  33031. }
  33032. };
  33033. /**
  33034. * Register a function that will be executed after the physics step
  33035. */
  33036. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  33037. this._onAfterPhysicsStepCallbacks.push(func);
  33038. };
  33039. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  33040. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  33041. if (index > -1) {
  33042. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  33043. }
  33044. else {
  33045. BABYLON.Tools.Warn("Function to remove was not found");
  33046. }
  33047. };
  33048. /**
  33049. * register a function that will be executed when this impostor collides against a different body.
  33050. */
  33051. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  33052. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  33053. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  33054. };
  33055. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  33056. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  33057. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  33058. if (index > -1) {
  33059. this._onPhysicsCollideCallbacks.splice(index, 1);
  33060. }
  33061. else {
  33062. BABYLON.Tools.Warn("Function to remove was not found");
  33063. }
  33064. };
  33065. /**
  33066. * Apply a force
  33067. */
  33068. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  33069. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  33070. };
  33071. /**
  33072. * Apply an impulse
  33073. */
  33074. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  33075. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  33076. };
  33077. /**
  33078. * A help function to create a joint.
  33079. */
  33080. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  33081. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  33082. this.addJoint(otherImpostor, joint);
  33083. };
  33084. /**
  33085. * Add a joint to this impostor with a different impostor.
  33086. */
  33087. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  33088. this._joints.push({
  33089. otherImpostor: otherImpostor,
  33090. joint: joint
  33091. });
  33092. this._physicsEngine.addJoint(this, otherImpostor, joint);
  33093. };
  33094. /**
  33095. * Will keep this body still, in a sleep mode.
  33096. */
  33097. PhysicsImpostor.prototype.sleep = function () {
  33098. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  33099. };
  33100. /**
  33101. * Wake the body up.
  33102. */
  33103. PhysicsImpostor.prototype.wakeUp = function () {
  33104. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  33105. };
  33106. PhysicsImpostor.prototype.clone = function (newObject) {
  33107. if (!newObject)
  33108. return null;
  33109. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  33110. };
  33111. PhysicsImpostor.prototype.dispose = function () {
  33112. var _this = this;
  33113. //no dispose if no physics engine is available.
  33114. if (!this._physicsEngine) {
  33115. return;
  33116. }
  33117. this._joints.forEach(function (j) {
  33118. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  33119. });
  33120. //dispose the physics body
  33121. this._physicsEngine.removeImpostor(this);
  33122. if (this.parent) {
  33123. this.parent.forceUpdate();
  33124. }
  33125. else {
  33126. }
  33127. };
  33128. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  33129. this._deltaPosition.copyFrom(position);
  33130. };
  33131. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  33132. if (!this._deltaRotation) {
  33133. this._deltaRotation = new BABYLON.Quaternion();
  33134. }
  33135. this._deltaRotation.copyFrom(rotation);
  33136. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  33137. };
  33138. return PhysicsImpostor;
  33139. }());
  33140. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  33141. //Impostor types
  33142. PhysicsImpostor.NoImpostor = 0;
  33143. PhysicsImpostor.SphereImpostor = 1;
  33144. PhysicsImpostor.BoxImpostor = 2;
  33145. PhysicsImpostor.PlaneImpostor = 3;
  33146. PhysicsImpostor.MeshImpostor = 4;
  33147. PhysicsImpostor.CylinderImpostor = 7;
  33148. PhysicsImpostor.ParticleImpostor = 8;
  33149. PhysicsImpostor.HeightmapImpostor = 9;
  33150. BABYLON.PhysicsImpostor = PhysicsImpostor;
  33151. })(BABYLON || (BABYLON = {}));
  33152. //# sourceMappingURL=babylon.physicsImpostor.js.map
  33153. var BABYLON;
  33154. (function (BABYLON) {
  33155. var PhysicsEngine = (function () {
  33156. function PhysicsEngine(gravity, _physicsPlugin) {
  33157. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  33158. this._physicsPlugin = _physicsPlugin;
  33159. //new methods and parameters
  33160. this._impostors = [];
  33161. this._joints = [];
  33162. if (!this._physicsPlugin.isSupported()) {
  33163. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  33164. + "Please make sure it is included.");
  33165. }
  33166. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  33167. this.setGravity(gravity);
  33168. this.setTimeStep();
  33169. }
  33170. PhysicsEngine.prototype.setGravity = function (gravity) {
  33171. this.gravity = gravity;
  33172. this._physicsPlugin.setGravity(this.gravity);
  33173. };
  33174. /**
  33175. * Set the time step of the physics engine.
  33176. * default is 1/60.
  33177. * To slow it down, enter 1/600 for example.
  33178. * To speed it up, 1/30
  33179. * @param {number} newTimeStep the new timestep to apply to this world.
  33180. */
  33181. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  33182. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  33183. this._physicsPlugin.setTimeStep(newTimeStep);
  33184. };
  33185. PhysicsEngine.prototype.dispose = function () {
  33186. this._impostors.forEach(function (impostor) {
  33187. impostor.dispose();
  33188. });
  33189. this._physicsPlugin.dispose();
  33190. };
  33191. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  33192. return this._physicsPlugin.name;
  33193. };
  33194. /**
  33195. * Adding a new impostor for the impostor tracking.
  33196. * This will be done by the impostor itself.
  33197. * @param {PhysicsImpostor} impostor the impostor to add
  33198. */
  33199. PhysicsEngine.prototype.addImpostor = function (impostor) {
  33200. impostor.uniqueId = this._impostors.push(impostor);
  33201. //if no parent, generate the body
  33202. if (!impostor.parent) {
  33203. this._physicsPlugin.generatePhysicsBody(impostor);
  33204. }
  33205. };
  33206. /**
  33207. * Remove an impostor from the engine.
  33208. * This impostor and its mesh will not longer be updated by the physics engine.
  33209. * @param {PhysicsImpostor} impostor the impostor to remove
  33210. */
  33211. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  33212. var index = this._impostors.indexOf(impostor);
  33213. if (index > -1) {
  33214. var removed = this._impostors.splice(index, 1);
  33215. //Is it needed?
  33216. if (removed.length) {
  33217. //this will also remove it from the world.
  33218. removed[0].physicsBody = null;
  33219. }
  33220. }
  33221. };
  33222. /**
  33223. * Add a joint to the physics engine
  33224. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  33225. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  33226. * @param {PhysicsJoint} the joint that will connect both impostors.
  33227. */
  33228. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  33229. var impostorJoint = {
  33230. mainImpostor: mainImpostor,
  33231. connectedImpostor: connectedImpostor,
  33232. joint: joint
  33233. };
  33234. joint.physicsPlugin = this._physicsPlugin;
  33235. this._joints.push(impostorJoint);
  33236. this._physicsPlugin.generateJoint(impostorJoint);
  33237. };
  33238. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  33239. var matchingJoints = this._joints.filter(function (impostorJoint) {
  33240. return (impostorJoint.connectedImpostor === connectedImpostor
  33241. && impostorJoint.joint === joint
  33242. && impostorJoint.mainImpostor === mainImpostor);
  33243. });
  33244. if (matchingJoints.length) {
  33245. this._physicsPlugin.removeJoint(matchingJoints[0]);
  33246. }
  33247. };
  33248. /**
  33249. * Called by the scene. no need to call it.
  33250. */
  33251. PhysicsEngine.prototype._step = function (delta) {
  33252. var _this = this;
  33253. //check if any mesh has no body / requires an update
  33254. this._impostors.forEach(function (impostor) {
  33255. if (impostor.isBodyInitRequired()) {
  33256. _this._physicsPlugin.generatePhysicsBody(impostor);
  33257. }
  33258. });
  33259. if (delta > 0.1) {
  33260. delta = 0.1;
  33261. }
  33262. else if (delta <= 0) {
  33263. delta = 1.0 / 60.0;
  33264. }
  33265. this._physicsPlugin.executeStep(delta, this._impostors);
  33266. };
  33267. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  33268. return this._physicsPlugin;
  33269. };
  33270. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  33271. for (var i = 0; i < this._impostors.length; ++i) {
  33272. if (this._impostors[i].object === object) {
  33273. return this._impostors[i];
  33274. }
  33275. }
  33276. };
  33277. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  33278. for (var i = 0; i < this._impostors.length; ++i) {
  33279. if (this._impostors[i].physicsBody === body) {
  33280. return this._impostors[i];
  33281. }
  33282. }
  33283. };
  33284. return PhysicsEngine;
  33285. }());
  33286. // Statics, Legacy support.
  33287. /**
  33288. * @Deprecated
  33289. *
  33290. */
  33291. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  33292. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  33293. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  33294. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  33295. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  33296. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  33297. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  33298. PhysicsEngine.CapsuleImpostor = -1;
  33299. PhysicsEngine.ConeImpostor = -1;
  33300. PhysicsEngine.ConvexHullImpostor = -1;
  33301. PhysicsEngine.Epsilon = 0.001;
  33302. BABYLON.PhysicsEngine = PhysicsEngine;
  33303. })(BABYLON || (BABYLON = {}));
  33304. //# sourceMappingURL=babylon.physicsEngine.js.map
  33305. var BABYLON;
  33306. (function (BABYLON) {
  33307. var VertexData = (function () {
  33308. function VertexData() {
  33309. }
  33310. VertexData.prototype.set = function (data, kind) {
  33311. switch (kind) {
  33312. case BABYLON.VertexBuffer.PositionKind:
  33313. this.positions = data;
  33314. break;
  33315. case BABYLON.VertexBuffer.NormalKind:
  33316. this.normals = data;
  33317. break;
  33318. case BABYLON.VertexBuffer.UVKind:
  33319. this.uvs = data;
  33320. break;
  33321. case BABYLON.VertexBuffer.UV2Kind:
  33322. this.uvs2 = data;
  33323. break;
  33324. case BABYLON.VertexBuffer.UV3Kind:
  33325. this.uvs3 = data;
  33326. break;
  33327. case BABYLON.VertexBuffer.UV4Kind:
  33328. this.uvs4 = data;
  33329. break;
  33330. case BABYLON.VertexBuffer.UV5Kind:
  33331. this.uvs5 = data;
  33332. break;
  33333. case BABYLON.VertexBuffer.UV6Kind:
  33334. this.uvs6 = data;
  33335. break;
  33336. case BABYLON.VertexBuffer.ColorKind:
  33337. this.colors = data;
  33338. break;
  33339. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33340. this.matricesIndices = data;
  33341. break;
  33342. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33343. this.matricesWeights = data;
  33344. break;
  33345. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33346. this.matricesIndicesExtra = data;
  33347. break;
  33348. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33349. this.matricesWeightsExtra = data;
  33350. break;
  33351. }
  33352. };
  33353. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33354. this._applyTo(mesh, updatable);
  33355. };
  33356. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33357. this._applyTo(geometry, updatable);
  33358. };
  33359. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33360. this._update(mesh);
  33361. };
  33362. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33363. this._update(geometry);
  33364. };
  33365. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33366. if (this.positions) {
  33367. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33368. }
  33369. if (this.normals) {
  33370. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33371. }
  33372. if (this.uvs) {
  33373. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33374. }
  33375. if (this.uvs2) {
  33376. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33377. }
  33378. if (this.uvs3) {
  33379. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33380. }
  33381. if (this.uvs4) {
  33382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33383. }
  33384. if (this.uvs5) {
  33385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33386. }
  33387. if (this.uvs6) {
  33388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33389. }
  33390. if (this.colors) {
  33391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33392. }
  33393. if (this.matricesIndices) {
  33394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33395. }
  33396. if (this.matricesWeights) {
  33397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33398. }
  33399. if (this.matricesIndicesExtra) {
  33400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33401. }
  33402. if (this.matricesWeightsExtra) {
  33403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33404. }
  33405. if (this.indices) {
  33406. meshOrGeometry.setIndices(this.indices);
  33407. }
  33408. };
  33409. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33410. if (this.positions) {
  33411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33412. }
  33413. if (this.normals) {
  33414. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33415. }
  33416. if (this.uvs) {
  33417. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33418. }
  33419. if (this.uvs2) {
  33420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33421. }
  33422. if (this.uvs3) {
  33423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33424. }
  33425. if (this.uvs4) {
  33426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33427. }
  33428. if (this.uvs5) {
  33429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33430. }
  33431. if (this.uvs6) {
  33432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33433. }
  33434. if (this.colors) {
  33435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33436. }
  33437. if (this.matricesIndices) {
  33438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33439. }
  33440. if (this.matricesWeights) {
  33441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33442. }
  33443. if (this.matricesIndicesExtra) {
  33444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33445. }
  33446. if (this.matricesWeightsExtra) {
  33447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33448. }
  33449. if (this.indices) {
  33450. meshOrGeometry.setIndices(this.indices);
  33451. }
  33452. };
  33453. VertexData.prototype.transform = function (matrix) {
  33454. var transformed = BABYLON.Vector3.Zero();
  33455. var index;
  33456. if (this.positions) {
  33457. var position = BABYLON.Vector3.Zero();
  33458. for (index = 0; index < this.positions.length; index += 3) {
  33459. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33460. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33461. this.positions[index] = transformed.x;
  33462. this.positions[index + 1] = transformed.y;
  33463. this.positions[index + 2] = transformed.z;
  33464. }
  33465. }
  33466. if (this.normals) {
  33467. var normal = BABYLON.Vector3.Zero();
  33468. for (index = 0; index < this.normals.length; index += 3) {
  33469. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33470. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33471. this.normals[index] = transformed.x;
  33472. this.normals[index + 1] = transformed.y;
  33473. this.normals[index + 2] = transformed.z;
  33474. }
  33475. }
  33476. };
  33477. VertexData.prototype.merge = function (other) {
  33478. if (other.indices) {
  33479. if (!this.indices) {
  33480. this.indices = [];
  33481. }
  33482. var offset = this.positions ? this.positions.length / 3 : 0;
  33483. for (var index = 0; index < other.indices.length; index++) {
  33484. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33485. this.indices.push(other.indices[index] + offset);
  33486. }
  33487. }
  33488. this.positions = this._mergeElement(this.positions, other.positions);
  33489. this.normals = this._mergeElement(this.normals, other.normals);
  33490. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33491. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33492. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33493. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33494. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33495. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33496. this.colors = this._mergeElement(this.colors, other.colors);
  33497. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33498. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33499. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33500. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33501. };
  33502. VertexData.prototype._mergeElement = function (source, other) {
  33503. if (!other)
  33504. return source;
  33505. if (!source)
  33506. return other;
  33507. var len = other.length + source.length;
  33508. var isSrcTypedArray = source instanceof Float32Array;
  33509. var isOthTypedArray = other instanceof Float32Array;
  33510. // use non-loop method when the source is Float32Array
  33511. if (isSrcTypedArray) {
  33512. var ret32 = new Float32Array(len);
  33513. ret32.set(source);
  33514. ret32.set(other, source.length);
  33515. return ret32;
  33516. }
  33517. else if (!isOthTypedArray) {
  33518. return source.concat(other);
  33519. }
  33520. else {
  33521. var ret = source.slice(0); // copy source to a separate array
  33522. for (var i = 0, len = other.length; i < len; i++) {
  33523. ret.push(other[i]);
  33524. }
  33525. return ret;
  33526. }
  33527. };
  33528. VertexData.prototype.serialize = function () {
  33529. var serializationObject = this.serialize();
  33530. if (this.positions) {
  33531. serializationObject.positions = this.positions;
  33532. }
  33533. if (this.normals) {
  33534. serializationObject.normals = this.normals;
  33535. }
  33536. if (this.uvs) {
  33537. serializationObject.uvs = this.uvs;
  33538. }
  33539. if (this.uvs2) {
  33540. serializationObject.uvs2 = this.uvs2;
  33541. }
  33542. if (this.uvs3) {
  33543. serializationObject.uvs3 = this.uvs3;
  33544. }
  33545. if (this.uvs4) {
  33546. serializationObject.uvs4 = this.uvs4;
  33547. }
  33548. if (this.uvs5) {
  33549. serializationObject.uvs5 = this.uvs5;
  33550. }
  33551. if (this.uvs6) {
  33552. serializationObject.uvs6 = this.uvs6;
  33553. }
  33554. if (this.colors) {
  33555. serializationObject.colors = this.colors;
  33556. }
  33557. if (this.matricesIndices) {
  33558. serializationObject.matricesIndices = this.matricesIndices;
  33559. serializationObject.matricesIndices._isExpanded = true;
  33560. }
  33561. if (this.matricesWeights) {
  33562. serializationObject.matricesWeights = this.matricesWeights;
  33563. }
  33564. if (this.matricesIndicesExtra) {
  33565. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33566. serializationObject.matricesIndicesExtra._isExpanded = true;
  33567. }
  33568. if (this.matricesWeightsExtra) {
  33569. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33570. }
  33571. serializationObject.indices = this.indices;
  33572. return serializationObject;
  33573. };
  33574. // Statics
  33575. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  33576. return VertexData._ExtractFrom(mesh, copyWhenShared);
  33577. };
  33578. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  33579. return VertexData._ExtractFrom(geometry, copyWhenShared);
  33580. };
  33581. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  33582. var result = new VertexData();
  33583. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33584. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  33585. }
  33586. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33587. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  33588. }
  33589. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33590. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  33591. }
  33592. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33593. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  33594. }
  33595. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33596. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  33597. }
  33598. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33599. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  33600. }
  33601. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33602. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  33603. }
  33604. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33605. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  33606. }
  33607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33608. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  33609. }
  33610. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33611. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  33612. }
  33613. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33614. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  33615. }
  33616. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33617. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  33618. }
  33619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33620. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  33621. }
  33622. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33623. return result;
  33624. };
  33625. VertexData.CreateRibbon = function (options) {
  33626. var pathArray = options.pathArray;
  33627. var closeArray = options.closeArray || false;
  33628. var closePath = options.closePath || false;
  33629. var invertUV = options.invertUV || false;
  33630. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33631. var offset = options.offset || defaultOffset;
  33632. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33633. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33634. var positions = [];
  33635. var indices = [];
  33636. var normals = [];
  33637. var uvs = [];
  33638. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33639. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33640. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33641. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33642. var minlg; // minimal length among all paths from pathArray
  33643. var lg = []; // array of path lengths : nb of vertex per path
  33644. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33645. var p; // path iterator
  33646. var i; // point iterator
  33647. var j; // point iterator
  33648. // if single path in pathArray
  33649. if (pathArray.length < 2) {
  33650. var ar1 = [];
  33651. var ar2 = [];
  33652. for (i = 0; i < pathArray[0].length - offset; i++) {
  33653. ar1.push(pathArray[0][i]);
  33654. ar2.push(pathArray[0][i + offset]);
  33655. }
  33656. pathArray = [ar1, ar2];
  33657. }
  33658. // positions and horizontal distances (u)
  33659. var idc = 0;
  33660. var closePathCorr = (closePath) ? 1 : 0;
  33661. var path;
  33662. var l;
  33663. minlg = pathArray[0].length;
  33664. var vectlg;
  33665. var dist;
  33666. for (p = 0; p < pathArray.length; p++) {
  33667. uTotalDistance[p] = 0;
  33668. us[p] = [0];
  33669. path = pathArray[p];
  33670. l = path.length;
  33671. minlg = (minlg < l) ? minlg : l;
  33672. j = 0;
  33673. while (j < l) {
  33674. positions.push(path[j].x, path[j].y, path[j].z);
  33675. if (j > 0) {
  33676. vectlg = path[j].subtract(path[j - 1]).length();
  33677. dist = vectlg + uTotalDistance[p];
  33678. us[p].push(dist);
  33679. uTotalDistance[p] = dist;
  33680. }
  33681. j++;
  33682. }
  33683. if (closePath) {
  33684. j--;
  33685. positions.push(path[0].x, path[0].y, path[0].z);
  33686. vectlg = path[j].subtract(path[0]).length();
  33687. dist = vectlg + uTotalDistance[p];
  33688. us[p].push(dist);
  33689. uTotalDistance[p] = dist;
  33690. }
  33691. lg[p] = l + closePathCorr;
  33692. idx[p] = idc;
  33693. idc += (l + closePathCorr);
  33694. }
  33695. // vertical distances (v)
  33696. var path1;
  33697. var path2;
  33698. var vertex1;
  33699. var vertex2;
  33700. for (i = 0; i < minlg + closePathCorr; i++) {
  33701. vTotalDistance[i] = 0;
  33702. vs[i] = [0];
  33703. for (p = 0; p < pathArray.length - 1; p++) {
  33704. path1 = pathArray[p];
  33705. path2 = pathArray[p + 1];
  33706. if (i === minlg) {
  33707. vertex1 = path1[0];
  33708. vertex2 = path2[0];
  33709. }
  33710. else {
  33711. vertex1 = path1[i];
  33712. vertex2 = path2[i];
  33713. }
  33714. vectlg = vertex2.subtract(vertex1).length();
  33715. dist = vectlg + vTotalDistance[i];
  33716. vs[i].push(dist);
  33717. vTotalDistance[i] = dist;
  33718. }
  33719. if (closeArray) {
  33720. path1 = pathArray[p];
  33721. path2 = pathArray[0];
  33722. if (i === minlg) {
  33723. vertex2 = path2[0];
  33724. }
  33725. vectlg = vertex2.subtract(vertex1).length();
  33726. dist = vectlg + vTotalDistance[i];
  33727. vTotalDistance[i] = dist;
  33728. }
  33729. }
  33730. // uvs
  33731. var u;
  33732. var v;
  33733. for (p = 0; p < pathArray.length; p++) {
  33734. for (i = 0; i < minlg + closePathCorr; i++) {
  33735. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33736. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33737. if (invertUV) {
  33738. uvs.push(v, u);
  33739. }
  33740. else {
  33741. uvs.push(u, v);
  33742. }
  33743. }
  33744. }
  33745. // indices
  33746. p = 0; // path index
  33747. var pi = 0; // positions array index
  33748. var l1 = lg[p] - 1; // path1 length
  33749. var l2 = lg[p + 1] - 1; // path2 length
  33750. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33751. var shft = idx[1] - idx[0]; // shift
  33752. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33753. while (pi <= min && p < path1nb) {
  33754. // 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
  33755. indices.push(pi, pi + shft, pi + 1);
  33756. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33757. pi += 1;
  33758. if (pi === min) {
  33759. p++;
  33760. if (p === lg.length - 1) {
  33761. shft = idx[0] - idx[p];
  33762. l1 = lg[p] - 1;
  33763. l2 = lg[0] - 1;
  33764. }
  33765. else {
  33766. shft = idx[p + 1] - idx[p];
  33767. l1 = lg[p] - 1;
  33768. l2 = lg[p + 1] - 1;
  33769. }
  33770. pi = idx[p];
  33771. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33772. }
  33773. }
  33774. // normals
  33775. VertexData.ComputeNormals(positions, indices, normals);
  33776. if (closePath) {
  33777. var indexFirst = 0;
  33778. var indexLast = 0;
  33779. for (p = 0; p < pathArray.length; p++) {
  33780. indexFirst = idx[p] * 3;
  33781. if (p + 1 < pathArray.length) {
  33782. indexLast = (idx[p + 1] - 1) * 3;
  33783. }
  33784. else {
  33785. indexLast = normals.length - 3;
  33786. }
  33787. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33788. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33789. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33790. normals[indexLast] = normals[indexFirst];
  33791. normals[indexLast + 1] = normals[indexFirst + 1];
  33792. normals[indexLast + 2] = normals[indexFirst + 2];
  33793. }
  33794. }
  33795. // sides
  33796. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33797. // Result
  33798. var vertexData = new VertexData();
  33799. vertexData.indices = indices;
  33800. vertexData.positions = positions;
  33801. vertexData.normals = normals;
  33802. vertexData.uvs = uvs;
  33803. if (closePath) {
  33804. vertexData._idx = idx;
  33805. }
  33806. return vertexData;
  33807. };
  33808. VertexData.CreateBox = function (options) {
  33809. var normalsSource = [
  33810. new BABYLON.Vector3(0, 0, 1),
  33811. new BABYLON.Vector3(0, 0, -1),
  33812. new BABYLON.Vector3(1, 0, 0),
  33813. new BABYLON.Vector3(-1, 0, 0),
  33814. new BABYLON.Vector3(0, 1, 0),
  33815. new BABYLON.Vector3(0, -1, 0)
  33816. ];
  33817. var indices = [];
  33818. var positions = [];
  33819. var normals = [];
  33820. var uvs = [];
  33821. var width = options.width || options.size || 1;
  33822. var height = options.height || options.size || 1;
  33823. var depth = options.depth || options.size || 1;
  33824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33825. var faceUV = options.faceUV || new Array(6);
  33826. var faceColors = options.faceColors;
  33827. var colors = [];
  33828. // default face colors and UV if undefined
  33829. for (var f = 0; f < 6; f++) {
  33830. if (faceUV[f] === undefined) {
  33831. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33832. }
  33833. if (faceColors && faceColors[f] === undefined) {
  33834. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33835. }
  33836. }
  33837. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33838. // Create each face in turn.
  33839. for (var index = 0; index < normalsSource.length; index++) {
  33840. var normal = normalsSource[index];
  33841. // Get two vectors perpendicular to the face normal and to each other.
  33842. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33843. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33844. // Six indices (two triangles) per face.
  33845. var verticesLength = positions.length / 3;
  33846. indices.push(verticesLength);
  33847. indices.push(verticesLength + 1);
  33848. indices.push(verticesLength + 2);
  33849. indices.push(verticesLength);
  33850. indices.push(verticesLength + 2);
  33851. indices.push(verticesLength + 3);
  33852. // Four vertices per face.
  33853. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33854. positions.push(vertex.x, vertex.y, vertex.z);
  33855. normals.push(normal.x, normal.y, normal.z);
  33856. uvs.push(faceUV[index].z, faceUV[index].w);
  33857. if (faceColors) {
  33858. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33859. }
  33860. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33861. positions.push(vertex.x, vertex.y, vertex.z);
  33862. normals.push(normal.x, normal.y, normal.z);
  33863. uvs.push(faceUV[index].x, faceUV[index].w);
  33864. if (faceColors) {
  33865. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33866. }
  33867. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33868. positions.push(vertex.x, vertex.y, vertex.z);
  33869. normals.push(normal.x, normal.y, normal.z);
  33870. uvs.push(faceUV[index].x, faceUV[index].y);
  33871. if (faceColors) {
  33872. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33873. }
  33874. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33875. positions.push(vertex.x, vertex.y, vertex.z);
  33876. normals.push(normal.x, normal.y, normal.z);
  33877. uvs.push(faceUV[index].z, faceUV[index].y);
  33878. if (faceColors) {
  33879. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33880. }
  33881. }
  33882. // sides
  33883. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33884. // Result
  33885. var vertexData = new VertexData();
  33886. vertexData.indices = indices;
  33887. vertexData.positions = positions;
  33888. vertexData.normals = normals;
  33889. vertexData.uvs = uvs;
  33890. if (faceColors) {
  33891. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33892. vertexData.colors = totalColors;
  33893. }
  33894. return vertexData;
  33895. };
  33896. VertexData.CreateSphere = function (options) {
  33897. var segments = options.segments || 32;
  33898. var diameterX = options.diameterX || options.diameter || 1;
  33899. var diameterY = options.diameterY || options.diameter || 1;
  33900. var diameterZ = options.diameterZ || options.diameter || 1;
  33901. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33902. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33903. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33904. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33905. var totalZRotationSteps = 2 + segments;
  33906. var totalYRotationSteps = 2 * totalZRotationSteps;
  33907. var indices = [];
  33908. var positions = [];
  33909. var normals = [];
  33910. var uvs = [];
  33911. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33912. var normalizedZ = zRotationStep / totalZRotationSteps;
  33913. var angleZ = normalizedZ * Math.PI * slice;
  33914. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33915. var normalizedY = yRotationStep / totalYRotationSteps;
  33916. var angleY = normalizedY * Math.PI * 2 * arc;
  33917. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33918. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33919. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33920. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33921. var vertex = complete.multiply(radius);
  33922. var normal = complete.divide(radius).normalize();
  33923. positions.push(vertex.x, vertex.y, vertex.z);
  33924. normals.push(normal.x, normal.y, normal.z);
  33925. uvs.push(normalizedY, normalizedZ);
  33926. }
  33927. if (zRotationStep > 0) {
  33928. var verticesCount = positions.length / 3;
  33929. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33930. indices.push((firstIndex));
  33931. indices.push((firstIndex + 1));
  33932. indices.push(firstIndex + totalYRotationSteps + 1);
  33933. indices.push((firstIndex + totalYRotationSteps + 1));
  33934. indices.push((firstIndex + 1));
  33935. indices.push((firstIndex + totalYRotationSteps + 2));
  33936. }
  33937. }
  33938. }
  33939. // Sides
  33940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33941. // Result
  33942. var vertexData = new VertexData();
  33943. vertexData.indices = indices;
  33944. vertexData.positions = positions;
  33945. vertexData.normals = normals;
  33946. vertexData.uvs = uvs;
  33947. return vertexData;
  33948. };
  33949. // Cylinder and cone
  33950. VertexData.CreateCylinder = function (options) {
  33951. var height = options.height || 2;
  33952. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33953. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33954. var tessellation = options.tessellation || 24;
  33955. var subdivisions = options.subdivisions || 1;
  33956. var hasRings = options.hasRings;
  33957. var enclose = options.enclose;
  33958. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33960. var faceUV = options.faceUV || new Array(3);
  33961. var faceColors = options.faceColors;
  33962. // default face colors and UV if undefined
  33963. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33964. var ringNb = (hasRings) ? subdivisions : 1;
  33965. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33966. var f;
  33967. for (f = 0; f < surfaceNb; f++) {
  33968. if (faceColors && faceColors[f] === undefined) {
  33969. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33970. }
  33971. }
  33972. for (f = 0; f < surfaceNb; f++) {
  33973. if (faceUV && faceUV[f] === undefined) {
  33974. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33975. }
  33976. }
  33977. var indices = [];
  33978. var positions = [];
  33979. var normals = [];
  33980. var uvs = [];
  33981. var colors = [];
  33982. var angle_step = Math.PI * 2 * arc / tessellation;
  33983. var angle;
  33984. var h;
  33985. var radius;
  33986. var tan = (diameterBottom - diameterTop) / 2 / height;
  33987. var ringVertex = BABYLON.Vector3.Zero();
  33988. var ringNormal = BABYLON.Vector3.Zero();
  33989. var ringFirstVertex = BABYLON.Vector3.Zero();
  33990. var ringFirstNormal = BABYLON.Vector3.Zero();
  33991. var quadNormal = BABYLON.Vector3.Zero();
  33992. var Y = BABYLON.Axis.Y;
  33993. // positions, normals, uvs
  33994. var i;
  33995. var j;
  33996. var r;
  33997. var ringIdx = 1;
  33998. var s = 1; // surface index
  33999. var cs = 0;
  34000. var v = 0;
  34001. for (i = 0; i <= subdivisions; i++) {
  34002. h = i / subdivisions;
  34003. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  34004. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  34005. for (r = 0; r < ringIdx; r++) {
  34006. if (hasRings) {
  34007. s += r;
  34008. }
  34009. if (enclose) {
  34010. s += 2 * r;
  34011. }
  34012. for (j = 0; j <= tessellation; j++) {
  34013. angle = j * angle_step;
  34014. // position
  34015. ringVertex.x = Math.cos(-angle) * radius;
  34016. ringVertex.y = -height / 2 + h * height;
  34017. ringVertex.z = Math.sin(-angle) * radius;
  34018. // normal
  34019. if (diameterTop === 0 && i === subdivisions) {
  34020. // if no top cap, reuse former normals
  34021. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  34022. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  34023. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  34024. }
  34025. else {
  34026. ringNormal.x = ringVertex.x;
  34027. ringNormal.z = ringVertex.z;
  34028. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  34029. ringNormal.normalize();
  34030. }
  34031. // keep first ring vertex values for enclose
  34032. if (j === 0) {
  34033. ringFirstVertex.copyFrom(ringVertex);
  34034. ringFirstNormal.copyFrom(ringNormal);
  34035. }
  34036. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34037. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  34038. if (hasRings) {
  34039. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  34040. }
  34041. else {
  34042. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  34043. }
  34044. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  34045. if (faceColors) {
  34046. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  34047. }
  34048. }
  34049. // if enclose, add four vertices and their dedicated normals
  34050. if (arc !== 1 && enclose) {
  34051. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34052. positions.push(0, ringVertex.y, 0);
  34053. positions.push(0, ringVertex.y, 0);
  34054. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  34055. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  34056. quadNormal.normalize();
  34057. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34058. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  34059. quadNormal.normalize();
  34060. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34061. if (hasRings) {
  34062. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  34063. }
  34064. else {
  34065. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  34066. }
  34067. uvs.push(faceUV[s + 1].x, v);
  34068. uvs.push(faceUV[s + 1].z, v);
  34069. if (hasRings) {
  34070. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  34071. }
  34072. else {
  34073. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  34074. }
  34075. uvs.push(faceUV[s + 2].x, v);
  34076. uvs.push(faceUV[s + 2].z, v);
  34077. if (faceColors) {
  34078. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34079. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34080. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34081. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34082. }
  34083. }
  34084. if (cs !== s) {
  34085. cs = s;
  34086. }
  34087. }
  34088. }
  34089. // indices
  34090. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  34091. var s;
  34092. i = 0;
  34093. for (s = 0; s < subdivisions; s++) {
  34094. for (j = 0; j < tessellation; j++) {
  34095. var i0 = i * (e + 1) + j;
  34096. var i1 = (i + 1) * (e + 1) + j;
  34097. var i2 = i * (e + 1) + (j + 1);
  34098. var i3 = (i + 1) * (e + 1) + (j + 1);
  34099. indices.push(i0, i1, i2);
  34100. indices.push(i3, i2, i1);
  34101. }
  34102. if (arc !== 1 && enclose) {
  34103. indices.push(i0 + 2, i1 + 2, i2 + 2);
  34104. indices.push(i3 + 2, i2 + 2, i1 + 2);
  34105. indices.push(i0 + 4, i1 + 4, i2 + 4);
  34106. indices.push(i3 + 4, i2 + 4, i1 + 4);
  34107. }
  34108. i = (hasRings) ? (i + 2) : (i + 1);
  34109. }
  34110. // Caps
  34111. var createCylinderCap = function (isTop) {
  34112. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  34113. if (radius === 0) {
  34114. return;
  34115. }
  34116. // Cap positions, normals & uvs
  34117. var angle;
  34118. var circleVector;
  34119. var i;
  34120. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  34121. var c;
  34122. if (faceColors) {
  34123. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  34124. }
  34125. // cap center
  34126. var vbase = positions.length / 3;
  34127. var offset = isTop ? height / 2 : -height / 2;
  34128. var center = new BABYLON.Vector3(0, offset, 0);
  34129. positions.push(center.x, center.y, center.z);
  34130. normals.push(0, isTop ? 1 : -1, 0);
  34131. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34132. if (faceColors) {
  34133. colors.push(c.r, c.g, c.b, c.a);
  34134. }
  34135. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34136. for (i = 0; i <= tessellation; i++) {
  34137. angle = Math.PI * 2 * i * arc / tessellation;
  34138. var cos = Math.cos(-angle);
  34139. var sin = Math.sin(-angle);
  34140. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34141. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34142. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34143. normals.push(0, isTop ? 1 : -1, 0);
  34144. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34145. if (faceColors) {
  34146. colors.push(c.r, c.g, c.b, c.a);
  34147. }
  34148. }
  34149. // Cap indices
  34150. for (i = 0; i < tessellation; i++) {
  34151. if (!isTop) {
  34152. indices.push(vbase);
  34153. indices.push(vbase + (i + 1));
  34154. indices.push(vbase + (i + 2));
  34155. }
  34156. else {
  34157. indices.push(vbase);
  34158. indices.push(vbase + (i + 2));
  34159. indices.push(vbase + (i + 1));
  34160. }
  34161. }
  34162. };
  34163. // add caps to geometry
  34164. createCylinderCap(false);
  34165. createCylinderCap(true);
  34166. // Sides
  34167. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34168. var vertexData = new VertexData();
  34169. vertexData.indices = indices;
  34170. vertexData.positions = positions;
  34171. vertexData.normals = normals;
  34172. vertexData.uvs = uvs;
  34173. if (faceColors) {
  34174. vertexData.colors = colors;
  34175. }
  34176. return vertexData;
  34177. };
  34178. VertexData.CreateTorus = function (options) {
  34179. var indices = [];
  34180. var positions = [];
  34181. var normals = [];
  34182. var uvs = [];
  34183. var diameter = options.diameter || 1;
  34184. var thickness = options.thickness || 0.5;
  34185. var tessellation = options.tessellation || 16;
  34186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34187. var stride = tessellation + 1;
  34188. for (var i = 0; i <= tessellation; i++) {
  34189. var u = i / tessellation;
  34190. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34191. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34192. for (var j = 0; j <= tessellation; j++) {
  34193. var v = 1 - j / tessellation;
  34194. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34195. var dx = Math.cos(innerAngle);
  34196. var dy = Math.sin(innerAngle);
  34197. // Create a vertex.
  34198. var normal = new BABYLON.Vector3(dx, dy, 0);
  34199. var position = normal.scale(thickness / 2);
  34200. var textureCoordinate = new BABYLON.Vector2(u, v);
  34201. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34202. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34203. positions.push(position.x, position.y, position.z);
  34204. normals.push(normal.x, normal.y, normal.z);
  34205. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34206. // And create indices for two triangles.
  34207. var nextI = (i + 1) % stride;
  34208. var nextJ = (j + 1) % stride;
  34209. indices.push(i * stride + j);
  34210. indices.push(i * stride + nextJ);
  34211. indices.push(nextI * stride + j);
  34212. indices.push(i * stride + nextJ);
  34213. indices.push(nextI * stride + nextJ);
  34214. indices.push(nextI * stride + j);
  34215. }
  34216. }
  34217. // Sides
  34218. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34219. // Result
  34220. var vertexData = new VertexData();
  34221. vertexData.indices = indices;
  34222. vertexData.positions = positions;
  34223. vertexData.normals = normals;
  34224. vertexData.uvs = uvs;
  34225. return vertexData;
  34226. };
  34227. VertexData.CreateLineSystem = function (options) {
  34228. var indices = [];
  34229. var positions = [];
  34230. var lines = options.lines;
  34231. var idx = 0;
  34232. for (var l = 0; l < lines.length; l++) {
  34233. var points = lines[l];
  34234. for (var index = 0; index < points.length; index++) {
  34235. positions.push(points[index].x, points[index].y, points[index].z);
  34236. if (index > 0) {
  34237. indices.push(idx - 1);
  34238. indices.push(idx);
  34239. }
  34240. idx++;
  34241. }
  34242. }
  34243. var vertexData = new VertexData();
  34244. vertexData.indices = indices;
  34245. vertexData.positions = positions;
  34246. return vertexData;
  34247. };
  34248. VertexData.CreateDashedLines = function (options) {
  34249. var dashSize = options.dashSize || 3;
  34250. var gapSize = options.gapSize || 1;
  34251. var dashNb = options.dashNb || 200;
  34252. var points = options.points;
  34253. var positions = new Array();
  34254. var indices = new Array();
  34255. var curvect = BABYLON.Vector3.Zero();
  34256. var lg = 0;
  34257. var nb = 0;
  34258. var shft = 0;
  34259. var dashshft = 0;
  34260. var curshft = 0;
  34261. var idx = 0;
  34262. var i = 0;
  34263. for (i = 0; i < points.length - 1; i++) {
  34264. points[i + 1].subtractToRef(points[i], curvect);
  34265. lg += curvect.length();
  34266. }
  34267. shft = lg / dashNb;
  34268. dashshft = dashSize * shft / (dashSize + gapSize);
  34269. for (i = 0; i < points.length - 1; i++) {
  34270. points[i + 1].subtractToRef(points[i], curvect);
  34271. nb = Math.floor(curvect.length() / shft);
  34272. curvect.normalize();
  34273. for (var j = 0; j < nb; j++) {
  34274. curshft = shft * j;
  34275. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34276. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34277. indices.push(idx, idx + 1);
  34278. idx += 2;
  34279. }
  34280. }
  34281. // Result
  34282. var vertexData = new VertexData();
  34283. vertexData.positions = positions;
  34284. vertexData.indices = indices;
  34285. return vertexData;
  34286. };
  34287. VertexData.CreateGround = function (options) {
  34288. var indices = [];
  34289. var positions = [];
  34290. var normals = [];
  34291. var uvs = [];
  34292. var row, col;
  34293. var width = options.width || 1;
  34294. var height = options.height || 1;
  34295. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34296. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34297. for (row = 0; row <= subdivisionsY; row++) {
  34298. for (col = 0; col <= subdivisionsX; col++) {
  34299. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34300. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34301. positions.push(position.x, position.y, position.z);
  34302. normals.push(normal.x, normal.y, normal.z);
  34303. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34304. }
  34305. }
  34306. for (row = 0; row < subdivisionsY; row++) {
  34307. for (col = 0; col < subdivisionsX; col++) {
  34308. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34309. indices.push(col + 1 + row * (subdivisionsX + 1));
  34310. indices.push(col + row * (subdivisionsX + 1));
  34311. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34312. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34313. indices.push(col + row * (subdivisionsX + 1));
  34314. }
  34315. }
  34316. // Result
  34317. var vertexData = new VertexData();
  34318. vertexData.indices = indices;
  34319. vertexData.positions = positions;
  34320. vertexData.normals = normals;
  34321. vertexData.uvs = uvs;
  34322. return vertexData;
  34323. };
  34324. VertexData.CreateTiledGround = function (options) {
  34325. var xmin = options.xmin || -1.0;
  34326. var zmin = options.zmin || -1.0;
  34327. var xmax = options.xmax || 1.0;
  34328. var zmax = options.zmax || 1.0;
  34329. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34330. var precision = options.precision || { w: 1, h: 1 };
  34331. var indices = [];
  34332. var positions = [];
  34333. var normals = [];
  34334. var uvs = [];
  34335. var row, col, tileRow, tileCol;
  34336. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34337. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34338. precision.w = (precision.w < 1) ? 1 : precision.w;
  34339. precision.h = (precision.h < 1) ? 1 : precision.h;
  34340. var tileSize = {
  34341. 'w': (xmax - xmin) / subdivisions.w,
  34342. 'h': (zmax - zmin) / subdivisions.h
  34343. };
  34344. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34345. // Indices
  34346. var base = positions.length / 3;
  34347. var rowLength = precision.w + 1;
  34348. for (row = 0; row < precision.h; row++) {
  34349. for (col = 0; col < precision.w; col++) {
  34350. var square = [
  34351. base + col + row * rowLength,
  34352. base + (col + 1) + row * rowLength,
  34353. base + (col + 1) + (row + 1) * rowLength,
  34354. base + col + (row + 1) * rowLength
  34355. ];
  34356. indices.push(square[1]);
  34357. indices.push(square[2]);
  34358. indices.push(square[3]);
  34359. indices.push(square[0]);
  34360. indices.push(square[1]);
  34361. indices.push(square[3]);
  34362. }
  34363. }
  34364. // Position, normals and uvs
  34365. var position = BABYLON.Vector3.Zero();
  34366. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34367. for (row = 0; row <= precision.h; row++) {
  34368. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34369. for (col = 0; col <= precision.w; col++) {
  34370. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34371. position.y = 0;
  34372. positions.push(position.x, position.y, position.z);
  34373. normals.push(normal.x, normal.y, normal.z);
  34374. uvs.push(col / precision.w, row / precision.h);
  34375. }
  34376. }
  34377. }
  34378. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34379. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34380. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34381. }
  34382. }
  34383. // Result
  34384. var vertexData = new VertexData();
  34385. vertexData.indices = indices;
  34386. vertexData.positions = positions;
  34387. vertexData.normals = normals;
  34388. vertexData.uvs = uvs;
  34389. return vertexData;
  34390. };
  34391. VertexData.CreateGroundFromHeightMap = function (options) {
  34392. var indices = [];
  34393. var positions = [];
  34394. var normals = [];
  34395. var uvs = [];
  34396. var row, col;
  34397. // Vertices
  34398. for (row = 0; row <= options.subdivisions; row++) {
  34399. for (col = 0; col <= options.subdivisions; col++) {
  34400. 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));
  34401. // Compute height
  34402. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34403. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34404. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34405. var r = options.buffer[pos] / 255.0;
  34406. var g = options.buffer[pos + 1] / 255.0;
  34407. var b = options.buffer[pos + 2] / 255.0;
  34408. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34409. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34410. // Add vertex
  34411. positions.push(position.x, position.y, position.z);
  34412. normals.push(0, 0, 0);
  34413. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34414. }
  34415. }
  34416. // Indices
  34417. for (row = 0; row < options.subdivisions; row++) {
  34418. for (col = 0; col < options.subdivisions; col++) {
  34419. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34420. indices.push(col + 1 + row * (options.subdivisions + 1));
  34421. indices.push(col + row * (options.subdivisions + 1));
  34422. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34423. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34424. indices.push(col + row * (options.subdivisions + 1));
  34425. }
  34426. }
  34427. // Normals
  34428. VertexData.ComputeNormals(positions, indices, normals);
  34429. // Result
  34430. var vertexData = new VertexData();
  34431. vertexData.indices = indices;
  34432. vertexData.positions = positions;
  34433. vertexData.normals = normals;
  34434. vertexData.uvs = uvs;
  34435. return vertexData;
  34436. };
  34437. VertexData.CreatePlane = function (options) {
  34438. var indices = [];
  34439. var positions = [];
  34440. var normals = [];
  34441. var uvs = [];
  34442. var width = options.width || options.size || 1;
  34443. var height = options.height || options.size || 1;
  34444. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34445. // Vertices
  34446. var halfWidth = width / 2.0;
  34447. var halfHeight = height / 2.0;
  34448. positions.push(-halfWidth, -halfHeight, 0);
  34449. normals.push(0, 0, -1.0);
  34450. uvs.push(0.0, 0.0);
  34451. positions.push(halfWidth, -halfHeight, 0);
  34452. normals.push(0, 0, -1.0);
  34453. uvs.push(1.0, 0.0);
  34454. positions.push(halfWidth, halfHeight, 0);
  34455. normals.push(0, 0, -1.0);
  34456. uvs.push(1.0, 1.0);
  34457. positions.push(-halfWidth, halfHeight, 0);
  34458. normals.push(0, 0, -1.0);
  34459. uvs.push(0.0, 1.0);
  34460. // Indices
  34461. indices.push(0);
  34462. indices.push(1);
  34463. indices.push(2);
  34464. indices.push(0);
  34465. indices.push(2);
  34466. indices.push(3);
  34467. // Sides
  34468. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34469. // Result
  34470. var vertexData = new VertexData();
  34471. vertexData.indices = indices;
  34472. vertexData.positions = positions;
  34473. vertexData.normals = normals;
  34474. vertexData.uvs = uvs;
  34475. return vertexData;
  34476. };
  34477. VertexData.CreateDisc = function (options) {
  34478. var positions = [];
  34479. var indices = [];
  34480. var normals = [];
  34481. var uvs = [];
  34482. var radius = options.radius || 0.5;
  34483. var tessellation = options.tessellation || 64;
  34484. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34485. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34486. // positions and uvs
  34487. positions.push(0, 0, 0); // disc center first
  34488. uvs.push(0.5, 0.5);
  34489. var theta = Math.PI * 2 * arc;
  34490. var step = theta / tessellation;
  34491. for (var a = 0; a < theta; a += step) {
  34492. var x = Math.cos(a);
  34493. var y = Math.sin(a);
  34494. var u = (x + 1) / 2;
  34495. var v = (1 - y) / 2;
  34496. positions.push(radius * x, radius * y, 0);
  34497. uvs.push(u, v);
  34498. }
  34499. if (arc === 1) {
  34500. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34501. uvs.push(uvs[2], uvs[3]);
  34502. }
  34503. //indices
  34504. var vertexNb = positions.length / 3;
  34505. for (var i = 1; i < vertexNb - 1; i++) {
  34506. indices.push(i + 1, 0, i);
  34507. }
  34508. // result
  34509. VertexData.ComputeNormals(positions, indices, normals);
  34510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34511. var vertexData = new VertexData();
  34512. vertexData.indices = indices;
  34513. vertexData.positions = positions;
  34514. vertexData.normals = normals;
  34515. vertexData.uvs = uvs;
  34516. return vertexData;
  34517. };
  34518. VertexData.CreateIcoSphere = function (options) {
  34519. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34520. var radius = options.radius || 1;
  34521. var flat = (options.flat === undefined) ? true : options.flat;
  34522. var subdivisions = options.subdivisions || 4;
  34523. var radiusX = options.radiusX || radius;
  34524. var radiusY = options.radiusY || radius;
  34525. var radiusZ = options.radiusZ || radius;
  34526. var t = (1 + Math.sqrt(5)) / 2;
  34527. // 12 vertex x,y,z
  34528. var ico_vertices = [
  34529. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34530. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34531. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34532. ];
  34533. // index of 3 vertex makes a face of icopshere
  34534. var ico_indices = [
  34535. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34536. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34537. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34538. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34539. ];
  34540. // vertex for uv have aliased position, not for UV
  34541. var vertices_unalias_id = [
  34542. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34543. // vertex alias
  34544. 0,
  34545. 2,
  34546. 3,
  34547. 3,
  34548. 3,
  34549. 4,
  34550. 7,
  34551. 8,
  34552. 9,
  34553. 9,
  34554. 10,
  34555. 11 // 23: B + 12
  34556. ];
  34557. // uv as integer step (not pixels !)
  34558. var ico_vertexuv = [
  34559. 5, 1, 3, 1, 6, 4, 0, 0,
  34560. 5, 3, 4, 2, 2, 2, 4, 0,
  34561. 2, 0, 1, 1, 6, 0, 6, 2,
  34562. // vertex alias (for same vertex on different faces)
  34563. 0, 4,
  34564. 3, 3,
  34565. 4, 4,
  34566. 3, 1,
  34567. 4, 2,
  34568. 4, 4,
  34569. 0, 2,
  34570. 1, 1,
  34571. 2, 2,
  34572. 3, 3,
  34573. 1, 3,
  34574. 2, 4 // 23: B + 12
  34575. ];
  34576. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34577. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34578. // First island of uv mapping
  34579. // v = 4h 3+ 2
  34580. // v = 3h 9+ 4
  34581. // v = 2h 9+ 5 B
  34582. // v = 1h 9 1 0
  34583. // v = 0h 3 8 7 A
  34584. // u = 0 1 2 3 4 5 6 *a
  34585. // Second island of uv mapping
  34586. // v = 4h 0+ B+ 4+
  34587. // v = 3h A+ 2+
  34588. // v = 2h 7+ 6 3+
  34589. // v = 1h 8+ 3+
  34590. // v = 0h
  34591. // u = 0 1 2 3 4 5 6 *a
  34592. // Face layout on texture UV mapping
  34593. // ============
  34594. // \ 4 /\ 16 / ======
  34595. // \ / \ / /\ 11 /
  34596. // \/ 7 \/ / \ /
  34597. // ======= / 10 \/
  34598. // /\ 17 /\ =======
  34599. // / \ / \ \ 15 /\
  34600. // / 8 \/ 12 \ \ / \
  34601. // ============ \/ 6 \
  34602. // \ 18 /\ ============
  34603. // \ / \ \ 5 /\ 0 /
  34604. // \/ 13 \ \ / \ /
  34605. // ======= \/ 1 \/
  34606. // =============
  34607. // /\ 19 /\ 2 /\
  34608. // / \ / \ / \
  34609. // / 14 \/ 9 \/ 3 \
  34610. // ===================
  34611. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34612. var ustep = 138 / 1024;
  34613. var vstep = 239 / 1024;
  34614. var uoffset = 60 / 1024;
  34615. var voffset = 26 / 1024;
  34616. // Second island should have margin, not to touch the first island
  34617. // avoid any borderline artefact in pixel rounding
  34618. var island_u_offset = -40 / 1024;
  34619. var island_v_offset = +20 / 1024;
  34620. // face is either island 0 or 1 :
  34621. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34622. var island = [
  34623. 0, 0, 0, 0, 1,
  34624. 0, 0, 1, 1, 0,
  34625. 0, 0, 1, 1, 0,
  34626. 0, 1, 1, 1, 0 // 15 - 19
  34627. ];
  34628. var indices = [];
  34629. var positions = [];
  34630. var normals = [];
  34631. var uvs = [];
  34632. var current_indice = 0;
  34633. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34634. var face_vertex_pos = new Array(3);
  34635. var face_vertex_uv = new Array(3);
  34636. var v012;
  34637. for (v012 = 0; v012 < 3; v012++) {
  34638. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34639. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34640. }
  34641. // create all with normals
  34642. for (var face = 0; face < 20; face++) {
  34643. // 3 vertex per face
  34644. for (v012 = 0; v012 < 3; v012++) {
  34645. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34646. var v_id = ico_indices[3 * face + v012];
  34647. // vertex have 3D position (x,y,z)
  34648. 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]);
  34649. // Normalize to get normal, then scale to radius
  34650. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34651. // uv Coordinates from vertex ID
  34652. 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);
  34653. }
  34654. // Subdivide the face (interpolate pos, norm, uv)
  34655. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34656. // - norm is linear interpolation of vertex corner normal
  34657. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34658. // - uv is linear interpolation
  34659. //
  34660. // Topology is as below for sub-divide by 2
  34661. // vertex shown as v0,v1,v2
  34662. // interp index is i1 to progress in range [v0,v1[
  34663. // interp index is i2 to progress in range [v0,v2[
  34664. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34665. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34666. //
  34667. //
  34668. // i2 v2
  34669. // ^ ^
  34670. // / / \
  34671. // / / \
  34672. // / / \
  34673. // / / (0,1) \
  34674. // / #---------\
  34675. // / / \ (0,0)'/ \
  34676. // / / \ / \
  34677. // / / \ / \
  34678. // / / (0,0) \ / (1,0) \
  34679. // / #---------#---------\
  34680. // v0 v1
  34681. //
  34682. // --------------------> i1
  34683. //
  34684. // interp of (i1,i2):
  34685. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34686. // along i1 : lerp(x0,x1, i1/(S-i2))
  34687. //
  34688. // centroid of triangle is needed to get help normal computation
  34689. // (c1,c2) are used for centroid location
  34690. var interp_vertex = function (i1, i2, c1, c2) {
  34691. // vertex is interpolated from
  34692. // - face_vertex_pos[0..2]
  34693. // - face_vertex_uv[0..2]
  34694. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34695. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34696. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34697. pos_interp.normalize();
  34698. var vertex_normal;
  34699. if (flat) {
  34700. // in flat mode, recalculate normal as face centroid normal
  34701. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34702. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34703. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34704. }
  34705. else {
  34706. // in smooth mode, recalculate normal from each single vertex position
  34707. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34708. }
  34709. // Vertex normal need correction due to X,Y,Z radius scaling
  34710. vertex_normal.x /= radiusX;
  34711. vertex_normal.y /= radiusY;
  34712. vertex_normal.z /= radiusZ;
  34713. vertex_normal.normalize();
  34714. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34715. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34716. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34717. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34718. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34719. uvs.push(uv_interp.x, uv_interp.y);
  34720. // push each vertex has member of a face
  34721. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34722. indices.push(current_indice);
  34723. current_indice++;
  34724. };
  34725. for (var i2 = 0; i2 < subdivisions; i2++) {
  34726. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34727. // face : (i1,i2) for /\ :
  34728. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34729. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34730. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34731. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34732. if (i1 + i2 + 1 < subdivisions) {
  34733. // face : (i1,i2)' for \/ :
  34734. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34735. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34736. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34737. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34738. }
  34739. }
  34740. }
  34741. }
  34742. // Sides
  34743. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34744. // Result
  34745. var vertexData = new VertexData();
  34746. vertexData.indices = indices;
  34747. vertexData.positions = positions;
  34748. vertexData.normals = normals;
  34749. vertexData.uvs = uvs;
  34750. return vertexData;
  34751. };
  34752. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34753. VertexData.CreatePolyhedron = function (options) {
  34754. // provided polyhedron types :
  34755. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34756. // 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)
  34757. var polyhedra = [];
  34758. 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]] };
  34759. 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]] };
  34760. polyhedra[2] = {
  34761. 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]],
  34762. 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]]
  34763. };
  34764. polyhedra[3] = {
  34765. 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]],
  34766. 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]]
  34767. };
  34768. polyhedra[4] = {
  34769. 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]],
  34770. 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]]
  34771. };
  34772. 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]] };
  34773. 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]] };
  34774. 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]] };
  34775. 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]] };
  34776. 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]] };
  34777. 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]] };
  34778. 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]] };
  34779. 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]] };
  34780. 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]] };
  34781. polyhedra[14] = {
  34782. 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]],
  34783. 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]]
  34784. };
  34785. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34786. var size = options.size;
  34787. var sizeX = options.sizeX || size || 1;
  34788. var sizeY = options.sizeY || size || 1;
  34789. var sizeZ = options.sizeZ || size || 1;
  34790. var data = options.custom || polyhedra[type];
  34791. var nbfaces = data.face.length;
  34792. var faceUV = options.faceUV || new Array(nbfaces);
  34793. var faceColors = options.faceColors;
  34794. var flat = (options.flat === undefined) ? true : options.flat;
  34795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34796. var positions = [];
  34797. var indices = [];
  34798. var normals = [];
  34799. var uvs = [];
  34800. var colors = [];
  34801. var index = 0;
  34802. var faceIdx = 0; // face cursor in the array "indexes"
  34803. var indexes = [];
  34804. var i = 0;
  34805. var f = 0;
  34806. var u, v, ang, x, y, tmp;
  34807. // default face colors and UV if undefined
  34808. if (flat) {
  34809. for (f = 0; f < nbfaces; f++) {
  34810. if (faceColors && faceColors[f] === undefined) {
  34811. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34812. }
  34813. if (faceUV && faceUV[f] === undefined) {
  34814. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34815. }
  34816. }
  34817. }
  34818. if (!flat) {
  34819. for (i = 0; i < data.vertex.length; i++) {
  34820. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34821. uvs.push(0, 0);
  34822. }
  34823. for (f = 0; f < nbfaces; f++) {
  34824. for (i = 0; i < data.face[f].length - 2; i++) {
  34825. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34826. }
  34827. }
  34828. }
  34829. else {
  34830. for (f = 0; f < nbfaces; f++) {
  34831. var fl = data.face[f].length; // number of vertices of the current face
  34832. ang = 2 * Math.PI / fl;
  34833. x = 0.5 * Math.tan(ang / 2);
  34834. y = 0.5;
  34835. // positions, uvs, colors
  34836. for (i = 0; i < fl; i++) {
  34837. // positions
  34838. 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);
  34839. indexes.push(index);
  34840. index++;
  34841. // uvs
  34842. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34843. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34844. uvs.push(u, v);
  34845. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34846. y = x * Math.sin(ang) + y * Math.cos(ang);
  34847. x = tmp;
  34848. // colors
  34849. if (faceColors) {
  34850. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34851. }
  34852. }
  34853. // indices from indexes
  34854. for (i = 0; i < fl - 2; i++) {
  34855. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34856. }
  34857. faceIdx += fl;
  34858. }
  34859. }
  34860. VertexData.ComputeNormals(positions, indices, normals);
  34861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34862. var vertexData = new VertexData();
  34863. vertexData.positions = positions;
  34864. vertexData.indices = indices;
  34865. vertexData.normals = normals;
  34866. vertexData.uvs = uvs;
  34867. if (faceColors && flat) {
  34868. vertexData.colors = colors;
  34869. }
  34870. return vertexData;
  34871. };
  34872. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34873. VertexData.CreateTorusKnot = function (options) {
  34874. var indices = [];
  34875. var positions = [];
  34876. var normals = [];
  34877. var uvs = [];
  34878. var radius = options.radius || 2;
  34879. var tube = options.tube || 0.5;
  34880. var radialSegments = options.radialSegments || 32;
  34881. var tubularSegments = options.tubularSegments || 32;
  34882. var p = options.p || 2;
  34883. var q = options.q || 3;
  34884. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34885. // Helper
  34886. var getPos = function (angle) {
  34887. var cu = Math.cos(angle);
  34888. var su = Math.sin(angle);
  34889. var quOverP = q / p * angle;
  34890. var cs = Math.cos(quOverP);
  34891. var tx = radius * (2 + cs) * 0.5 * cu;
  34892. var ty = radius * (2 + cs) * su * 0.5;
  34893. var tz = radius * Math.sin(quOverP) * 0.5;
  34894. return new BABYLON.Vector3(tx, ty, tz);
  34895. };
  34896. // Vertices
  34897. var i;
  34898. var j;
  34899. for (i = 0; i <= radialSegments; i++) {
  34900. var modI = i % radialSegments;
  34901. var u = modI / radialSegments * 2 * p * Math.PI;
  34902. var p1 = getPos(u);
  34903. var p2 = getPos(u + 0.01);
  34904. var tang = p2.subtract(p1);
  34905. var n = p2.add(p1);
  34906. var bitan = BABYLON.Vector3.Cross(tang, n);
  34907. n = BABYLON.Vector3.Cross(bitan, tang);
  34908. bitan.normalize();
  34909. n.normalize();
  34910. for (j = 0; j < tubularSegments; j++) {
  34911. var modJ = j % tubularSegments;
  34912. var v = modJ / tubularSegments * 2 * Math.PI;
  34913. var cx = -tube * Math.cos(v);
  34914. var cy = tube * Math.sin(v);
  34915. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34916. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34917. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34918. uvs.push(i / radialSegments);
  34919. uvs.push(j / tubularSegments);
  34920. }
  34921. }
  34922. for (i = 0; i < radialSegments; i++) {
  34923. for (j = 0; j < tubularSegments; j++) {
  34924. var jNext = (j + 1) % tubularSegments;
  34925. var a = i * tubularSegments + j;
  34926. var b = (i + 1) * tubularSegments + j;
  34927. var c = (i + 1) * tubularSegments + jNext;
  34928. var d = i * tubularSegments + jNext;
  34929. indices.push(d);
  34930. indices.push(b);
  34931. indices.push(a);
  34932. indices.push(d);
  34933. indices.push(c);
  34934. indices.push(b);
  34935. }
  34936. }
  34937. // Normals
  34938. VertexData.ComputeNormals(positions, indices, normals);
  34939. // Sides
  34940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34941. // Result
  34942. var vertexData = new VertexData();
  34943. vertexData.indices = indices;
  34944. vertexData.positions = positions;
  34945. vertexData.normals = normals;
  34946. vertexData.uvs = uvs;
  34947. return vertexData;
  34948. };
  34949. // Tools
  34950. /**
  34951. * @param {any} - positions (number[] or Float32Array)
  34952. * @param {any} - indices (number[] or Uint16Array)
  34953. * @param {any} - normals (number[] or Float32Array)
  34954. * options (optional) :
  34955. * facetPositions : optional array of facet positions (vector3)
  34956. * facetNormals : optional array of facet normals (vector3)
  34957. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34958. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34959. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34960. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34961. * bInfo : optional bounding info, required for facetPartitioning computation
  34962. */
  34963. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34964. // temporary scalar variables
  34965. var index = 0; // facet index
  34966. var p1p2x = 0.0; // p1p2 vector x coordinate
  34967. var p1p2y = 0.0; // p1p2 vector y coordinate
  34968. var p1p2z = 0.0; // p1p2 vector z coordinate
  34969. var p3p2x = 0.0; // p3p2 vector x coordinate
  34970. var p3p2y = 0.0; // p3p2 vector y coordinate
  34971. var p3p2z = 0.0; // p3p2 vector z coordinate
  34972. var faceNormalx = 0.0; // facet normal x coordinate
  34973. var faceNormaly = 0.0; // facet normal y coordinate
  34974. var faceNormalz = 0.0; // facet normal z coordinate
  34975. var length = 0.0; // facet normal length before normalization
  34976. var v1x = 0; // vector1 x index in the positions array
  34977. var v1y = 0; // vector1 y index in the positions array
  34978. var v1z = 0; // vector1 z index in the positions array
  34979. var v2x = 0; // vector2 x index in the positions array
  34980. var v2y = 0; // vector2 y index in the positions array
  34981. var v2z = 0; // vector2 z index in the positions array
  34982. var v3x = 0; // vector3 x index in the positions array
  34983. var v3y = 0; // vector3 y index in the positions array
  34984. var v3z = 0; // vector3 z index in the positions array
  34985. var computeFacetNormals = false;
  34986. var computeFacetPositions = false;
  34987. var computeFacetPartitioning = false;
  34988. if (options) {
  34989. computeFacetNormals = (options.facetNormals) ? true : false;
  34990. computeFacetPositions = (options.facetPositions) ? true : false;
  34991. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34992. }
  34993. // facetPartitioning reinit if needed
  34994. if (computeFacetPartitioning) {
  34995. var ox = 0; // X partitioning index for facet position
  34996. var oy = 0; // Y partinioning index for facet position
  34997. var oz = 0; // Z partinioning index for facet position
  34998. var b1x = 0; // X partitioning index for facet v1 vertex
  34999. var b1y = 0; // Y partitioning index for facet v1 vertex
  35000. var b1z = 0; // z partitioning index for facet v1 vertex
  35001. var b2x = 0; // X partitioning index for facet v2 vertex
  35002. var b2y = 0; // Y partitioning index for facet v2 vertex
  35003. var b2z = 0; // Z partitioning index for facet v2 vertex
  35004. var b3x = 0; // X partitioning index for facet v3 vertex
  35005. var b3y = 0; // Y partitioning index for facet v3 vertex
  35006. var b3z = 0; // Z partitioning index for facet v3 vertex
  35007. var block_idx_o = 0; // facet barycenter block index
  35008. var block_idx_v1 = 0; // v1 vertex block index
  35009. var block_idx_v2 = 0; // v2 vertex block index
  35010. var block_idx_v3 = 0; // v3 vertex block index
  35011. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35012. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35013. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  35014. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  35015. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  35016. var subSq = options.subDiv.max * options.subDiv.max;
  35017. options.facetPartitioning.length = 0;
  35018. }
  35019. // reset the normals
  35020. for (index = 0; index < positions.length; index++) {
  35021. normals[index] = 0.0;
  35022. }
  35023. // Loop : 1 indice triplet = 1 facet
  35024. var nbFaces = indices.length / 3;
  35025. for (index = 0; index < nbFaces; index++) {
  35026. // get the indexes of the coordinates of each vertex of the facet
  35027. v1x = indices[index * 3] * 3;
  35028. v1y = v1x + 1;
  35029. v1z = v1x + 2;
  35030. v2x = indices[index * 3 + 1] * 3;
  35031. v2y = v2x + 1;
  35032. v2z = v2x + 2;
  35033. v3x = indices[index * 3 + 2] * 3;
  35034. v3y = v3x + 1;
  35035. v3z = v3x + 2;
  35036. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35037. p1p2y = positions[v1y] - positions[v2y];
  35038. p1p2z = positions[v1z] - positions[v2z];
  35039. p3p2x = positions[v3x] - positions[v2x];
  35040. p3p2y = positions[v3y] - positions[v2y];
  35041. p3p2z = positions[v3z] - positions[v2z];
  35042. // compute the face normal with the cross product
  35043. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  35044. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  35045. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  35046. // normalize this normal and store it in the array facetData
  35047. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35048. length = (length === 0) ? 1.0 : length;
  35049. faceNormalx /= length;
  35050. faceNormaly /= length;
  35051. faceNormalz /= length;
  35052. if (computeFacetNormals) {
  35053. options.facetNormals[index].x = faceNormalx;
  35054. options.facetNormals[index].y = faceNormaly;
  35055. options.facetNormals[index].z = faceNormalz;
  35056. }
  35057. if (computeFacetPositions) {
  35058. // compute and the facet barycenter coordinates in the array facetPositions
  35059. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35060. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35061. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35062. }
  35063. if (computeFacetPartitioning) {
  35064. // store the facet indexes in arrays in the main facetPartitioning array :
  35065. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35066. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35067. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35068. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35069. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35070. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35071. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35072. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35073. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35074. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35075. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35076. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35077. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35078. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35079. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35080. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35081. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35082. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35083. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35084. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35085. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35086. // push each facet index in each block containing the vertex
  35087. options.facetPartitioning[block_idx_v1].push(index);
  35088. if (block_idx_v2 != block_idx_v1) {
  35089. options.facetPartitioning[block_idx_v2].push(index);
  35090. }
  35091. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35092. options.facetPartitioning[block_idx_v3].push(index);
  35093. }
  35094. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35095. options.facetPartitioning[block_idx_o].push(index);
  35096. }
  35097. }
  35098. // compute the normals anyway
  35099. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35100. normals[v1y] += faceNormaly;
  35101. normals[v1z] += faceNormalz;
  35102. normals[v2x] += faceNormalx;
  35103. normals[v2y] += faceNormaly;
  35104. normals[v2z] += faceNormalz;
  35105. normals[v3x] += faceNormalx;
  35106. normals[v3y] += faceNormaly;
  35107. normals[v3z] += faceNormalz;
  35108. }
  35109. // last normalization of each normal
  35110. for (index = 0; index < normals.length / 3; index++) {
  35111. faceNormalx = normals[index * 3];
  35112. faceNormaly = normals[index * 3 + 1];
  35113. faceNormalz = normals[index * 3 + 2];
  35114. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35115. length = (length === 0) ? 1.0 : length;
  35116. faceNormalx /= length;
  35117. faceNormaly /= length;
  35118. faceNormalz /= length;
  35119. normals[index * 3] = faceNormalx;
  35120. normals[index * 3 + 1] = faceNormaly;
  35121. normals[index * 3 + 2] = faceNormalz;
  35122. }
  35123. };
  35124. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  35125. var li = indices.length;
  35126. var ln = normals.length;
  35127. var i;
  35128. var n;
  35129. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35130. switch (sideOrientation) {
  35131. case BABYLON.Mesh.FRONTSIDE:
  35132. // nothing changed
  35133. break;
  35134. case BABYLON.Mesh.BACKSIDE:
  35135. var tmp;
  35136. // indices
  35137. for (i = 0; i < li; i += 3) {
  35138. tmp = indices[i];
  35139. indices[i] = indices[i + 2];
  35140. indices[i + 2] = tmp;
  35141. }
  35142. // normals
  35143. for (n = 0; n < ln; n++) {
  35144. normals[n] = -normals[n];
  35145. }
  35146. break;
  35147. case BABYLON.Mesh.DOUBLESIDE:
  35148. // positions
  35149. var lp = positions.length;
  35150. var l = lp / 3;
  35151. for (var p = 0; p < lp; p++) {
  35152. positions[lp + p] = positions[p];
  35153. }
  35154. // indices
  35155. for (i = 0; i < li; i += 3) {
  35156. indices[i + li] = indices[i + 2] + l;
  35157. indices[i + 1 + li] = indices[i + 1] + l;
  35158. indices[i + 2 + li] = indices[i] + l;
  35159. }
  35160. // normals
  35161. for (n = 0; n < ln; n++) {
  35162. normals[ln + n] = -normals[n];
  35163. }
  35164. // uvs
  35165. var lu = uvs.length;
  35166. for (var u = 0; u < lu; u++) {
  35167. uvs[u + lu] = uvs[u];
  35168. }
  35169. break;
  35170. }
  35171. };
  35172. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35173. var vertexData = new VertexData();
  35174. // positions
  35175. var positions = parsedVertexData.positions;
  35176. if (positions) {
  35177. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35178. }
  35179. // normals
  35180. var normals = parsedVertexData.normals;
  35181. if (normals) {
  35182. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35183. }
  35184. // uvs
  35185. var uvs = parsedVertexData.uvs;
  35186. if (uvs) {
  35187. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35188. }
  35189. // uv2s
  35190. var uv2s = parsedVertexData.uv2s;
  35191. if (uv2s) {
  35192. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35193. }
  35194. // uv3s
  35195. var uv3s = parsedVertexData.uv3s;
  35196. if (uv3s) {
  35197. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35198. }
  35199. // uv4s
  35200. var uv4s = parsedVertexData.uv4s;
  35201. if (uv4s) {
  35202. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35203. }
  35204. // uv5s
  35205. var uv5s = parsedVertexData.uv5s;
  35206. if (uv5s) {
  35207. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35208. }
  35209. // uv6s
  35210. var uv6s = parsedVertexData.uv6s;
  35211. if (uv6s) {
  35212. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35213. }
  35214. // colors
  35215. var colors = parsedVertexData.colors;
  35216. if (colors) {
  35217. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35218. }
  35219. // matricesIndices
  35220. var matricesIndices = parsedVertexData.matricesIndices;
  35221. if (matricesIndices) {
  35222. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35223. }
  35224. // matricesWeights
  35225. var matricesWeights = parsedVertexData.matricesWeights;
  35226. if (matricesWeights) {
  35227. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35228. }
  35229. // indices
  35230. var indices = parsedVertexData.indices;
  35231. if (indices) {
  35232. vertexData.indices = indices;
  35233. }
  35234. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35235. };
  35236. return VertexData;
  35237. }());
  35238. BABYLON.VertexData = VertexData;
  35239. })(BABYLON || (BABYLON = {}));
  35240. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35241. var BABYLON;
  35242. (function (BABYLON) {
  35243. var Tags = (function () {
  35244. function Tags() {
  35245. }
  35246. Tags.EnableFor = function (obj) {
  35247. obj._tags = obj._tags || {};
  35248. obj.hasTags = function () {
  35249. return Tags.HasTags(obj);
  35250. };
  35251. obj.addTags = function (tagsString) {
  35252. return Tags.AddTagsTo(obj, tagsString);
  35253. };
  35254. obj.removeTags = function (tagsString) {
  35255. return Tags.RemoveTagsFrom(obj, tagsString);
  35256. };
  35257. obj.matchesTagsQuery = function (tagsQuery) {
  35258. return Tags.MatchesQuery(obj, tagsQuery);
  35259. };
  35260. };
  35261. Tags.DisableFor = function (obj) {
  35262. delete obj._tags;
  35263. delete obj.hasTags;
  35264. delete obj.addTags;
  35265. delete obj.removeTags;
  35266. delete obj.matchesTagsQuery;
  35267. };
  35268. Tags.HasTags = function (obj) {
  35269. if (!obj._tags) {
  35270. return false;
  35271. }
  35272. return !BABYLON.Tools.IsEmpty(obj._tags);
  35273. };
  35274. Tags.GetTags = function (obj, asString) {
  35275. if (asString === void 0) { asString = true; }
  35276. if (!obj._tags) {
  35277. return null;
  35278. }
  35279. if (asString) {
  35280. var tagsArray = [];
  35281. for (var tag in obj._tags) {
  35282. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  35283. tagsArray.push(tag);
  35284. }
  35285. }
  35286. return tagsArray.join(" ");
  35287. }
  35288. else {
  35289. return obj._tags;
  35290. }
  35291. };
  35292. // the tags 'true' and 'false' are reserved and cannot be used as tags
  35293. // a tag cannot start with '||', '&&', and '!'
  35294. // it cannot contain whitespaces
  35295. Tags.AddTagsTo = function (obj, tagsString) {
  35296. if (!tagsString) {
  35297. return;
  35298. }
  35299. if (typeof tagsString !== "string") {
  35300. return;
  35301. }
  35302. var tags = tagsString.split(" ");
  35303. tags.forEach(function (tag, index, array) {
  35304. Tags._AddTagTo(obj, tag);
  35305. });
  35306. };
  35307. Tags._AddTagTo = function (obj, tag) {
  35308. tag = tag.trim();
  35309. if (tag === "" || tag === "true" || tag === "false") {
  35310. return;
  35311. }
  35312. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  35313. return;
  35314. }
  35315. Tags.EnableFor(obj);
  35316. obj._tags[tag] = true;
  35317. };
  35318. Tags.RemoveTagsFrom = function (obj, tagsString) {
  35319. if (!Tags.HasTags(obj)) {
  35320. return;
  35321. }
  35322. var tags = tagsString.split(" ");
  35323. for (var t in tags) {
  35324. Tags._RemoveTagFrom(obj, tags[t]);
  35325. }
  35326. };
  35327. Tags._RemoveTagFrom = function (obj, tag) {
  35328. delete obj._tags[tag];
  35329. };
  35330. Tags.MatchesQuery = function (obj, tagsQuery) {
  35331. if (tagsQuery === undefined) {
  35332. return true;
  35333. }
  35334. if (tagsQuery === "") {
  35335. return Tags.HasTags(obj);
  35336. }
  35337. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  35338. };
  35339. return Tags;
  35340. }());
  35341. BABYLON.Tags = Tags;
  35342. })(BABYLON || (BABYLON = {}));
  35343. //# sourceMappingURL=babylon.tags.js.map
  35344. var BABYLON;
  35345. (function (BABYLON) {
  35346. var Internals;
  35347. (function (Internals) {
  35348. var AndOrNotEvaluator = (function () {
  35349. function AndOrNotEvaluator() {
  35350. }
  35351. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  35352. if (!query.match(/\([^\(\)]*\)/g)) {
  35353. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  35354. }
  35355. else {
  35356. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  35357. // remove parenthesis
  35358. r = r.slice(1, r.length - 1);
  35359. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  35360. });
  35361. }
  35362. if (query === "true") {
  35363. return true;
  35364. }
  35365. if (query === "false") {
  35366. return false;
  35367. }
  35368. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  35369. };
  35370. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  35371. evaluateCallback = evaluateCallback || (function (r) {
  35372. return r === "true" ? true : false;
  35373. });
  35374. var result;
  35375. var or = parenthesisContent.split("||");
  35376. for (var i in or) {
  35377. if (or.hasOwnProperty(i)) {
  35378. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  35379. var and = ori.split("&&");
  35380. if (and.length > 1) {
  35381. for (var j = 0; j < and.length; ++j) {
  35382. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  35383. if (andj !== "true" && andj !== "false") {
  35384. if (andj[0] === "!") {
  35385. result = !evaluateCallback(andj.substring(1));
  35386. }
  35387. else {
  35388. result = evaluateCallback(andj);
  35389. }
  35390. }
  35391. else {
  35392. result = andj === "true" ? true : false;
  35393. }
  35394. if (!result) {
  35395. ori = "false";
  35396. break;
  35397. }
  35398. }
  35399. }
  35400. if (result || ori === "true") {
  35401. result = true;
  35402. break;
  35403. }
  35404. // result equals false (or undefined)
  35405. if (ori !== "true" && ori !== "false") {
  35406. if (ori[0] === "!") {
  35407. result = !evaluateCallback(ori.substring(1));
  35408. }
  35409. else {
  35410. result = evaluateCallback(ori);
  35411. }
  35412. }
  35413. else {
  35414. result = ori === "true" ? true : false;
  35415. }
  35416. }
  35417. }
  35418. // the whole parenthesis scope is replaced by 'true' or 'false'
  35419. return result ? "true" : "false";
  35420. };
  35421. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  35422. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  35423. // remove whitespaces
  35424. r = r.replace(/[\s]/g, function () { return ""; });
  35425. return r.length % 2 ? "!" : "";
  35426. });
  35427. booleanString = booleanString.trim();
  35428. if (booleanString === "!true") {
  35429. booleanString = "false";
  35430. }
  35431. else if (booleanString === "!false") {
  35432. booleanString = "true";
  35433. }
  35434. return booleanString;
  35435. };
  35436. return AndOrNotEvaluator;
  35437. }());
  35438. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  35439. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35440. })(BABYLON || (BABYLON = {}));
  35441. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  35442. var BABYLON;
  35443. (function (BABYLON) {
  35444. var PostProcessRenderPass = (function () {
  35445. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  35446. this._enabled = true;
  35447. this._refCount = 0;
  35448. this._name = name;
  35449. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  35450. this.setRenderList(renderList);
  35451. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  35452. this._renderTexture.onAfterRenderObservable.add(afterRender);
  35453. this._scene = scene;
  35454. this._renderList = renderList;
  35455. }
  35456. // private
  35457. PostProcessRenderPass.prototype._incRefCount = function () {
  35458. if (this._refCount === 0) {
  35459. this._scene.customRenderTargets.push(this._renderTexture);
  35460. }
  35461. return ++this._refCount;
  35462. };
  35463. PostProcessRenderPass.prototype._decRefCount = function () {
  35464. this._refCount--;
  35465. if (this._refCount <= 0) {
  35466. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  35467. }
  35468. return this._refCount;
  35469. };
  35470. PostProcessRenderPass.prototype._update = function () {
  35471. this.setRenderList(this._renderList);
  35472. };
  35473. // public
  35474. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  35475. this._renderTexture.renderList = renderList;
  35476. };
  35477. PostProcessRenderPass.prototype.getRenderTexture = function () {
  35478. return this._renderTexture;
  35479. };
  35480. return PostProcessRenderPass;
  35481. }());
  35482. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  35483. })(BABYLON || (BABYLON = {}));
  35484. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  35485. var BABYLON;
  35486. (function (BABYLON) {
  35487. var PostProcessRenderEffect = (function () {
  35488. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  35489. this._engine = engine;
  35490. this._name = name;
  35491. this._singleInstance = singleInstance || true;
  35492. this._getPostProcess = getPostProcess;
  35493. this._cameras = [];
  35494. this._indicesForCamera = [];
  35495. this._postProcesses = {};
  35496. this._renderPasses = {};
  35497. this._renderEffectAsPasses = {};
  35498. }
  35499. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  35500. get: function () {
  35501. for (var index in this._postProcesses) {
  35502. if (!this._postProcesses[index].isSupported) {
  35503. return false;
  35504. }
  35505. }
  35506. return true;
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. PostProcessRenderEffect.prototype._update = function () {
  35512. for (var renderPassName in this._renderPasses) {
  35513. this._renderPasses[renderPassName]._update();
  35514. }
  35515. };
  35516. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  35517. this._renderPasses[renderPass._name] = renderPass;
  35518. this._linkParameters();
  35519. };
  35520. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  35521. delete this._renderPasses[renderPass._name];
  35522. this._linkParameters();
  35523. };
  35524. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  35525. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  35526. this._linkParameters();
  35527. };
  35528. PostProcessRenderEffect.prototype.getPass = function (passName) {
  35529. for (var renderPassName in this._renderPasses) {
  35530. if (renderPassName === passName) {
  35531. return this._renderPasses[passName];
  35532. }
  35533. }
  35534. };
  35535. PostProcessRenderEffect.prototype.emptyPasses = function () {
  35536. this._renderPasses = {};
  35537. this._linkParameters();
  35538. };
  35539. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  35540. var cameraKey;
  35541. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35542. for (var i = 0; i < _cam.length; i++) {
  35543. var camera = _cam[i];
  35544. var cameraName = camera.name;
  35545. if (this._singleInstance) {
  35546. cameraKey = 0;
  35547. }
  35548. else {
  35549. cameraKey = cameraName;
  35550. }
  35551. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  35552. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  35553. if (!this._indicesForCamera[cameraName]) {
  35554. this._indicesForCamera[cameraName] = [];
  35555. }
  35556. this._indicesForCamera[cameraName].push(index);
  35557. if (this._cameras.indexOf(camera) === -1) {
  35558. this._cameras[cameraName] = camera;
  35559. }
  35560. for (var passName in this._renderPasses) {
  35561. this._renderPasses[passName]._incRefCount();
  35562. }
  35563. }
  35564. this._linkParameters();
  35565. };
  35566. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  35567. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35568. for (var i = 0; i < _cam.length; i++) {
  35569. var camera = _cam[i];
  35570. var cameraName = camera.name;
  35571. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35572. var index = this._cameras.indexOf(cameraName);
  35573. this._indicesForCamera.splice(index, 1);
  35574. this._cameras.splice(index, 1);
  35575. for (var passName in this._renderPasses) {
  35576. this._renderPasses[passName]._decRefCount();
  35577. }
  35578. }
  35579. };
  35580. PostProcessRenderEffect.prototype._enable = function (cameras) {
  35581. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35582. for (var i = 0; i < _cam.length; i++) {
  35583. var camera = _cam[i];
  35584. var cameraName = camera.name;
  35585. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  35586. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  35587. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  35588. }
  35589. }
  35590. for (var passName in this._renderPasses) {
  35591. this._renderPasses[passName]._incRefCount();
  35592. }
  35593. }
  35594. };
  35595. PostProcessRenderEffect.prototype._disable = function (cameras) {
  35596. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35597. for (var i = 0; i < _cam.length; i++) {
  35598. var camera = _cam[i];
  35599. var cameraName = camera.Name;
  35600. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35601. for (var passName in this._renderPasses) {
  35602. this._renderPasses[passName]._decRefCount();
  35603. }
  35604. }
  35605. };
  35606. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  35607. if (this._singleInstance) {
  35608. return this._postProcesses[0];
  35609. }
  35610. else {
  35611. return this._postProcesses[camera.name];
  35612. }
  35613. };
  35614. PostProcessRenderEffect.prototype._linkParameters = function () {
  35615. var _this = this;
  35616. for (var index in this._postProcesses) {
  35617. if (this.applyParameters) {
  35618. this.applyParameters(this._postProcesses[index]);
  35619. }
  35620. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  35621. _this._linkTextures(effect);
  35622. });
  35623. }
  35624. };
  35625. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  35626. for (var renderPassName in this._renderPasses) {
  35627. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  35628. }
  35629. for (var renderEffectName in this._renderEffectAsPasses) {
  35630. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  35631. }
  35632. };
  35633. return PostProcessRenderEffect;
  35634. }());
  35635. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  35636. })(BABYLON || (BABYLON = {}));
  35637. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  35638. var BABYLON;
  35639. (function (BABYLON) {
  35640. var PostProcessRenderPipeline = (function () {
  35641. function PostProcessRenderPipeline(engine, name) {
  35642. this._engine = engine;
  35643. this._name = name;
  35644. this._renderEffects = {};
  35645. this._renderEffectsForIsolatedPass = {};
  35646. this._cameras = [];
  35647. }
  35648. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  35649. get: function () {
  35650. for (var renderEffectName in this._renderEffects) {
  35651. if (!this._renderEffects[renderEffectName].isSupported) {
  35652. return false;
  35653. }
  35654. }
  35655. return true;
  35656. },
  35657. enumerable: true,
  35658. configurable: true
  35659. });
  35660. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  35661. this._renderEffects[renderEffect._name] = renderEffect;
  35662. };
  35663. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  35664. var renderEffects = this._renderEffects[renderEffectName];
  35665. if (!renderEffects) {
  35666. return;
  35667. }
  35668. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35669. };
  35670. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  35671. var renderEffects = this._renderEffects[renderEffectName];
  35672. if (!renderEffects) {
  35673. return;
  35674. }
  35675. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35676. };
  35677. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  35678. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35679. var indicesToDelete = [];
  35680. var i;
  35681. for (i = 0; i < _cam.length; i++) {
  35682. var camera = _cam[i];
  35683. var cameraName = camera.name;
  35684. if (this._cameras.indexOf(camera) === -1) {
  35685. this._cameras[cameraName] = camera;
  35686. }
  35687. else if (unique) {
  35688. indicesToDelete.push(i);
  35689. }
  35690. }
  35691. for (i = 0; i < indicesToDelete.length; i++) {
  35692. cameras.splice(indicesToDelete[i], 1);
  35693. }
  35694. for (var renderEffectName in this._renderEffects) {
  35695. this._renderEffects[renderEffectName]._attachCameras(_cam);
  35696. }
  35697. };
  35698. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  35699. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35700. for (var renderEffectName in this._renderEffects) {
  35701. this._renderEffects[renderEffectName]._detachCameras(_cam);
  35702. }
  35703. for (var i = 0; i < _cam.length; i++) {
  35704. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  35705. }
  35706. };
  35707. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  35708. var _this = this;
  35709. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35710. var pass = null;
  35711. var renderEffectName;
  35712. for (renderEffectName in this._renderEffects) {
  35713. pass = this._renderEffects[renderEffectName].getPass(passName);
  35714. if (pass != null) {
  35715. break;
  35716. }
  35717. }
  35718. if (pass === null) {
  35719. return;
  35720. }
  35721. for (renderEffectName in this._renderEffects) {
  35722. this._renderEffects[renderEffectName]._disable(_cam);
  35723. }
  35724. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  35725. for (var i = 0; i < _cam.length; i++) {
  35726. var camera = _cam[i];
  35727. var cameraName = camera.name;
  35728. 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); });
  35729. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  35730. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  35731. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  35732. }
  35733. };
  35734. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  35735. var _this = this;
  35736. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35737. for (var i = 0; i < _cam.length; i++) {
  35738. var camera = _cam[i];
  35739. var cameraName = camera.name;
  35740. 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); });
  35741. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  35742. }
  35743. for (var renderEffectName in this._renderEffects) {
  35744. this._renderEffects[renderEffectName]._enable(_cam);
  35745. }
  35746. };
  35747. PostProcessRenderPipeline.prototype._update = function () {
  35748. for (var renderEffectName in this._renderEffects) {
  35749. this._renderEffects[renderEffectName]._update();
  35750. }
  35751. for (var i = 0; i < this._cameras.length; i++) {
  35752. var cameraName = this._cameras[i].name;
  35753. if (this._renderEffectsForIsolatedPass[cameraName]) {
  35754. this._renderEffectsForIsolatedPass[cameraName]._update();
  35755. }
  35756. }
  35757. };
  35758. PostProcessRenderPipeline.prototype.dispose = function () {
  35759. // Must be implemented by children
  35760. };
  35761. return PostProcessRenderPipeline;
  35762. }());
  35763. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  35764. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  35765. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  35766. })(BABYLON || (BABYLON = {}));
  35767. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  35768. var BABYLON;
  35769. (function (BABYLON) {
  35770. var PostProcessRenderPipelineManager = (function () {
  35771. function PostProcessRenderPipelineManager() {
  35772. this._renderPipelines = {};
  35773. }
  35774. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  35775. this._renderPipelines[renderPipeline._name] = renderPipeline;
  35776. };
  35777. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  35778. var renderPipeline = this._renderPipelines[renderPipelineName];
  35779. if (!renderPipeline) {
  35780. return;
  35781. }
  35782. renderPipeline._attachCameras(cameras, unique);
  35783. };
  35784. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  35785. var renderPipeline = this._renderPipelines[renderPipelineName];
  35786. if (!renderPipeline) {
  35787. return;
  35788. }
  35789. renderPipeline._detachCameras(cameras);
  35790. };
  35791. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35792. var renderPipeline = this._renderPipelines[renderPipelineName];
  35793. if (!renderPipeline) {
  35794. return;
  35795. }
  35796. renderPipeline._enableEffect(renderEffectName, cameras);
  35797. };
  35798. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35799. var renderPipeline = this._renderPipelines[renderPipelineName];
  35800. if (!renderPipeline) {
  35801. return;
  35802. }
  35803. renderPipeline._disableEffect(renderEffectName, cameras);
  35804. };
  35805. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  35806. var renderPipeline = this._renderPipelines[renderPipelineName];
  35807. if (!renderPipeline) {
  35808. return;
  35809. }
  35810. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  35811. };
  35812. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  35813. var renderPipeline = this._renderPipelines[renderPipelineName];
  35814. if (!renderPipeline) {
  35815. return;
  35816. }
  35817. renderPipeline._disableDisplayOnlyPass(cameras);
  35818. };
  35819. PostProcessRenderPipelineManager.prototype.update = function () {
  35820. for (var renderPipelineName in this._renderPipelines) {
  35821. var pipeline = this._renderPipelines[renderPipelineName];
  35822. if (!pipeline.isSupported) {
  35823. pipeline.dispose();
  35824. delete this._renderPipelines[renderPipelineName];
  35825. }
  35826. else {
  35827. pipeline._update();
  35828. }
  35829. }
  35830. };
  35831. return PostProcessRenderPipelineManager;
  35832. }());
  35833. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  35834. })(BABYLON || (BABYLON = {}));
  35835. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  35836. var BABYLON;
  35837. (function (BABYLON) {
  35838. var BoundingBoxRenderer = (function () {
  35839. function BoundingBoxRenderer(scene) {
  35840. this.frontColor = new BABYLON.Color3(1, 1, 1);
  35841. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  35842. this.showBackLines = true;
  35843. this.renderList = new BABYLON.SmartArray(32);
  35844. this._vertexBuffers = {};
  35845. this._scene = scene;
  35846. }
  35847. BoundingBoxRenderer.prototype._prepareRessources = function () {
  35848. if (this._colorShader) {
  35849. return;
  35850. }
  35851. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  35852. attributes: [BABYLON.VertexBuffer.PositionKind],
  35853. uniforms: ["worldViewProjection", "color"]
  35854. });
  35855. var engine = this._scene.getEngine();
  35856. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  35857. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  35858. 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]);
  35859. };
  35860. BoundingBoxRenderer.prototype.reset = function () {
  35861. this.renderList.reset();
  35862. };
  35863. BoundingBoxRenderer.prototype.render = function () {
  35864. if (this.renderList.length === 0) {
  35865. return;
  35866. }
  35867. this._prepareRessources();
  35868. if (!this._colorShader.isReady()) {
  35869. return;
  35870. }
  35871. var engine = this._scene.getEngine();
  35872. engine.setDepthWrite(false);
  35873. this._colorShader._preBind();
  35874. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  35875. var boundingBox = this.renderList.data[boundingBoxIndex];
  35876. var min = boundingBox.minimum;
  35877. var max = boundingBox.maximum;
  35878. var diff = max.subtract(min);
  35879. var median = min.add(diff.scale(0.5));
  35880. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  35881. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  35882. .multiply(boundingBox.getWorldMatrix());
  35883. // VBOs
  35884. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  35885. if (this.showBackLines) {
  35886. // Back
  35887. engine.setDepthFunctionToGreaterOrEqual();
  35888. this._scene.resetCachedMaterial();
  35889. this._colorShader.setColor4("color", this.backColor.toColor4());
  35890. this._colorShader.bind(worldMatrix);
  35891. // Draw order
  35892. engine.draw(false, 0, 24);
  35893. }
  35894. // Front
  35895. engine.setDepthFunctionToLess();
  35896. this._scene.resetCachedMaterial();
  35897. this._colorShader.setColor4("color", this.frontColor.toColor4());
  35898. this._colorShader.bind(worldMatrix);
  35899. // Draw order
  35900. engine.draw(false, 0, 24);
  35901. }
  35902. this._colorShader.unbind();
  35903. engine.setDepthFunctionToLessOrEqual();
  35904. engine.setDepthWrite(true);
  35905. };
  35906. BoundingBoxRenderer.prototype.dispose = function () {
  35907. if (!this._colorShader) {
  35908. return;
  35909. }
  35910. this._colorShader.dispose();
  35911. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35912. if (buffer) {
  35913. buffer.dispose();
  35914. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35915. }
  35916. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35917. };
  35918. return BoundingBoxRenderer;
  35919. }());
  35920. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  35921. })(BABYLON || (BABYLON = {}));
  35922. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  35923. var BABYLON;
  35924. (function (BABYLON) {
  35925. var Condition = (function () {
  35926. function Condition(actionManager) {
  35927. this._actionManager = actionManager;
  35928. }
  35929. Condition.prototype.isValid = function () {
  35930. return true;
  35931. };
  35932. Condition.prototype._getProperty = function (propertyPath) {
  35933. return this._actionManager._getProperty(propertyPath);
  35934. };
  35935. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35936. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35937. };
  35938. Condition.prototype.serialize = function () {
  35939. };
  35940. Condition.prototype._serialize = function (serializedCondition) {
  35941. return {
  35942. type: 2,
  35943. children: [],
  35944. name: serializedCondition.name,
  35945. properties: serializedCondition.properties
  35946. };
  35947. };
  35948. return Condition;
  35949. }());
  35950. BABYLON.Condition = Condition;
  35951. var ValueCondition = (function (_super) {
  35952. __extends(ValueCondition, _super);
  35953. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35954. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35955. var _this = _super.call(this, actionManager) || this;
  35956. _this.propertyPath = propertyPath;
  35957. _this.value = value;
  35958. _this.operator = operator;
  35959. _this._target = target;
  35960. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35961. _this._property = _this._getProperty(_this.propertyPath);
  35962. return _this;
  35963. }
  35964. Object.defineProperty(ValueCondition, "IsEqual", {
  35965. get: function () {
  35966. return ValueCondition._IsEqual;
  35967. },
  35968. enumerable: true,
  35969. configurable: true
  35970. });
  35971. Object.defineProperty(ValueCondition, "IsDifferent", {
  35972. get: function () {
  35973. return ValueCondition._IsDifferent;
  35974. },
  35975. enumerable: true,
  35976. configurable: true
  35977. });
  35978. Object.defineProperty(ValueCondition, "IsGreater", {
  35979. get: function () {
  35980. return ValueCondition._IsGreater;
  35981. },
  35982. enumerable: true,
  35983. configurable: true
  35984. });
  35985. Object.defineProperty(ValueCondition, "IsLesser", {
  35986. get: function () {
  35987. return ValueCondition._IsLesser;
  35988. },
  35989. enumerable: true,
  35990. configurable: true
  35991. });
  35992. // Methods
  35993. ValueCondition.prototype.isValid = function () {
  35994. switch (this.operator) {
  35995. case ValueCondition.IsGreater:
  35996. return this._effectiveTarget[this._property] > this.value;
  35997. case ValueCondition.IsLesser:
  35998. return this._effectiveTarget[this._property] < this.value;
  35999. case ValueCondition.IsEqual:
  36000. case ValueCondition.IsDifferent:
  36001. var check;
  36002. if (this.value.equals) {
  36003. check = this.value.equals(this._effectiveTarget[this._property]);
  36004. }
  36005. else {
  36006. check = this.value === this._effectiveTarget[this._property];
  36007. }
  36008. return this.operator === ValueCondition.IsEqual ? check : !check;
  36009. }
  36010. return false;
  36011. };
  36012. ValueCondition.prototype.serialize = function () {
  36013. return this._serialize({
  36014. name: "ValueCondition",
  36015. properties: [
  36016. BABYLON.Action._GetTargetProperty(this._target),
  36017. { name: "propertyPath", value: this.propertyPath },
  36018. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36019. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36020. ]
  36021. });
  36022. };
  36023. ValueCondition.GetOperatorName = function (operator) {
  36024. switch (operator) {
  36025. case ValueCondition._IsEqual: return "IsEqual";
  36026. case ValueCondition._IsDifferent: return "IsDifferent";
  36027. case ValueCondition._IsGreater: return "IsGreater";
  36028. case ValueCondition._IsLesser: return "IsLesser";
  36029. default: return "";
  36030. }
  36031. };
  36032. return ValueCondition;
  36033. }(Condition));
  36034. // Statics
  36035. ValueCondition._IsEqual = 0;
  36036. ValueCondition._IsDifferent = 1;
  36037. ValueCondition._IsGreater = 2;
  36038. ValueCondition._IsLesser = 3;
  36039. BABYLON.ValueCondition = ValueCondition;
  36040. var PredicateCondition = (function (_super) {
  36041. __extends(PredicateCondition, _super);
  36042. function PredicateCondition(actionManager, predicate) {
  36043. var _this = _super.call(this, actionManager) || this;
  36044. _this.predicate = predicate;
  36045. return _this;
  36046. }
  36047. PredicateCondition.prototype.isValid = function () {
  36048. return this.predicate();
  36049. };
  36050. return PredicateCondition;
  36051. }(Condition));
  36052. BABYLON.PredicateCondition = PredicateCondition;
  36053. var StateCondition = (function (_super) {
  36054. __extends(StateCondition, _super);
  36055. function StateCondition(actionManager, target, value) {
  36056. var _this = _super.call(this, actionManager) || this;
  36057. _this.value = value;
  36058. _this._target = target;
  36059. return _this;
  36060. }
  36061. // Methods
  36062. StateCondition.prototype.isValid = function () {
  36063. return this._target.state === this.value;
  36064. };
  36065. StateCondition.prototype.serialize = function () {
  36066. return this._serialize({
  36067. name: "StateCondition",
  36068. properties: [
  36069. BABYLON.Action._GetTargetProperty(this._target),
  36070. { name: "value", value: this.value }
  36071. ]
  36072. });
  36073. };
  36074. return StateCondition;
  36075. }(Condition));
  36076. BABYLON.StateCondition = StateCondition;
  36077. })(BABYLON || (BABYLON = {}));
  36078. //# sourceMappingURL=babylon.condition.js.map
  36079. var BABYLON;
  36080. (function (BABYLON) {
  36081. var Action = (function () {
  36082. function Action(triggerOptions, condition) {
  36083. this.triggerOptions = triggerOptions;
  36084. if (triggerOptions.parameter) {
  36085. this.trigger = triggerOptions.trigger;
  36086. this._triggerParameter = triggerOptions.parameter;
  36087. }
  36088. else {
  36089. this.trigger = triggerOptions;
  36090. }
  36091. this._nextActiveAction = this;
  36092. this._condition = condition;
  36093. }
  36094. // Methods
  36095. Action.prototype._prepare = function () {
  36096. };
  36097. Action.prototype.getTriggerParameter = function () {
  36098. return this._triggerParameter;
  36099. };
  36100. Action.prototype._executeCurrent = function (evt) {
  36101. if (this._nextActiveAction._condition) {
  36102. var condition = this._nextActiveAction._condition;
  36103. var currentRenderId = this._actionManager.getScene().getRenderId();
  36104. // We cache the current evaluation for the current frame
  36105. if (condition._evaluationId === currentRenderId) {
  36106. if (!condition._currentResult) {
  36107. return;
  36108. }
  36109. }
  36110. else {
  36111. condition._evaluationId = currentRenderId;
  36112. if (!condition.isValid()) {
  36113. condition._currentResult = false;
  36114. return;
  36115. }
  36116. condition._currentResult = true;
  36117. }
  36118. }
  36119. this._nextActiveAction.execute(evt);
  36120. this.skipToNextActiveAction();
  36121. };
  36122. Action.prototype.execute = function (evt) {
  36123. };
  36124. Action.prototype.skipToNextActiveAction = function () {
  36125. if (this._nextActiveAction._child) {
  36126. if (!this._nextActiveAction._child._actionManager) {
  36127. this._nextActiveAction._child._actionManager = this._actionManager;
  36128. }
  36129. this._nextActiveAction = this._nextActiveAction._child;
  36130. }
  36131. else {
  36132. this._nextActiveAction = this;
  36133. }
  36134. };
  36135. Action.prototype.then = function (action) {
  36136. this._child = action;
  36137. action._actionManager = this._actionManager;
  36138. action._prepare();
  36139. return action;
  36140. };
  36141. Action.prototype._getProperty = function (propertyPath) {
  36142. return this._actionManager._getProperty(propertyPath);
  36143. };
  36144. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36145. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36146. };
  36147. Action.prototype.serialize = function (parent) {
  36148. };
  36149. // Called by BABYLON.Action objects in serialize(...). Internal use
  36150. Action.prototype._serialize = function (serializedAction, parent) {
  36151. var serializationObject = {
  36152. type: 1,
  36153. children: [],
  36154. name: serializedAction.name,
  36155. properties: serializedAction.properties || []
  36156. };
  36157. // Serialize child
  36158. if (this._child) {
  36159. this._child.serialize(serializationObject);
  36160. }
  36161. // Check if "this" has a condition
  36162. if (this._condition) {
  36163. var serializedCondition = this._condition.serialize();
  36164. serializedCondition.children.push(serializationObject);
  36165. if (parent) {
  36166. parent.children.push(serializedCondition);
  36167. }
  36168. return serializedCondition;
  36169. }
  36170. if (parent) {
  36171. parent.children.push(serializationObject);
  36172. }
  36173. return serializationObject;
  36174. };
  36175. return Action;
  36176. }());
  36177. Action._SerializeValueAsString = function (value) {
  36178. if (typeof value === "number") {
  36179. return value.toString();
  36180. }
  36181. if (typeof value === "boolean") {
  36182. return value ? "true" : "false";
  36183. }
  36184. if (value instanceof BABYLON.Vector2) {
  36185. return value.x + ", " + value.y;
  36186. }
  36187. if (value instanceof BABYLON.Vector3) {
  36188. return value.x + ", " + value.y + ", " + value.z;
  36189. }
  36190. if (value instanceof BABYLON.Color3) {
  36191. return value.r + ", " + value.g + ", " + value.b;
  36192. }
  36193. if (value instanceof BABYLON.Color4) {
  36194. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36195. }
  36196. return value; // string
  36197. };
  36198. Action._GetTargetProperty = function (target) {
  36199. return {
  36200. name: "target",
  36201. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36202. : target instanceof BABYLON.Light ? "LightProperties"
  36203. : target instanceof BABYLON.Camera ? "CameraProperties"
  36204. : "SceneProperties",
  36205. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36206. };
  36207. };
  36208. BABYLON.Action = Action;
  36209. })(BABYLON || (BABYLON = {}));
  36210. //# sourceMappingURL=babylon.action.js.map
  36211. var BABYLON;
  36212. (function (BABYLON) {
  36213. /**
  36214. * ActionEvent is the event beint sent when an action is triggered.
  36215. */
  36216. var ActionEvent = (function () {
  36217. /**
  36218. * @constructor
  36219. * @param source The mesh or sprite that triggered the action.
  36220. * @param pointerX The X mouse cursor position at the time of the event
  36221. * @param pointerY The Y mouse cursor position at the time of the event
  36222. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36223. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36224. */
  36225. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36226. this.source = source;
  36227. this.pointerX = pointerX;
  36228. this.pointerY = pointerY;
  36229. this.meshUnderPointer = meshUnderPointer;
  36230. this.sourceEvent = sourceEvent;
  36231. this.additionalData = additionalData;
  36232. }
  36233. /**
  36234. * Helper function to auto-create an ActionEvent from a source mesh.
  36235. * @param source The source mesh that triggered the event
  36236. * @param evt {Event} The original (browser) event
  36237. */
  36238. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36239. var scene = source.getScene();
  36240. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36241. };
  36242. /**
  36243. * Helper function to auto-create an ActionEvent from a source mesh.
  36244. * @param source The source sprite that triggered the event
  36245. * @param scene Scene associated with the sprite
  36246. * @param evt {Event} The original (browser) event
  36247. */
  36248. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36249. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36250. };
  36251. /**
  36252. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36253. * @param scene the scene where the event occurred
  36254. * @param evt {Event} The original (browser) event
  36255. */
  36256. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36257. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36258. };
  36259. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36260. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36261. };
  36262. return ActionEvent;
  36263. }());
  36264. BABYLON.ActionEvent = ActionEvent;
  36265. /**
  36266. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36267. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36268. */
  36269. var ActionManager = (function () {
  36270. function ActionManager(scene) {
  36271. // Members
  36272. this.actions = new Array();
  36273. this.hoverCursor = '';
  36274. this._scene = scene;
  36275. scene._actionManagers.push(this);
  36276. }
  36277. Object.defineProperty(ActionManager, "NothingTrigger", {
  36278. get: function () {
  36279. return ActionManager._NothingTrigger;
  36280. },
  36281. enumerable: true,
  36282. configurable: true
  36283. });
  36284. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36285. get: function () {
  36286. return ActionManager._OnPickTrigger;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36292. get: function () {
  36293. return ActionManager._OnLeftPickTrigger;
  36294. },
  36295. enumerable: true,
  36296. configurable: true
  36297. });
  36298. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36299. get: function () {
  36300. return ActionManager._OnRightPickTrigger;
  36301. },
  36302. enumerable: true,
  36303. configurable: true
  36304. });
  36305. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36306. get: function () {
  36307. return ActionManager._OnCenterPickTrigger;
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36313. get: function () {
  36314. return ActionManager._OnPickDownTrigger;
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36320. get: function () {
  36321. return ActionManager._OnPickUpTrigger;
  36322. },
  36323. enumerable: true,
  36324. configurable: true
  36325. });
  36326. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36327. /// This trigger will only be raised if you also declared a OnPickDown
  36328. get: function () {
  36329. return ActionManager._OnPickOutTrigger;
  36330. },
  36331. enumerable: true,
  36332. configurable: true
  36333. });
  36334. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36335. get: function () {
  36336. return ActionManager._OnLongPressTrigger;
  36337. },
  36338. enumerable: true,
  36339. configurable: true
  36340. });
  36341. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36342. get: function () {
  36343. return ActionManager._OnPointerOverTrigger;
  36344. },
  36345. enumerable: true,
  36346. configurable: true
  36347. });
  36348. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36349. get: function () {
  36350. return ActionManager._OnPointerOutTrigger;
  36351. },
  36352. enumerable: true,
  36353. configurable: true
  36354. });
  36355. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36356. get: function () {
  36357. return ActionManager._OnEveryFrameTrigger;
  36358. },
  36359. enumerable: true,
  36360. configurable: true
  36361. });
  36362. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36363. get: function () {
  36364. return ActionManager._OnIntersectionEnterTrigger;
  36365. },
  36366. enumerable: true,
  36367. configurable: true
  36368. });
  36369. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36370. get: function () {
  36371. return ActionManager._OnIntersectionExitTrigger;
  36372. },
  36373. enumerable: true,
  36374. configurable: true
  36375. });
  36376. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36377. get: function () {
  36378. return ActionManager._OnKeyDownTrigger;
  36379. },
  36380. enumerable: true,
  36381. configurable: true
  36382. });
  36383. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36384. get: function () {
  36385. return ActionManager._OnKeyUpTrigger;
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. // Methods
  36391. ActionManager.prototype.dispose = function () {
  36392. var index = this._scene._actionManagers.indexOf(this);
  36393. if (index > -1) {
  36394. this._scene._actionManagers.splice(index, 1);
  36395. }
  36396. };
  36397. ActionManager.prototype.getScene = function () {
  36398. return this._scene;
  36399. };
  36400. /**
  36401. * Does this action manager handles actions of any of the given triggers
  36402. * @param {number[]} triggers - the triggers to be tested
  36403. * @return {boolean} whether one (or more) of the triggers is handeled
  36404. */
  36405. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36406. for (var index = 0; index < this.actions.length; index++) {
  36407. var action = this.actions[index];
  36408. if (triggers.indexOf(action.trigger) > -1) {
  36409. return true;
  36410. }
  36411. }
  36412. return false;
  36413. };
  36414. /**
  36415. * Does this action manager handles actions of a given trigger
  36416. * @param {number} trigger - the trigger to be tested
  36417. * @return {boolean} whether the trigger is handeled
  36418. */
  36419. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36420. for (var index = 0; index < this.actions.length; index++) {
  36421. var action = this.actions[index];
  36422. if (action.trigger === trigger) {
  36423. return true;
  36424. }
  36425. }
  36426. return false;
  36427. };
  36428. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36429. /**
  36430. * Does this action manager has pointer triggers
  36431. * @return {boolean} whether or not it has pointer triggers
  36432. */
  36433. get: function () {
  36434. for (var index = 0; index < this.actions.length; index++) {
  36435. var action = this.actions[index];
  36436. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36437. return true;
  36438. }
  36439. }
  36440. return false;
  36441. },
  36442. enumerable: true,
  36443. configurable: true
  36444. });
  36445. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36446. /**
  36447. * Does this action manager has pick triggers
  36448. * @return {boolean} whether or not it has pick triggers
  36449. */
  36450. get: function () {
  36451. for (var index = 0; index < this.actions.length; index++) {
  36452. var action = this.actions[index];
  36453. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36454. return true;
  36455. }
  36456. }
  36457. return false;
  36458. },
  36459. enumerable: true,
  36460. configurable: true
  36461. });
  36462. /**
  36463. * Registers an action to this action manager
  36464. * @param {BABYLON.Action} action - the action to be registered
  36465. * @return {BABYLON.Action} the action amended (prepared) after registration
  36466. */
  36467. ActionManager.prototype.registerAction = function (action) {
  36468. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36469. if (this.getScene().actionManager !== this) {
  36470. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36471. return null;
  36472. }
  36473. }
  36474. this.actions.push(action);
  36475. action._actionManager = this;
  36476. action._prepare();
  36477. return action;
  36478. };
  36479. /**
  36480. * Process a specific trigger
  36481. * @param {number} trigger - the trigger to process
  36482. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36483. */
  36484. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36485. for (var index = 0; index < this.actions.length; index++) {
  36486. var action = this.actions[index];
  36487. if (action.trigger === trigger) {
  36488. if (trigger === ActionManager.OnKeyUpTrigger
  36489. || trigger === ActionManager.OnKeyDownTrigger) {
  36490. var parameter = action.getTriggerParameter();
  36491. if (parameter) {
  36492. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36493. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36494. if (actualkey !== parameter.toLowerCase()) {
  36495. continue;
  36496. }
  36497. }
  36498. }
  36499. action._executeCurrent(evt);
  36500. }
  36501. }
  36502. };
  36503. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36504. var properties = propertyPath.split(".");
  36505. for (var index = 0; index < properties.length - 1; index++) {
  36506. target = target[properties[index]];
  36507. }
  36508. return target;
  36509. };
  36510. ActionManager.prototype._getProperty = function (propertyPath) {
  36511. var properties = propertyPath.split(".");
  36512. return properties[properties.length - 1];
  36513. };
  36514. ActionManager.prototype.serialize = function (name) {
  36515. var root = {
  36516. children: [],
  36517. name: name,
  36518. type: 3,
  36519. properties: [] // Empty for root but required
  36520. };
  36521. for (var i = 0; i < this.actions.length; i++) {
  36522. var triggerObject = {
  36523. type: 0,
  36524. children: [],
  36525. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36526. properties: []
  36527. };
  36528. var triggerOptions = this.actions[i].triggerOptions;
  36529. if (triggerOptions && typeof triggerOptions !== "number") {
  36530. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36531. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36532. }
  36533. else {
  36534. var parameter = {};
  36535. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36536. if (triggerOptions.parameter.mesh) {
  36537. parameter._meshId = triggerOptions.parameter.mesh.id;
  36538. }
  36539. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36540. }
  36541. }
  36542. // Serialize child action, recursively
  36543. this.actions[i].serialize(triggerObject);
  36544. // Add serialized trigger
  36545. root.children.push(triggerObject);
  36546. }
  36547. return root;
  36548. };
  36549. ActionManager.Parse = function (parsedActions, object, scene) {
  36550. var actionManager = new BABYLON.ActionManager(scene);
  36551. if (object === null)
  36552. scene.actionManager = actionManager;
  36553. else
  36554. object.actionManager = actionManager;
  36555. // instanciate a new object
  36556. var instanciate = function (name, params) {
  36557. var newInstance = Object.create(BABYLON[name].prototype);
  36558. newInstance.constructor.apply(newInstance, params);
  36559. return newInstance;
  36560. };
  36561. var parseParameter = function (name, value, target, propertyPath) {
  36562. if (propertyPath === null) {
  36563. // String, boolean or float
  36564. var floatValue = parseFloat(value);
  36565. if (value === "true" || value === "false")
  36566. return value === "true";
  36567. else
  36568. return isNaN(floatValue) ? value : floatValue;
  36569. }
  36570. var effectiveTarget = propertyPath.split(".");
  36571. var values = value.split(",");
  36572. // Get effective Target
  36573. for (var i = 0; i < effectiveTarget.length; i++) {
  36574. target = target[effectiveTarget[i]];
  36575. }
  36576. // Return appropriate value with its type
  36577. if (typeof (target) === "boolean")
  36578. return values[0] === "true";
  36579. if (typeof (target) === "string")
  36580. return values[0];
  36581. // Parameters with multiple values such as Vector3 etc.
  36582. var split = new Array();
  36583. for (var i = 0; i < values.length; i++)
  36584. split.push(parseFloat(values[i]));
  36585. if (target instanceof BABYLON.Vector3)
  36586. return BABYLON.Vector3.FromArray(split);
  36587. if (target instanceof BABYLON.Vector4)
  36588. return BABYLON.Vector4.FromArray(split);
  36589. if (target instanceof BABYLON.Color3)
  36590. return BABYLON.Color3.FromArray(split);
  36591. if (target instanceof BABYLON.Color4)
  36592. return BABYLON.Color4.FromArray(split);
  36593. return parseFloat(values[0]);
  36594. };
  36595. // traverse graph per trigger
  36596. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36597. if (combineArray === void 0) { combineArray = null; }
  36598. if (parsedAction.detached)
  36599. return;
  36600. var parameters = new Array();
  36601. var target = null;
  36602. var propertyPath = null;
  36603. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36604. // Parameters
  36605. if (parsedAction.type === 2)
  36606. parameters.push(actionManager);
  36607. else
  36608. parameters.push(trigger);
  36609. if (combine) {
  36610. var actions = new Array();
  36611. for (var j = 0; j < parsedAction.combine.length; j++) {
  36612. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36613. }
  36614. parameters.push(actions);
  36615. }
  36616. else {
  36617. for (var i = 0; i < parsedAction.properties.length; i++) {
  36618. var value = parsedAction.properties[i].value;
  36619. var name = parsedAction.properties[i].name;
  36620. var targetType = parsedAction.properties[i].targetType;
  36621. if (name === "target")
  36622. if (targetType !== null && targetType === "SceneProperties")
  36623. value = target = scene;
  36624. else
  36625. value = target = scene.getNodeByName(value);
  36626. else if (name === "parent")
  36627. value = scene.getNodeByName(value);
  36628. else if (name === "sound")
  36629. value = scene.getSoundByName(value);
  36630. else if (name !== "propertyPath") {
  36631. if (parsedAction.type === 2 && name === "operator")
  36632. value = BABYLON.ValueCondition[value];
  36633. else
  36634. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36635. }
  36636. else {
  36637. propertyPath = value;
  36638. }
  36639. parameters.push(value);
  36640. }
  36641. }
  36642. if (combineArray === null) {
  36643. parameters.push(condition);
  36644. }
  36645. else {
  36646. parameters.push(null);
  36647. }
  36648. // If interpolate value action
  36649. if (parsedAction.name === "InterpolateValueAction") {
  36650. var param = parameters[parameters.length - 2];
  36651. parameters[parameters.length - 1] = param;
  36652. parameters[parameters.length - 2] = condition;
  36653. }
  36654. // Action or condition(s) and not CombineAction
  36655. var newAction = instanciate(parsedAction.name, parameters);
  36656. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36657. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36658. if (action)
  36659. action.then(nothing);
  36660. else
  36661. actionManager.registerAction(nothing);
  36662. action = nothing;
  36663. }
  36664. if (combineArray === null) {
  36665. if (newAction instanceof BABYLON.Condition) {
  36666. condition = newAction;
  36667. newAction = action;
  36668. }
  36669. else {
  36670. condition = null;
  36671. if (action)
  36672. action.then(newAction);
  36673. else
  36674. actionManager.registerAction(newAction);
  36675. }
  36676. }
  36677. else {
  36678. combineArray.push(newAction);
  36679. }
  36680. for (var i = 0; i < parsedAction.children.length; i++)
  36681. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36682. };
  36683. // triggers
  36684. for (var i = 0; i < parsedActions.children.length; i++) {
  36685. var triggerParams;
  36686. var trigger = parsedActions.children[i];
  36687. if (trigger.properties.length > 0) {
  36688. var param = trigger.properties[0].value;
  36689. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36690. if (value._meshId) {
  36691. value.mesh = scene.getMeshByID(value._meshId);
  36692. }
  36693. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36694. }
  36695. else
  36696. triggerParams = BABYLON.ActionManager[trigger.name];
  36697. for (var j = 0; j < trigger.children.length; j++) {
  36698. if (!trigger.detached)
  36699. traverse(trigger.children[j], triggerParams, null, null);
  36700. }
  36701. }
  36702. };
  36703. ActionManager.GetTriggerName = function (trigger) {
  36704. switch (trigger) {
  36705. case 0: return "NothingTrigger";
  36706. case 1: return "OnPickTrigger";
  36707. case 2: return "OnLeftPickTrigger";
  36708. case 3: return "OnRightPickTrigger";
  36709. case 4: return "OnCenterPickTrigger";
  36710. case 5: return "OnPickDownTrigger";
  36711. case 6: return "OnPickUpTrigger";
  36712. case 7: return "OnLongPressTrigger";
  36713. case 8: return "OnPointerOverTrigger";
  36714. case 9: return "OnPointerOutTrigger";
  36715. case 10: return "OnEveryFrameTrigger";
  36716. case 11: return "OnIntersectionEnterTrigger";
  36717. case 12: return "OnIntersectionExitTrigger";
  36718. case 13: return "OnKeyDownTrigger";
  36719. case 14: return "OnKeyUpTrigger";
  36720. case 15: return "OnPickOutTrigger";
  36721. default: return "";
  36722. }
  36723. };
  36724. return ActionManager;
  36725. }());
  36726. // Statics
  36727. ActionManager._NothingTrigger = 0;
  36728. ActionManager._OnPickTrigger = 1;
  36729. ActionManager._OnLeftPickTrigger = 2;
  36730. ActionManager._OnRightPickTrigger = 3;
  36731. ActionManager._OnCenterPickTrigger = 4;
  36732. ActionManager._OnPickDownTrigger = 5;
  36733. ActionManager._OnPickUpTrigger = 6;
  36734. ActionManager._OnLongPressTrigger = 7;
  36735. ActionManager._OnPointerOverTrigger = 8;
  36736. ActionManager._OnPointerOutTrigger = 9;
  36737. ActionManager._OnEveryFrameTrigger = 10;
  36738. ActionManager._OnIntersectionEnterTrigger = 11;
  36739. ActionManager._OnIntersectionExitTrigger = 12;
  36740. ActionManager._OnKeyDownTrigger = 13;
  36741. ActionManager._OnKeyUpTrigger = 14;
  36742. ActionManager._OnPickOutTrigger = 15;
  36743. ActionManager.DragMovementThreshold = 10; // in pixels
  36744. ActionManager.LongPressDelay = 500; // in milliseconds
  36745. BABYLON.ActionManager = ActionManager;
  36746. })(BABYLON || (BABYLON = {}));
  36747. //# sourceMappingURL=babylon.actionManager.js.map
  36748. var BABYLON;
  36749. (function (BABYLON) {
  36750. var InterpolateValueAction = (function (_super) {
  36751. __extends(InterpolateValueAction, _super);
  36752. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36753. if (duration === void 0) { duration = 1000; }
  36754. var _this = _super.call(this, triggerOptions, condition) || this;
  36755. _this.propertyPath = propertyPath;
  36756. _this.value = value;
  36757. _this.duration = duration;
  36758. _this.stopOtherAnimations = stopOtherAnimations;
  36759. _this.onInterpolationDone = onInterpolationDone;
  36760. _this._target = _this._effectiveTarget = target;
  36761. return _this;
  36762. }
  36763. InterpolateValueAction.prototype._prepare = function () {
  36764. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36765. this._property = this._getProperty(this.propertyPath);
  36766. };
  36767. InterpolateValueAction.prototype.execute = function () {
  36768. var scene = this._actionManager.getScene();
  36769. var keys = [
  36770. {
  36771. frame: 0,
  36772. value: this._effectiveTarget[this._property]
  36773. }, {
  36774. frame: 100,
  36775. value: this.value
  36776. }
  36777. ];
  36778. var dataType;
  36779. if (typeof this.value === "number") {
  36780. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36781. }
  36782. else if (this.value instanceof BABYLON.Color3) {
  36783. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36784. }
  36785. else if (this.value instanceof BABYLON.Vector3) {
  36786. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36787. }
  36788. else if (this.value instanceof BABYLON.Matrix) {
  36789. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36790. }
  36791. else if (this.value instanceof BABYLON.Quaternion) {
  36792. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36793. }
  36794. else {
  36795. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36796. return;
  36797. }
  36798. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36799. animation.setKeys(keys);
  36800. if (this.stopOtherAnimations) {
  36801. scene.stopAnimation(this._effectiveTarget);
  36802. }
  36803. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36804. };
  36805. InterpolateValueAction.prototype.serialize = function (parent) {
  36806. return _super.prototype._serialize.call(this, {
  36807. name: "InterpolateValueAction",
  36808. properties: [
  36809. BABYLON.Action._GetTargetProperty(this._target),
  36810. { name: "propertyPath", value: this.propertyPath },
  36811. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36812. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36813. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36814. ]
  36815. }, parent);
  36816. };
  36817. return InterpolateValueAction;
  36818. }(BABYLON.Action));
  36819. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36820. })(BABYLON || (BABYLON = {}));
  36821. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36822. var BABYLON;
  36823. (function (BABYLON) {
  36824. var SwitchBooleanAction = (function (_super) {
  36825. __extends(SwitchBooleanAction, _super);
  36826. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36827. var _this = _super.call(this, triggerOptions, condition) || this;
  36828. _this.propertyPath = propertyPath;
  36829. _this._target = _this._effectiveTarget = target;
  36830. return _this;
  36831. }
  36832. SwitchBooleanAction.prototype._prepare = function () {
  36833. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36834. this._property = this._getProperty(this.propertyPath);
  36835. };
  36836. SwitchBooleanAction.prototype.execute = function () {
  36837. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36838. };
  36839. SwitchBooleanAction.prototype.serialize = function (parent) {
  36840. return _super.prototype._serialize.call(this, {
  36841. name: "SwitchBooleanAction",
  36842. properties: [
  36843. BABYLON.Action._GetTargetProperty(this._target),
  36844. { name: "propertyPath", value: this.propertyPath }
  36845. ]
  36846. }, parent);
  36847. };
  36848. return SwitchBooleanAction;
  36849. }(BABYLON.Action));
  36850. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36851. var SetStateAction = (function (_super) {
  36852. __extends(SetStateAction, _super);
  36853. function SetStateAction(triggerOptions, target, value, condition) {
  36854. var _this = _super.call(this, triggerOptions, condition) || this;
  36855. _this.value = value;
  36856. _this._target = target;
  36857. return _this;
  36858. }
  36859. SetStateAction.prototype.execute = function () {
  36860. this._target.state = this.value;
  36861. };
  36862. SetStateAction.prototype.serialize = function (parent) {
  36863. return _super.prototype._serialize.call(this, {
  36864. name: "SetStateAction",
  36865. properties: [
  36866. BABYLON.Action._GetTargetProperty(this._target),
  36867. { name: "value", value: this.value }
  36868. ]
  36869. }, parent);
  36870. };
  36871. return SetStateAction;
  36872. }(BABYLON.Action));
  36873. BABYLON.SetStateAction = SetStateAction;
  36874. var SetValueAction = (function (_super) {
  36875. __extends(SetValueAction, _super);
  36876. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36877. var _this = _super.call(this, triggerOptions, condition) || this;
  36878. _this.propertyPath = propertyPath;
  36879. _this.value = value;
  36880. _this._target = _this._effectiveTarget = target;
  36881. return _this;
  36882. }
  36883. SetValueAction.prototype._prepare = function () {
  36884. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36885. this._property = this._getProperty(this.propertyPath);
  36886. };
  36887. SetValueAction.prototype.execute = function () {
  36888. this._effectiveTarget[this._property] = this.value;
  36889. if (this._target.markAsDirty) {
  36890. this._target.markAsDirty(this._property);
  36891. }
  36892. };
  36893. SetValueAction.prototype.serialize = function (parent) {
  36894. return _super.prototype._serialize.call(this, {
  36895. name: "SetValueAction",
  36896. properties: [
  36897. BABYLON.Action._GetTargetProperty(this._target),
  36898. { name: "propertyPath", value: this.propertyPath },
  36899. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36900. ]
  36901. }, parent);
  36902. };
  36903. return SetValueAction;
  36904. }(BABYLON.Action));
  36905. BABYLON.SetValueAction = SetValueAction;
  36906. var IncrementValueAction = (function (_super) {
  36907. __extends(IncrementValueAction, _super);
  36908. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36909. var _this = _super.call(this, triggerOptions, condition) || this;
  36910. _this.propertyPath = propertyPath;
  36911. _this.value = value;
  36912. _this._target = _this._effectiveTarget = target;
  36913. return _this;
  36914. }
  36915. IncrementValueAction.prototype._prepare = function () {
  36916. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36917. this._property = this._getProperty(this.propertyPath);
  36918. if (typeof this._effectiveTarget[this._property] !== "number") {
  36919. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36920. }
  36921. };
  36922. IncrementValueAction.prototype.execute = function () {
  36923. this._effectiveTarget[this._property] += this.value;
  36924. if (this._target.markAsDirty) {
  36925. this._target.markAsDirty(this._property);
  36926. }
  36927. };
  36928. IncrementValueAction.prototype.serialize = function (parent) {
  36929. return _super.prototype._serialize.call(this, {
  36930. name: "IncrementValueAction",
  36931. properties: [
  36932. BABYLON.Action._GetTargetProperty(this._target),
  36933. { name: "propertyPath", value: this.propertyPath },
  36934. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36935. ]
  36936. }, parent);
  36937. };
  36938. return IncrementValueAction;
  36939. }(BABYLON.Action));
  36940. BABYLON.IncrementValueAction = IncrementValueAction;
  36941. var PlayAnimationAction = (function (_super) {
  36942. __extends(PlayAnimationAction, _super);
  36943. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36944. var _this = _super.call(this, triggerOptions, condition) || this;
  36945. _this.from = from;
  36946. _this.to = to;
  36947. _this.loop = loop;
  36948. _this._target = target;
  36949. return _this;
  36950. }
  36951. PlayAnimationAction.prototype._prepare = function () {
  36952. };
  36953. PlayAnimationAction.prototype.execute = function () {
  36954. var scene = this._actionManager.getScene();
  36955. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36956. };
  36957. PlayAnimationAction.prototype.serialize = function (parent) {
  36958. return _super.prototype._serialize.call(this, {
  36959. name: "PlayAnimationAction",
  36960. properties: [
  36961. BABYLON.Action._GetTargetProperty(this._target),
  36962. { name: "from", value: String(this.from) },
  36963. { name: "to", value: String(this.to) },
  36964. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36965. ]
  36966. }, parent);
  36967. };
  36968. return PlayAnimationAction;
  36969. }(BABYLON.Action));
  36970. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36971. var StopAnimationAction = (function (_super) {
  36972. __extends(StopAnimationAction, _super);
  36973. function StopAnimationAction(triggerOptions, target, condition) {
  36974. var _this = _super.call(this, triggerOptions, condition) || this;
  36975. _this._target = target;
  36976. return _this;
  36977. }
  36978. StopAnimationAction.prototype._prepare = function () {
  36979. };
  36980. StopAnimationAction.prototype.execute = function () {
  36981. var scene = this._actionManager.getScene();
  36982. scene.stopAnimation(this._target);
  36983. };
  36984. StopAnimationAction.prototype.serialize = function (parent) {
  36985. return _super.prototype._serialize.call(this, {
  36986. name: "StopAnimationAction",
  36987. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36988. }, parent);
  36989. };
  36990. return StopAnimationAction;
  36991. }(BABYLON.Action));
  36992. BABYLON.StopAnimationAction = StopAnimationAction;
  36993. var DoNothingAction = (function (_super) {
  36994. __extends(DoNothingAction, _super);
  36995. function DoNothingAction(triggerOptions, condition) {
  36996. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36997. return _super.call(this, triggerOptions, condition) || this;
  36998. }
  36999. DoNothingAction.prototype.execute = function () {
  37000. };
  37001. DoNothingAction.prototype.serialize = function (parent) {
  37002. return _super.prototype._serialize.call(this, {
  37003. name: "DoNothingAction",
  37004. properties: []
  37005. }, parent);
  37006. };
  37007. return DoNothingAction;
  37008. }(BABYLON.Action));
  37009. BABYLON.DoNothingAction = DoNothingAction;
  37010. var CombineAction = (function (_super) {
  37011. __extends(CombineAction, _super);
  37012. function CombineAction(triggerOptions, children, condition) {
  37013. var _this = _super.call(this, triggerOptions, condition) || this;
  37014. _this.children = children;
  37015. return _this;
  37016. }
  37017. CombineAction.prototype._prepare = function () {
  37018. for (var index = 0; index < this.children.length; index++) {
  37019. this.children[index]._actionManager = this._actionManager;
  37020. this.children[index]._prepare();
  37021. }
  37022. };
  37023. CombineAction.prototype.execute = function (evt) {
  37024. for (var index = 0; index < this.children.length; index++) {
  37025. this.children[index].execute(evt);
  37026. }
  37027. };
  37028. CombineAction.prototype.serialize = function (parent) {
  37029. var serializationObject = _super.prototype._serialize.call(this, {
  37030. name: "CombineAction",
  37031. properties: [],
  37032. combine: []
  37033. }, parent);
  37034. for (var i = 0; i < this.children.length; i++) {
  37035. serializationObject.combine.push(this.children[i].serialize(null));
  37036. }
  37037. return serializationObject;
  37038. };
  37039. return CombineAction;
  37040. }(BABYLON.Action));
  37041. BABYLON.CombineAction = CombineAction;
  37042. var ExecuteCodeAction = (function (_super) {
  37043. __extends(ExecuteCodeAction, _super);
  37044. function ExecuteCodeAction(triggerOptions, func, condition) {
  37045. var _this = _super.call(this, triggerOptions, condition) || this;
  37046. _this.func = func;
  37047. return _this;
  37048. }
  37049. ExecuteCodeAction.prototype.execute = function (evt) {
  37050. this.func(evt);
  37051. };
  37052. return ExecuteCodeAction;
  37053. }(BABYLON.Action));
  37054. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37055. var SetParentAction = (function (_super) {
  37056. __extends(SetParentAction, _super);
  37057. function SetParentAction(triggerOptions, target, parent, condition) {
  37058. var _this = _super.call(this, triggerOptions, condition) || this;
  37059. _this._target = target;
  37060. _this._parent = parent;
  37061. return _this;
  37062. }
  37063. SetParentAction.prototype._prepare = function () {
  37064. };
  37065. SetParentAction.prototype.execute = function () {
  37066. if (this._target.parent === this._parent) {
  37067. return;
  37068. }
  37069. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37070. invertParentWorldMatrix.invert();
  37071. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37072. this._target.parent = this._parent;
  37073. };
  37074. SetParentAction.prototype.serialize = function (parent) {
  37075. return _super.prototype._serialize.call(this, {
  37076. name: "SetParentAction",
  37077. properties: [
  37078. BABYLON.Action._GetTargetProperty(this._target),
  37079. BABYLON.Action._GetTargetProperty(this._parent),
  37080. ]
  37081. }, parent);
  37082. };
  37083. return SetParentAction;
  37084. }(BABYLON.Action));
  37085. BABYLON.SetParentAction = SetParentAction;
  37086. var PlaySoundAction = (function (_super) {
  37087. __extends(PlaySoundAction, _super);
  37088. function PlaySoundAction(triggerOptions, sound, condition) {
  37089. var _this = _super.call(this, triggerOptions, condition) || this;
  37090. _this._sound = sound;
  37091. return _this;
  37092. }
  37093. PlaySoundAction.prototype._prepare = function () {
  37094. };
  37095. PlaySoundAction.prototype.execute = function () {
  37096. if (this._sound !== undefined)
  37097. this._sound.play();
  37098. };
  37099. PlaySoundAction.prototype.serialize = function (parent) {
  37100. return _super.prototype._serialize.call(this, {
  37101. name: "PlaySoundAction",
  37102. properties: [{ name: "sound", value: this._sound.name }]
  37103. }, parent);
  37104. };
  37105. return PlaySoundAction;
  37106. }(BABYLON.Action));
  37107. BABYLON.PlaySoundAction = PlaySoundAction;
  37108. var StopSoundAction = (function (_super) {
  37109. __extends(StopSoundAction, _super);
  37110. function StopSoundAction(triggerOptions, sound, condition) {
  37111. var _this = _super.call(this, triggerOptions, condition) || this;
  37112. _this._sound = sound;
  37113. return _this;
  37114. }
  37115. StopSoundAction.prototype._prepare = function () {
  37116. };
  37117. StopSoundAction.prototype.execute = function () {
  37118. if (this._sound !== undefined)
  37119. this._sound.stop();
  37120. };
  37121. StopSoundAction.prototype.serialize = function (parent) {
  37122. return _super.prototype._serialize.call(this, {
  37123. name: "StopSoundAction",
  37124. properties: [{ name: "sound", value: this._sound.name }]
  37125. }, parent);
  37126. };
  37127. return StopSoundAction;
  37128. }(BABYLON.Action));
  37129. BABYLON.StopSoundAction = StopSoundAction;
  37130. })(BABYLON || (BABYLON = {}));
  37131. //# sourceMappingURL=babylon.directActions.js.map
  37132. var BABYLON;
  37133. (function (BABYLON) {
  37134. var Geometry = (function () {
  37135. function Geometry(id, scene, vertexData, updatable, mesh) {
  37136. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37137. this._totalVertices = 0;
  37138. this._isDisposed = false;
  37139. this.id = id;
  37140. this._engine = scene.getEngine();
  37141. this._meshes = [];
  37142. this._scene = scene;
  37143. //Init vertex buffer cache
  37144. this._vertexBuffers = {};
  37145. this._indices = [];
  37146. // vertexData
  37147. if (vertexData) {
  37148. this.setAllVerticesData(vertexData, updatable);
  37149. }
  37150. else {
  37151. this._totalVertices = 0;
  37152. this._indices = [];
  37153. }
  37154. if (this._engine.getCaps().vertexArrayObject) {
  37155. this._vertexArrayObjects = {};
  37156. }
  37157. // applyToMesh
  37158. if (mesh) {
  37159. if (mesh instanceof BABYLON.LinesMesh) {
  37160. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37161. this.updateExtend();
  37162. }
  37163. this.applyToMesh(mesh);
  37164. mesh.computeWorldMatrix(true);
  37165. }
  37166. }
  37167. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37168. /**
  37169. * 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
  37170. * @returns The Bias Vector
  37171. */
  37172. get: function () {
  37173. return this._boundingBias;
  37174. },
  37175. set: function (value) {
  37176. if (this._boundingBias && this._boundingBias.equals(value)) {
  37177. return;
  37178. }
  37179. this._boundingBias = value.clone();
  37180. this.updateBoundingInfo(true, null);
  37181. },
  37182. enumerable: true,
  37183. configurable: true
  37184. });
  37185. Object.defineProperty(Geometry.prototype, "extend", {
  37186. get: function () {
  37187. return this._extend;
  37188. },
  37189. enumerable: true,
  37190. configurable: true
  37191. });
  37192. Geometry.prototype.getScene = function () {
  37193. return this._scene;
  37194. };
  37195. Geometry.prototype.getEngine = function () {
  37196. return this._engine;
  37197. };
  37198. Geometry.prototype.isReady = function () {
  37199. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37200. };
  37201. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37202. get: function () {
  37203. for (var index = 0; index < this._meshes.length; index++) {
  37204. if (!this._meshes[index].doNotSerialize) {
  37205. return false;
  37206. }
  37207. }
  37208. return true;
  37209. },
  37210. enumerable: true,
  37211. configurable: true
  37212. });
  37213. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37214. vertexData.applyToGeometry(this, updatable);
  37215. this.notifyUpdate();
  37216. };
  37217. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37218. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37219. this.setVerticesBuffer(buffer);
  37220. };
  37221. Geometry.prototype.setVerticesBuffer = function (buffer) {
  37222. var kind = buffer.getKind();
  37223. if (this._vertexBuffers[kind]) {
  37224. this._vertexBuffers[kind].dispose();
  37225. }
  37226. this._vertexBuffers[kind] = buffer;
  37227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37228. var data = buffer.getData();
  37229. var stride = buffer.getStrideSize();
  37230. this._totalVertices = data.length / stride;
  37231. this.updateExtend(data, stride);
  37232. var meshes = this._meshes;
  37233. var numOfMeshes = meshes.length;
  37234. for (var index = 0; index < numOfMeshes; index++) {
  37235. var mesh = meshes[index];
  37236. mesh._resetPointsArrayCache();
  37237. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37238. mesh._createGlobalSubMesh();
  37239. mesh.computeWorldMatrix(true);
  37240. }
  37241. }
  37242. this.notifyUpdate(kind);
  37243. if (this._vertexArrayObjects) {
  37244. this._disposeVertexArrayObjects();
  37245. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37246. }
  37247. };
  37248. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37249. var vertexBuffer = this.getVertexBuffer(kind);
  37250. if (!vertexBuffer) {
  37251. return;
  37252. }
  37253. vertexBuffer.updateDirectly(data, offset);
  37254. this.notifyUpdate(kind);
  37255. };
  37256. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37257. var vertexBuffer = this.getVertexBuffer(kind);
  37258. if (!vertexBuffer) {
  37259. return;
  37260. }
  37261. vertexBuffer.update(data);
  37262. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37263. var stride = vertexBuffer.getStrideSize();
  37264. this._totalVertices = data.length / stride;
  37265. this.updateBoundingInfo(updateExtends, data);
  37266. }
  37267. this.notifyUpdate(kind);
  37268. };
  37269. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  37270. if (updateExtends) {
  37271. this.updateExtend(data);
  37272. }
  37273. var meshes = this._meshes;
  37274. var numOfMeshes = meshes.length;
  37275. for (var index = 0; index < numOfMeshes; index++) {
  37276. var mesh = meshes[index];
  37277. mesh._resetPointsArrayCache();
  37278. if (updateExtends) {
  37279. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37280. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37281. var subMesh = mesh.subMeshes[subIndex];
  37282. subMesh.refreshBoundingInfo();
  37283. }
  37284. }
  37285. }
  37286. };
  37287. Geometry.prototype._bind = function (effect, indexToBind) {
  37288. if (indexToBind === void 0) { indexToBind = undefined; }
  37289. if (indexToBind === undefined) {
  37290. indexToBind = this._indexBuffer;
  37291. }
  37292. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37293. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  37294. return;
  37295. }
  37296. // Using VAO
  37297. if (!this._vertexArrayObjects[effect.key]) {
  37298. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  37299. }
  37300. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37301. };
  37302. Geometry.prototype.getTotalVertices = function () {
  37303. if (!this.isReady()) {
  37304. return 0;
  37305. }
  37306. return this._totalVertices;
  37307. };
  37308. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  37309. var vertexBuffer = this.getVertexBuffer(kind);
  37310. if (!vertexBuffer) {
  37311. return null;
  37312. }
  37313. var orig = vertexBuffer.getData();
  37314. if (!copyWhenShared || this._meshes.length === 1) {
  37315. return orig;
  37316. }
  37317. else {
  37318. var len = orig.length;
  37319. var copy = [];
  37320. for (var i = 0; i < len; i++) {
  37321. copy.push(orig[i]);
  37322. }
  37323. return copy;
  37324. }
  37325. };
  37326. Geometry.prototype.getVertexBuffer = function (kind) {
  37327. if (!this.isReady()) {
  37328. return null;
  37329. }
  37330. return this._vertexBuffers[kind];
  37331. };
  37332. Geometry.prototype.getVertexBuffers = function () {
  37333. if (!this.isReady()) {
  37334. return null;
  37335. }
  37336. return this._vertexBuffers;
  37337. };
  37338. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37339. if (!this._vertexBuffers) {
  37340. if (this._delayInfo) {
  37341. return this._delayInfo.indexOf(kind) !== -1;
  37342. }
  37343. return false;
  37344. }
  37345. return this._vertexBuffers[kind] !== undefined;
  37346. };
  37347. Geometry.prototype.getVerticesDataKinds = function () {
  37348. var result = [];
  37349. var kind;
  37350. if (!this._vertexBuffers && this._delayInfo) {
  37351. for (kind in this._delayInfo) {
  37352. result.push(kind);
  37353. }
  37354. }
  37355. else {
  37356. for (kind in this._vertexBuffers) {
  37357. result.push(kind);
  37358. }
  37359. }
  37360. return result;
  37361. };
  37362. Geometry.prototype.setIndices = function (indices, totalVertices) {
  37363. if (this._indexBuffer) {
  37364. this._engine._releaseBuffer(this._indexBuffer);
  37365. }
  37366. this._disposeVertexArrayObjects();
  37367. this._indices = indices;
  37368. if (this._meshes.length !== 0 && this._indices) {
  37369. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37370. }
  37371. if (totalVertices !== undefined) {
  37372. this._totalVertices = totalVertices;
  37373. }
  37374. var meshes = this._meshes;
  37375. var numOfMeshes = meshes.length;
  37376. for (var index = 0; index < numOfMeshes; index++) {
  37377. meshes[index]._createGlobalSubMesh();
  37378. }
  37379. this.notifyUpdate();
  37380. };
  37381. Geometry.prototype.getTotalIndices = function () {
  37382. if (!this.isReady()) {
  37383. return 0;
  37384. }
  37385. return this._indices.length;
  37386. };
  37387. Geometry.prototype.getIndices = function (copyWhenShared) {
  37388. if (!this.isReady()) {
  37389. return null;
  37390. }
  37391. var orig = this._indices;
  37392. if (!copyWhenShared || this._meshes.length === 1) {
  37393. return orig;
  37394. }
  37395. else {
  37396. var len = orig.length;
  37397. var copy = [];
  37398. for (var i = 0; i < len; i++) {
  37399. copy.push(orig[i]);
  37400. }
  37401. return copy;
  37402. }
  37403. };
  37404. Geometry.prototype.getIndexBuffer = function () {
  37405. if (!this.isReady()) {
  37406. return null;
  37407. }
  37408. return this._indexBuffer;
  37409. };
  37410. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37411. var meshes = this._meshes;
  37412. var index = meshes.indexOf(mesh);
  37413. if (index === -1) {
  37414. return;
  37415. }
  37416. meshes.splice(index, 1);
  37417. mesh._geometry = null;
  37418. if (meshes.length === 0 && shouldDispose) {
  37419. this.dispose();
  37420. }
  37421. };
  37422. Geometry.prototype.applyToMesh = function (mesh) {
  37423. if (mesh._geometry === this) {
  37424. return;
  37425. }
  37426. var previousGeometry = mesh._geometry;
  37427. if (previousGeometry) {
  37428. previousGeometry.releaseForMesh(mesh);
  37429. }
  37430. var meshes = this._meshes;
  37431. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37432. mesh._geometry = this;
  37433. this._scene.pushGeometry(this);
  37434. meshes.push(mesh);
  37435. if (this.isReady()) {
  37436. this._applyToMesh(mesh);
  37437. }
  37438. else {
  37439. mesh._boundingInfo = this._boundingInfo;
  37440. }
  37441. };
  37442. Geometry.prototype.updateExtend = function (data, stride) {
  37443. if (data === void 0) { data = null; }
  37444. if (!data) {
  37445. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  37446. }
  37447. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  37448. };
  37449. Geometry.prototype._applyToMesh = function (mesh) {
  37450. var numOfMeshes = this._meshes.length;
  37451. // vertexBuffers
  37452. for (var kind in this._vertexBuffers) {
  37453. if (numOfMeshes === 1) {
  37454. this._vertexBuffers[kind].create();
  37455. }
  37456. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  37457. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37458. mesh._resetPointsArrayCache();
  37459. if (!this._extend) {
  37460. this.updateExtend(this._vertexBuffers[kind].getData());
  37461. }
  37462. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37463. mesh._createGlobalSubMesh();
  37464. //bounding info was just created again, world matrix should be applied again.
  37465. mesh._updateBoundingInfo();
  37466. }
  37467. }
  37468. // indexBuffer
  37469. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37470. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37471. }
  37472. if (this._indexBuffer) {
  37473. this._indexBuffer.references = numOfMeshes;
  37474. }
  37475. };
  37476. Geometry.prototype.notifyUpdate = function (kind) {
  37477. if (this.onGeometryUpdated) {
  37478. this.onGeometryUpdated(this, kind);
  37479. }
  37480. };
  37481. Geometry.prototype.load = function (scene, onLoaded) {
  37482. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37483. return;
  37484. }
  37485. if (this.isReady()) {
  37486. if (onLoaded) {
  37487. onLoaded();
  37488. }
  37489. return;
  37490. }
  37491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37492. this._queueLoad(scene, onLoaded);
  37493. };
  37494. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37495. var _this = this;
  37496. scene._addPendingData(this);
  37497. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  37498. _this._delayLoadingFunction(JSON.parse(data), _this);
  37499. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37500. _this._delayInfo = [];
  37501. scene._removePendingData(_this);
  37502. var meshes = _this._meshes;
  37503. var numOfMeshes = meshes.length;
  37504. for (var index = 0; index < numOfMeshes; index++) {
  37505. _this._applyToMesh(meshes[index]);
  37506. }
  37507. if (onLoaded) {
  37508. onLoaded();
  37509. }
  37510. }, function () { }, scene.database);
  37511. };
  37512. /**
  37513. * Invert the geometry to move from a right handed system to a left handed one.
  37514. */
  37515. Geometry.prototype.toLeftHanded = function () {
  37516. // Flip faces
  37517. var tIndices = this.getIndices(false);
  37518. if (tIndices != null && tIndices.length > 0) {
  37519. for (var i = 0; i < tIndices.length; i += 3) {
  37520. var tTemp = tIndices[i + 0];
  37521. tIndices[i + 0] = tIndices[i + 2];
  37522. tIndices[i + 2] = tTemp;
  37523. }
  37524. this.setIndices(tIndices);
  37525. }
  37526. // Negate position.z
  37527. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37528. if (tPositions != null && tPositions.length > 0) {
  37529. for (var i = 0; i < tPositions.length; i += 3) {
  37530. tPositions[i + 2] = -tPositions[i + 2];
  37531. }
  37532. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37533. }
  37534. // Negate normal.z
  37535. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37536. if (tNormals != null && tNormals.length > 0) {
  37537. for (var i = 0; i < tNormals.length; i += 3) {
  37538. tNormals[i + 2] = -tNormals[i + 2];
  37539. }
  37540. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37541. }
  37542. };
  37543. Geometry.prototype.isDisposed = function () {
  37544. return this._isDisposed;
  37545. };
  37546. Geometry.prototype._disposeVertexArrayObjects = function () {
  37547. if (this._vertexArrayObjects) {
  37548. for (var kind in this._vertexArrayObjects) {
  37549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37550. }
  37551. this._vertexArrayObjects = {};
  37552. }
  37553. };
  37554. Geometry.prototype.dispose = function () {
  37555. var meshes = this._meshes;
  37556. var numOfMeshes = meshes.length;
  37557. var index;
  37558. for (index = 0; index < numOfMeshes; index++) {
  37559. this.releaseForMesh(meshes[index]);
  37560. }
  37561. this._meshes = [];
  37562. this._disposeVertexArrayObjects();
  37563. for (var kind in this._vertexBuffers) {
  37564. this._vertexBuffers[kind].dispose();
  37565. }
  37566. this._vertexBuffers = {};
  37567. this._totalVertices = 0;
  37568. if (this._indexBuffer) {
  37569. this._engine._releaseBuffer(this._indexBuffer);
  37570. }
  37571. this._indexBuffer = null;
  37572. this._indices = [];
  37573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37574. this.delayLoadingFile = null;
  37575. this._delayLoadingFunction = null;
  37576. this._delayInfo = [];
  37577. this._boundingInfo = null;
  37578. this._scene.removeGeometry(this);
  37579. this._isDisposed = true;
  37580. };
  37581. Geometry.prototype.copy = function (id) {
  37582. var vertexData = new BABYLON.VertexData();
  37583. vertexData.indices = [];
  37584. var indices = this.getIndices();
  37585. for (var index = 0; index < indices.length; index++) {
  37586. vertexData.indices.push(indices[index]);
  37587. }
  37588. var updatable = false;
  37589. var stopChecking = false;
  37590. var kind;
  37591. for (kind in this._vertexBuffers) {
  37592. // using slice() to make a copy of the array and not just reference it
  37593. var data = this.getVerticesData(kind);
  37594. if (data instanceof Float32Array) {
  37595. vertexData.set(new Float32Array(data), kind);
  37596. }
  37597. else {
  37598. vertexData.set(data.slice(0), kind);
  37599. }
  37600. if (!stopChecking) {
  37601. updatable = this.getVertexBuffer(kind).isUpdatable();
  37602. stopChecking = !updatable;
  37603. }
  37604. }
  37605. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  37606. geometry.delayLoadState = this.delayLoadState;
  37607. geometry.delayLoadingFile = this.delayLoadingFile;
  37608. geometry._delayLoadingFunction = this._delayLoadingFunction;
  37609. for (kind in this._delayInfo) {
  37610. geometry._delayInfo = geometry._delayInfo || [];
  37611. geometry._delayInfo.push(kind);
  37612. }
  37613. // Bounding info
  37614. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37615. return geometry;
  37616. };
  37617. Geometry.prototype.serialize = function () {
  37618. var serializationObject = {};
  37619. serializationObject.id = this.id;
  37620. if (BABYLON.Tags.HasTags(this)) {
  37621. serializationObject.tags = BABYLON.Tags.GetTags(this);
  37622. }
  37623. return serializationObject;
  37624. };
  37625. Geometry.prototype.serializeVerticeData = function () {
  37626. var serializationObject = this.serialize();
  37627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37628. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37629. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  37630. serializationObject.positions._updatable = true;
  37631. }
  37632. }
  37633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37634. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37635. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  37636. serializationObject.normals._updatable = true;
  37637. }
  37638. }
  37639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37640. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37641. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  37642. serializationObject.uvs._updatable = true;
  37643. }
  37644. }
  37645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37646. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  37647. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  37648. serializationObject.uv2s._updatable = true;
  37649. }
  37650. }
  37651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37652. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  37653. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  37654. serializationObject.uv3s._updatable = true;
  37655. }
  37656. }
  37657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37658. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  37659. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  37660. serializationObject.uv4s._updatable = true;
  37661. }
  37662. }
  37663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37664. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  37665. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  37666. serializationObject.uv5s._updatable = true;
  37667. }
  37668. }
  37669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37670. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  37671. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  37672. serializationObject.uv6s._updatable = true;
  37673. }
  37674. }
  37675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37676. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37677. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  37678. serializationObject.colors._updatable = true;
  37679. }
  37680. }
  37681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37682. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37683. serializationObject.matricesIndices._isExpanded = true;
  37684. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  37685. serializationObject.matricesIndices._updatable = true;
  37686. }
  37687. }
  37688. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37689. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  37690. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  37691. serializationObject.matricesWeights._updatable = true;
  37692. }
  37693. }
  37694. serializationObject.indices = this.getIndices();
  37695. return serializationObject;
  37696. };
  37697. // Statics
  37698. Geometry.ExtractFromMesh = function (mesh, id) {
  37699. var geometry = mesh._geometry;
  37700. if (!geometry) {
  37701. return null;
  37702. }
  37703. return geometry.copy(id);
  37704. };
  37705. /**
  37706. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37707. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37708. * Be aware Math.random() could cause collisions, but:
  37709. * "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"
  37710. */
  37711. Geometry.RandomId = function () {
  37712. return BABYLON.Tools.RandomId();
  37713. };
  37714. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  37715. var scene = mesh.getScene();
  37716. // Geometry
  37717. var geometryId = parsedGeometry.geometryId;
  37718. if (geometryId) {
  37719. var geometry = scene.getGeometryByID(geometryId);
  37720. if (geometry) {
  37721. geometry.applyToMesh(mesh);
  37722. }
  37723. }
  37724. else if (parsedGeometry instanceof ArrayBuffer) {
  37725. var binaryInfo = mesh._binaryInfo;
  37726. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37727. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37728. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37729. }
  37730. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37731. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37732. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37733. }
  37734. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37735. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37736. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37737. }
  37738. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37739. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37740. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37741. }
  37742. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37743. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37744. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37745. }
  37746. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37747. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37748. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37749. }
  37750. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37751. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37752. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37753. }
  37754. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37755. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37756. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37757. }
  37758. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37759. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37760. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37761. }
  37762. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37763. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37764. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37765. }
  37766. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37767. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37768. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37769. }
  37770. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37771. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37772. mesh.setIndices(indicesData);
  37773. }
  37774. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37775. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37776. mesh.subMeshes = [];
  37777. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37778. var materialIndex = subMeshesData[(i * 5) + 0];
  37779. var verticesStart = subMeshesData[(i * 5) + 1];
  37780. var verticesCount = subMeshesData[(i * 5) + 2];
  37781. var indexStart = subMeshesData[(i * 5) + 3];
  37782. var indexCount = subMeshesData[(i * 5) + 4];
  37783. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37784. }
  37785. }
  37786. }
  37787. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37788. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37789. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37790. if (parsedGeometry.uvs) {
  37791. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37792. }
  37793. if (parsedGeometry.uvs2) {
  37794. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37795. }
  37796. if (parsedGeometry.uvs3) {
  37797. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37798. }
  37799. if (parsedGeometry.uvs4) {
  37800. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37801. }
  37802. if (parsedGeometry.uvs5) {
  37803. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37804. }
  37805. if (parsedGeometry.uvs6) {
  37806. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37807. }
  37808. if (parsedGeometry.colors) {
  37809. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37810. }
  37811. if (parsedGeometry.matricesIndices) {
  37812. if (!parsedGeometry.matricesIndices._isExpanded) {
  37813. var floatIndices = [];
  37814. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37815. var matricesIndex = parsedGeometry.matricesIndices[i];
  37816. floatIndices.push(matricesIndex & 0x000000FF);
  37817. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37818. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37819. floatIndices.push(matricesIndex >> 24);
  37820. }
  37821. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37822. }
  37823. else {
  37824. delete parsedGeometry.matricesIndices._isExpanded;
  37825. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37826. }
  37827. }
  37828. if (parsedGeometry.matricesIndicesExtra) {
  37829. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37830. var floatIndices = [];
  37831. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37832. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37833. floatIndices.push(matricesIndex & 0x000000FF);
  37834. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37835. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37836. floatIndices.push(matricesIndex >> 24);
  37837. }
  37838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37839. }
  37840. else {
  37841. delete parsedGeometry.matricesIndices._isExpanded;
  37842. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37843. }
  37844. }
  37845. if (parsedGeometry.matricesWeights) {
  37846. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37847. }
  37848. if (parsedGeometry.matricesWeightsExtra) {
  37849. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37850. }
  37851. mesh.setIndices(parsedGeometry.indices);
  37852. }
  37853. // SubMeshes
  37854. if (parsedGeometry.subMeshes) {
  37855. mesh.subMeshes = [];
  37856. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37857. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37858. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37859. }
  37860. }
  37861. // Flat shading
  37862. if (mesh._shouldGenerateFlatShading) {
  37863. mesh.convertToFlatShadedMesh();
  37864. delete mesh._shouldGenerateFlatShading;
  37865. }
  37866. // Update
  37867. mesh.computeWorldMatrix(true);
  37868. // Octree
  37869. if (scene['_selectionOctree']) {
  37870. scene['_selectionOctree'].addMesh(mesh);
  37871. }
  37872. };
  37873. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37874. if (scene.getGeometryByID(parsedVertexData.id)) {
  37875. return null; // null since geometry could be something else than a box...
  37876. }
  37877. var geometry = new Geometry(parsedVertexData.id, scene);
  37878. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37879. if (parsedVertexData.delayLoadingFile) {
  37880. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37881. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37882. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37883. geometry._delayInfo = [];
  37884. if (parsedVertexData.hasUVs) {
  37885. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37886. }
  37887. if (parsedVertexData.hasUVs2) {
  37888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37889. }
  37890. if (parsedVertexData.hasUVs3) {
  37891. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37892. }
  37893. if (parsedVertexData.hasUVs4) {
  37894. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37895. }
  37896. if (parsedVertexData.hasUVs5) {
  37897. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37898. }
  37899. if (parsedVertexData.hasUVs6) {
  37900. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37901. }
  37902. if (parsedVertexData.hasColors) {
  37903. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37904. }
  37905. if (parsedVertexData.hasMatricesIndices) {
  37906. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37907. }
  37908. if (parsedVertexData.hasMatricesWeights) {
  37909. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37910. }
  37911. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37912. }
  37913. else {
  37914. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37915. }
  37916. scene.pushGeometry(geometry, true);
  37917. return geometry;
  37918. };
  37919. return Geometry;
  37920. }());
  37921. BABYLON.Geometry = Geometry;
  37922. /////// Primitives //////////////////////////////////////////////
  37923. (function (Geometry) {
  37924. var Primitives;
  37925. (function (Primitives) {
  37926. /// Abstract class
  37927. var _Primitive = (function (_super) {
  37928. __extends(_Primitive, _super);
  37929. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  37930. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  37931. _this._canBeRegenerated = _canBeRegenerated;
  37932. _this._beingRegenerated = true;
  37933. _this.regenerate();
  37934. _this._beingRegenerated = false;
  37935. return _this;
  37936. }
  37937. _Primitive.prototype.canBeRegenerated = function () {
  37938. return this._canBeRegenerated;
  37939. };
  37940. _Primitive.prototype.regenerate = function () {
  37941. if (!this._canBeRegenerated) {
  37942. return;
  37943. }
  37944. this._beingRegenerated = true;
  37945. this.setAllVerticesData(this._regenerateVertexData(), false);
  37946. this._beingRegenerated = false;
  37947. };
  37948. _Primitive.prototype.asNewGeometry = function (id) {
  37949. return _super.prototype.copy.call(this, id);
  37950. };
  37951. // overrides
  37952. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  37953. if (!this._beingRegenerated) {
  37954. return;
  37955. }
  37956. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37957. };
  37958. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  37959. if (!this._beingRegenerated) {
  37960. return;
  37961. }
  37962. _super.prototype.setVerticesData.call(this, kind, data, false);
  37963. };
  37964. // to override
  37965. // protected
  37966. _Primitive.prototype._regenerateVertexData = function () {
  37967. throw new Error("Abstract method");
  37968. };
  37969. _Primitive.prototype.copy = function (id) {
  37970. throw new Error("Must be overriden in sub-classes.");
  37971. };
  37972. _Primitive.prototype.serialize = function () {
  37973. var serializationObject = _super.prototype.serialize.call(this);
  37974. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37975. return serializationObject;
  37976. };
  37977. return _Primitive;
  37978. }(Geometry));
  37979. Primitives._Primitive = _Primitive;
  37980. var Ribbon = (function (_super) {
  37981. __extends(Ribbon, _super);
  37982. // Members
  37983. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  37984. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37985. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37986. _this.pathArray = pathArray;
  37987. _this.closeArray = closeArray;
  37988. _this.closePath = closePath;
  37989. _this.offset = offset;
  37990. _this.side = side;
  37991. return _this;
  37992. }
  37993. Ribbon.prototype._regenerateVertexData = function () {
  37994. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37995. };
  37996. Ribbon.prototype.copy = function (id) {
  37997. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  37998. };
  37999. return Ribbon;
  38000. }(_Primitive));
  38001. Primitives.Ribbon = Ribbon;
  38002. var Box = (function (_super) {
  38003. __extends(Box, _super);
  38004. // Members
  38005. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  38006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38008. _this.size = size;
  38009. _this.side = side;
  38010. return _this;
  38011. }
  38012. Box.prototype._regenerateVertexData = function () {
  38013. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38014. };
  38015. Box.prototype.copy = function (id) {
  38016. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38017. };
  38018. Box.prototype.serialize = function () {
  38019. var serializationObject = _super.prototype.serialize.call(this);
  38020. serializationObject.size = this.size;
  38021. return serializationObject;
  38022. };
  38023. Box.Parse = function (parsedBox, scene) {
  38024. if (scene.getGeometryByID(parsedBox.id)) {
  38025. return null; // null since geometry could be something else than a box...
  38026. }
  38027. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  38028. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  38029. scene.pushGeometry(box, true);
  38030. return box;
  38031. };
  38032. return Box;
  38033. }(_Primitive));
  38034. Primitives.Box = Box;
  38035. var Sphere = (function (_super) {
  38036. __extends(Sphere, _super);
  38037. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  38038. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38039. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38040. _this.segments = segments;
  38041. _this.diameter = diameter;
  38042. _this.side = side;
  38043. return _this;
  38044. }
  38045. Sphere.prototype._regenerateVertexData = function () {
  38046. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  38047. };
  38048. Sphere.prototype.copy = function (id) {
  38049. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  38050. };
  38051. Sphere.prototype.serialize = function () {
  38052. var serializationObject = _super.prototype.serialize.call(this);
  38053. serializationObject.segments = this.segments;
  38054. serializationObject.diameter = this.diameter;
  38055. return serializationObject;
  38056. };
  38057. Sphere.Parse = function (parsedSphere, scene) {
  38058. if (scene.getGeometryByID(parsedSphere.id)) {
  38059. return null; // null since geometry could be something else than a sphere...
  38060. }
  38061. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  38062. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  38063. scene.pushGeometry(sphere, true);
  38064. return sphere;
  38065. };
  38066. return Sphere;
  38067. }(_Primitive));
  38068. Primitives.Sphere = Sphere;
  38069. var Disc = (function (_super) {
  38070. __extends(Disc, _super);
  38071. // Members
  38072. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  38073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38075. _this.radius = radius;
  38076. _this.tessellation = tessellation;
  38077. _this.side = side;
  38078. return _this;
  38079. }
  38080. Disc.prototype._regenerateVertexData = function () {
  38081. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  38082. };
  38083. Disc.prototype.copy = function (id) {
  38084. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  38085. };
  38086. return Disc;
  38087. }(_Primitive));
  38088. Primitives.Disc = Disc;
  38089. var Cylinder = (function (_super) {
  38090. __extends(Cylinder, _super);
  38091. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  38092. if (subdivisions === void 0) { subdivisions = 1; }
  38093. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38094. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38095. _this.height = height;
  38096. _this.diameterTop = diameterTop;
  38097. _this.diameterBottom = diameterBottom;
  38098. _this.tessellation = tessellation;
  38099. _this.subdivisions = subdivisions;
  38100. _this.side = side;
  38101. return _this;
  38102. }
  38103. Cylinder.prototype._regenerateVertexData = function () {
  38104. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  38105. };
  38106. Cylinder.prototype.copy = function (id) {
  38107. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  38108. };
  38109. Cylinder.prototype.serialize = function () {
  38110. var serializationObject = _super.prototype.serialize.call(this);
  38111. serializationObject.height = this.height;
  38112. serializationObject.diameterTop = this.diameterTop;
  38113. serializationObject.diameterBottom = this.diameterBottom;
  38114. serializationObject.tessellation = this.tessellation;
  38115. return serializationObject;
  38116. };
  38117. Cylinder.Parse = function (parsedCylinder, scene) {
  38118. if (scene.getGeometryByID(parsedCylinder.id)) {
  38119. return null; // null since geometry could be something else than a cylinder...
  38120. }
  38121. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  38122. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  38123. scene.pushGeometry(cylinder, true);
  38124. return cylinder;
  38125. };
  38126. return Cylinder;
  38127. }(_Primitive));
  38128. Primitives.Cylinder = Cylinder;
  38129. var Torus = (function (_super) {
  38130. __extends(Torus, _super);
  38131. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  38132. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38133. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38134. _this.diameter = diameter;
  38135. _this.thickness = thickness;
  38136. _this.tessellation = tessellation;
  38137. _this.side = side;
  38138. return _this;
  38139. }
  38140. Torus.prototype._regenerateVertexData = function () {
  38141. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  38142. };
  38143. Torus.prototype.copy = function (id) {
  38144. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  38145. };
  38146. Torus.prototype.serialize = function () {
  38147. var serializationObject = _super.prototype.serialize.call(this);
  38148. serializationObject.diameter = this.diameter;
  38149. serializationObject.thickness = this.thickness;
  38150. serializationObject.tessellation = this.tessellation;
  38151. return serializationObject;
  38152. };
  38153. Torus.Parse = function (parsedTorus, scene) {
  38154. if (scene.getGeometryByID(parsedTorus.id)) {
  38155. return null; // null since geometry could be something else than a torus...
  38156. }
  38157. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38158. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38159. scene.pushGeometry(torus, true);
  38160. return torus;
  38161. };
  38162. return Torus;
  38163. }(_Primitive));
  38164. Primitives.Torus = Torus;
  38165. var Ground = (function (_super) {
  38166. __extends(Ground, _super);
  38167. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  38168. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38169. _this.width = width;
  38170. _this.height = height;
  38171. _this.subdivisions = subdivisions;
  38172. return _this;
  38173. }
  38174. Ground.prototype._regenerateVertexData = function () {
  38175. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38176. };
  38177. Ground.prototype.copy = function (id) {
  38178. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38179. };
  38180. Ground.prototype.serialize = function () {
  38181. var serializationObject = _super.prototype.serialize.call(this);
  38182. serializationObject.width = this.width;
  38183. serializationObject.height = this.height;
  38184. serializationObject.subdivisions = this.subdivisions;
  38185. return serializationObject;
  38186. };
  38187. Ground.Parse = function (parsedGround, scene) {
  38188. if (scene.getGeometryByID(parsedGround.id)) {
  38189. return null; // null since geometry could be something else than a ground...
  38190. }
  38191. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38192. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38193. scene.pushGeometry(ground, true);
  38194. return ground;
  38195. };
  38196. return Ground;
  38197. }(_Primitive));
  38198. Primitives.Ground = Ground;
  38199. var TiledGround = (function (_super) {
  38200. __extends(TiledGround, _super);
  38201. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  38202. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38203. _this.xmin = xmin;
  38204. _this.zmin = zmin;
  38205. _this.xmax = xmax;
  38206. _this.zmax = zmax;
  38207. _this.subdivisions = subdivisions;
  38208. _this.precision = precision;
  38209. return _this;
  38210. }
  38211. TiledGround.prototype._regenerateVertexData = function () {
  38212. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  38213. };
  38214. TiledGround.prototype.copy = function (id) {
  38215. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  38216. };
  38217. return TiledGround;
  38218. }(_Primitive));
  38219. Primitives.TiledGround = TiledGround;
  38220. var Plane = (function (_super) {
  38221. __extends(Plane, _super);
  38222. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  38223. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38224. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38225. _this.size = size;
  38226. _this.side = side;
  38227. return _this;
  38228. }
  38229. Plane.prototype._regenerateVertexData = function () {
  38230. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  38231. };
  38232. Plane.prototype.copy = function (id) {
  38233. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38234. };
  38235. Plane.prototype.serialize = function () {
  38236. var serializationObject = _super.prototype.serialize.call(this);
  38237. serializationObject.size = this.size;
  38238. return serializationObject;
  38239. };
  38240. Plane.Parse = function (parsedPlane, scene) {
  38241. if (scene.getGeometryByID(parsedPlane.id)) {
  38242. return null; // null since geometry could be something else than a ground...
  38243. }
  38244. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  38245. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  38246. scene.pushGeometry(plane, true);
  38247. return plane;
  38248. };
  38249. return Plane;
  38250. }(_Primitive));
  38251. Primitives.Plane = Plane;
  38252. var TorusKnot = (function (_super) {
  38253. __extends(TorusKnot, _super);
  38254. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  38255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38257. _this.radius = radius;
  38258. _this.tube = tube;
  38259. _this.radialSegments = radialSegments;
  38260. _this.tubularSegments = tubularSegments;
  38261. _this.p = p;
  38262. _this.q = q;
  38263. _this.side = side;
  38264. return _this;
  38265. }
  38266. TorusKnot.prototype._regenerateVertexData = function () {
  38267. 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 });
  38268. };
  38269. TorusKnot.prototype.copy = function (id) {
  38270. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38271. };
  38272. TorusKnot.prototype.serialize = function () {
  38273. var serializationObject = _super.prototype.serialize.call(this);
  38274. serializationObject.radius = this.radius;
  38275. serializationObject.tube = this.tube;
  38276. serializationObject.radialSegments = this.radialSegments;
  38277. serializationObject.tubularSegments = this.tubularSegments;
  38278. serializationObject.p = this.p;
  38279. serializationObject.q = this.q;
  38280. return serializationObject;
  38281. };
  38282. ;
  38283. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  38284. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38285. return null; // null since geometry could be something else than a ground...
  38286. }
  38287. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38288. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38289. scene.pushGeometry(torusKnot, true);
  38290. return torusKnot;
  38291. };
  38292. return TorusKnot;
  38293. }(_Primitive));
  38294. Primitives.TorusKnot = TorusKnot;
  38295. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  38296. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  38297. })(BABYLON || (BABYLON = {}));
  38298. //# sourceMappingURL=babylon.geometry.js.map
  38299. var BABYLON;
  38300. (function (BABYLON) {
  38301. var GroundMesh = (function (_super) {
  38302. __extends(GroundMesh, _super);
  38303. function GroundMesh(name, scene) {
  38304. var _this = _super.call(this, name, scene) || this;
  38305. _this.generateOctree = false;
  38306. _this._worldInverse = new BABYLON.Matrix();
  38307. return _this;
  38308. }
  38309. GroundMesh.prototype.getClassName = function () {
  38310. return "GroundMesh";
  38311. };
  38312. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  38313. get: function () {
  38314. return Math.min(this._subdivisionsX, this._subdivisionsY);
  38315. },
  38316. enumerable: true,
  38317. configurable: true
  38318. });
  38319. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  38320. get: function () {
  38321. return this._subdivisionsX;
  38322. },
  38323. enumerable: true,
  38324. configurable: true
  38325. });
  38326. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  38327. get: function () {
  38328. return this._subdivisionsY;
  38329. },
  38330. enumerable: true,
  38331. configurable: true
  38332. });
  38333. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  38334. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  38335. this._subdivisionsX = chunksCount;
  38336. this._subdivisionsY = chunksCount;
  38337. this.subdivide(chunksCount);
  38338. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  38339. };
  38340. /**
  38341. * Returns a height (y) value in the Worl system :
  38342. * the ground altitude at the coordinates (x, z) expressed in the World system.
  38343. * Returns the ground y position if (x, z) are outside the ground surface.
  38344. */
  38345. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  38346. var world = this.getWorldMatrix();
  38347. var invMat = BABYLON.Tmp.Matrix[5];
  38348. world.invertToRef(invMat);
  38349. var tmpVect = BABYLON.Tmp.Vector3[8];
  38350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  38351. x = tmpVect.x;
  38352. z = tmpVect.z;
  38353. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38354. return this.position.y;
  38355. }
  38356. if (!this._heightQuads || this._heightQuads.length == 0) {
  38357. this._initHeightQuads();
  38358. this._computeHeightQuads();
  38359. }
  38360. var facet = this._getFacetAt(x, z);
  38361. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  38362. // return y in the World system
  38363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  38364. return tmpVect.y;
  38365. };
  38366. /**
  38367. * Returns a normalized vector (Vector3) orthogonal to the ground
  38368. * at the ground coordinates (x, z) expressed in the World system.
  38369. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  38370. */
  38371. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  38372. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  38373. this.getNormalAtCoordinatesToRef(x, z, normal);
  38374. return normal;
  38375. };
  38376. /**
  38377. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  38378. * at the ground coordinates (x, z) expressed in the World system.
  38379. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  38380. * Returns the GroundMesh.
  38381. */
  38382. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  38383. var world = this.getWorldMatrix();
  38384. var tmpMat = BABYLON.Tmp.Matrix[5];
  38385. world.invertToRef(tmpMat);
  38386. var tmpVect = BABYLON.Tmp.Vector3[8];
  38387. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  38388. x = tmpVect.x;
  38389. z = tmpVect.z;
  38390. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38391. return this;
  38392. }
  38393. if (!this._heightQuads || this._heightQuads.length == 0) {
  38394. this._initHeightQuads();
  38395. this._computeHeightQuads();
  38396. }
  38397. var facet = this._getFacetAt(x, z);
  38398. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  38399. return this;
  38400. };
  38401. /**
  38402. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  38403. * if the ground has been updated.
  38404. * This can be used in the render loop
  38405. */
  38406. GroundMesh.prototype.updateCoordinateHeights = function () {
  38407. if (!this._heightQuads || this._heightQuads.length == 0) {
  38408. this._initHeightQuads();
  38409. }
  38410. this._computeHeightQuads();
  38411. };
  38412. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  38413. GroundMesh.prototype._getFacetAt = function (x, z) {
  38414. // retrieve col and row from x, z coordinates in the ground local system
  38415. var subdivisionsX = this._subdivisionsX;
  38416. var subdivisionsY = this._subdivisionsY;
  38417. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  38418. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  38419. var quad = this._heightQuads[row * this._subdivisionsX + col];
  38420. var facet;
  38421. if (z < quad.slope.x * x + quad.slope.y) {
  38422. facet = quad.facet1;
  38423. }
  38424. else {
  38425. facet = quad.facet2;
  38426. }
  38427. return facet;
  38428. };
  38429. // Creates and populates the heightMap array with "facet" elements :
  38430. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  38431. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38432. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38433. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38434. GroundMesh.prototype._initHeightQuads = function () {
  38435. var subdivisionsX = this._subdivisionsX;
  38436. var subdivisionsY = this._subdivisionsY;
  38437. this._heightQuads = new Array();
  38438. for (var row = 0; row < subdivisionsY; row++) {
  38439. for (var col = 0; col < subdivisionsX; col++) {
  38440. 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) };
  38441. this._heightQuads[row * subdivisionsX + col] = quad;
  38442. }
  38443. }
  38444. };
  38445. // Compute each quad element values and update the the heightMap array :
  38446. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38447. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38448. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38449. GroundMesh.prototype._computeHeightQuads = function () {
  38450. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38451. var v1 = BABYLON.Tmp.Vector3[3];
  38452. var v2 = BABYLON.Tmp.Vector3[2];
  38453. var v3 = BABYLON.Tmp.Vector3[1];
  38454. var v4 = BABYLON.Tmp.Vector3[0];
  38455. var v1v2 = BABYLON.Tmp.Vector3[4];
  38456. var v1v3 = BABYLON.Tmp.Vector3[5];
  38457. var v1v4 = BABYLON.Tmp.Vector3[6];
  38458. var norm1 = BABYLON.Tmp.Vector3[7];
  38459. var norm2 = BABYLON.Tmp.Vector3[8];
  38460. var i = 0;
  38461. var j = 0;
  38462. var k = 0;
  38463. var cd = 0; // 2D slope coefficient : z = cd * x + h
  38464. var h = 0;
  38465. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  38466. var d2 = 0;
  38467. var subdivisionsX = this._subdivisionsX;
  38468. var subdivisionsY = this._subdivisionsY;
  38469. for (var row = 0; row < subdivisionsY; row++) {
  38470. for (var col = 0; col < subdivisionsX; col++) {
  38471. i = col * 3;
  38472. j = row * (subdivisionsX + 1) * 3;
  38473. k = (row + 1) * (subdivisionsX + 1) * 3;
  38474. v1.x = positions[j + i];
  38475. v1.y = positions[j + i + 1];
  38476. v1.z = positions[j + i + 2];
  38477. v2.x = positions[j + i + 3];
  38478. v2.y = positions[j + i + 4];
  38479. v2.z = positions[j + i + 5];
  38480. v3.x = positions[k + i];
  38481. v3.y = positions[k + i + 1];
  38482. v3.z = positions[k + i + 2];
  38483. v4.x = positions[k + i + 3];
  38484. v4.y = positions[k + i + 4];
  38485. v4.z = positions[k + i + 5];
  38486. // 2D slope V1V4
  38487. cd = (v4.z - v1.z) / (v4.x - v1.x);
  38488. h = v1.z - cd * v1.x; // v1 belongs to the slope
  38489. // facet equations :
  38490. // we compute each facet normal vector
  38491. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  38492. // we compute the value d by applying the equation to v1 which belongs to the plane
  38493. // then we store the facet equation in a Vector4
  38494. v2.subtractToRef(v1, v1v2);
  38495. v3.subtractToRef(v1, v1v3);
  38496. v4.subtractToRef(v1, v1v4);
  38497. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  38498. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  38499. norm1.normalize();
  38500. norm2.normalize();
  38501. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  38502. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  38503. var quad = this._heightQuads[row * subdivisionsX + col];
  38504. quad.slope.copyFromFloats(cd, h);
  38505. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  38506. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  38507. }
  38508. }
  38509. };
  38510. return GroundMesh;
  38511. }(BABYLON.Mesh));
  38512. BABYLON.GroundMesh = GroundMesh;
  38513. })(BABYLON || (BABYLON = {}));
  38514. //# sourceMappingURL=babylon.groundMesh.js.map
  38515. var BABYLON;
  38516. (function (BABYLON) {
  38517. var LinesMesh = (function (_super) {
  38518. __extends(LinesMesh, _super);
  38519. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  38520. if (parent === void 0) { parent = null; }
  38521. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38522. _this.color = new BABYLON.Color3(1, 1, 1);
  38523. _this.alpha = 1;
  38524. _this._positionBuffer = {};
  38525. if (source) {
  38526. _this.color = source.color.clone();
  38527. _this.alpha = source.alpha;
  38528. }
  38529. _this._intersectionThreshold = 0.1;
  38530. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  38531. attributes: [BABYLON.VertexBuffer.PositionKind],
  38532. uniforms: ["worldViewProjection", "color"],
  38533. needAlphaBlending: true
  38534. });
  38535. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  38536. return _this;
  38537. }
  38538. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38539. /**
  38540. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38541. * This margin is expressed in world space coordinates, so its value may vary.
  38542. * Default value is 0.1
  38543. * @returns the intersection Threshold value.
  38544. */
  38545. get: function () {
  38546. return this._intersectionThreshold;
  38547. },
  38548. /**
  38549. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38550. * This margin is expressed in world space coordinates, so its value may vary.
  38551. * @param value the new threshold to apply
  38552. */
  38553. set: function (value) {
  38554. if (this._intersectionThreshold === value) {
  38555. return;
  38556. }
  38557. this._intersectionThreshold = value;
  38558. if (this.geometry) {
  38559. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38560. }
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. LinesMesh.prototype.getClassName = function () {
  38566. return "LinesMesh";
  38567. };
  38568. Object.defineProperty(LinesMesh.prototype, "material", {
  38569. get: function () {
  38570. return this._colorShader;
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38576. get: function () {
  38577. return false;
  38578. },
  38579. enumerable: true,
  38580. configurable: true
  38581. });
  38582. LinesMesh.prototype.createInstance = function (name) {
  38583. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38584. return null;
  38585. };
  38586. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38587. var engine = this.getScene().getEngine();
  38588. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  38589. // VBOs
  38590. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  38591. // Color
  38592. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38593. };
  38594. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38595. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38596. return;
  38597. }
  38598. var engine = this.getScene().getEngine();
  38599. // Draw order
  38600. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38601. };
  38602. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38603. this._colorShader.dispose();
  38604. _super.prototype.dispose.call(this, doNotRecurse);
  38605. };
  38606. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38607. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38608. };
  38609. return LinesMesh;
  38610. }(BABYLON.Mesh));
  38611. BABYLON.LinesMesh = LinesMesh;
  38612. })(BABYLON || (BABYLON = {}));
  38613. //# sourceMappingURL=babylon.linesMesh.js.map
  38614. var BABYLON;
  38615. (function (BABYLON) {
  38616. var DefaultLoadingScreen = (function () {
  38617. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  38618. if (_loadingText === void 0) { _loadingText = ""; }
  38619. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  38620. var _this = this;
  38621. this._renderingCanvas = _renderingCanvas;
  38622. this._loadingText = _loadingText;
  38623. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  38624. // Resize
  38625. this._resizeLoadingUI = function () {
  38626. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  38627. _this._loadingDiv.style.position = "absolute";
  38628. _this._loadingDiv.style.left = canvasRect.left + "px";
  38629. _this._loadingDiv.style.top = canvasRect.top + "px";
  38630. _this._loadingDiv.style.width = canvasRect.width + "px";
  38631. _this._loadingDiv.style.height = canvasRect.height + "px";
  38632. };
  38633. }
  38634. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  38635. var _this = this;
  38636. if (this._loadingDiv) {
  38637. // Do not add a loading screen if there is already one
  38638. return;
  38639. }
  38640. this._loadingDiv = document.createElement("div");
  38641. this._loadingDiv.id = "babylonjsLoadingDiv";
  38642. this._loadingDiv.style.opacity = "0";
  38643. this._loadingDiv.style.transition = "opacity 1.5s ease";
  38644. // Loading text
  38645. this._loadingTextDiv = document.createElement("div");
  38646. this._loadingTextDiv.style.position = "absolute";
  38647. this._loadingTextDiv.style.left = "0";
  38648. this._loadingTextDiv.style.top = "50%";
  38649. this._loadingTextDiv.style.marginTop = "80px";
  38650. this._loadingTextDiv.style.width = "100%";
  38651. this._loadingTextDiv.style.height = "20px";
  38652. this._loadingTextDiv.style.fontFamily = "Arial";
  38653. this._loadingTextDiv.style.fontSize = "14px";
  38654. this._loadingTextDiv.style.color = "white";
  38655. this._loadingTextDiv.style.textAlign = "center";
  38656. this._loadingTextDiv.innerHTML = "Loading";
  38657. this._loadingDiv.appendChild(this._loadingTextDiv);
  38658. //set the predefined text
  38659. this._loadingTextDiv.innerHTML = this._loadingText;
  38660. // Loading img
  38661. var imgBack = new Image();
  38662. 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==";
  38663. imgBack.style.position = "absolute";
  38664. imgBack.style.left = "50%";
  38665. imgBack.style.top = "50%";
  38666. imgBack.style.marginLeft = "-50px";
  38667. imgBack.style.marginTop = "-50px";
  38668. imgBack.style.transition = "transform 1.0s ease";
  38669. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  38670. var deg = 360;
  38671. var onTransitionEnd = function () {
  38672. deg += 360;
  38673. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  38674. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  38675. };
  38676. imgBack.addEventListener("transitionend", onTransitionEnd);
  38677. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  38678. this._loadingDiv.appendChild(imgBack);
  38679. // front image
  38680. var imgFront = new Image();
  38681. 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=";
  38682. imgFront.style.position = "absolute";
  38683. imgFront.style.left = "50%";
  38684. imgFront.style.top = "50%";
  38685. imgFront.style.marginLeft = "-50px";
  38686. imgFront.style.marginTop = "-50px";
  38687. this._loadingDiv.appendChild(imgFront);
  38688. this._resizeLoadingUI();
  38689. window.addEventListener("resize", this._resizeLoadingUI);
  38690. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38691. document.body.appendChild(this._loadingDiv);
  38692. setTimeout(function () {
  38693. _this._loadingDiv.style.opacity = "1";
  38694. imgBack.style.transform = "rotateZ(360deg)";
  38695. imgBack.style.webkitTransform = "rotateZ(360deg)";
  38696. }, 0);
  38697. };
  38698. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  38699. var _this = this;
  38700. if (!this._loadingDiv) {
  38701. return;
  38702. }
  38703. var onTransitionEnd = function () {
  38704. if (!_this._loadingDiv) {
  38705. return;
  38706. }
  38707. document.body.removeChild(_this._loadingDiv);
  38708. window.removeEventListener("resize", _this._resizeLoadingUI);
  38709. _this._loadingDiv = null;
  38710. };
  38711. this._loadingDiv.style.opacity = "0";
  38712. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  38713. };
  38714. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  38715. set: function (text) {
  38716. this._loadingText = text;
  38717. if (this._loadingTextDiv) {
  38718. this._loadingTextDiv.innerHTML = this._loadingText;
  38719. }
  38720. },
  38721. enumerable: true,
  38722. configurable: true
  38723. });
  38724. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  38725. get: function () {
  38726. return this._loadingDivBackgroundColor;
  38727. },
  38728. set: function (color) {
  38729. this._loadingDivBackgroundColor = color;
  38730. if (!this._loadingDiv) {
  38731. return;
  38732. }
  38733. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38734. },
  38735. enumerable: true,
  38736. configurable: true
  38737. });
  38738. return DefaultLoadingScreen;
  38739. }());
  38740. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  38741. })(BABYLON || (BABYLON = {}));
  38742. //# sourceMappingURL=babylon.loadingScreen.js.map
  38743. var BABYLON;
  38744. (function (BABYLON) {
  38745. var AudioEngine = (function () {
  38746. function AudioEngine() {
  38747. this._audioContext = null;
  38748. this._audioContextInitialized = false;
  38749. this.canUseWebAudio = false;
  38750. this.WarnedWebAudioUnsupported = false;
  38751. this.unlocked = false;
  38752. this.isMP3supported = false;
  38753. this.isOGGsupported = false;
  38754. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38755. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38756. this.canUseWebAudio = true;
  38757. }
  38758. var audioElem = document.createElement('audio');
  38759. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38760. this.isMP3supported = true;
  38761. }
  38762. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38763. this.isOGGsupported = true;
  38764. }
  38765. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38766. this._unlockiOSaudio();
  38767. }
  38768. else {
  38769. this.unlocked = true;
  38770. }
  38771. }
  38772. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38773. get: function () {
  38774. if (!this._audioContextInitialized) {
  38775. this._initializeAudioContext();
  38776. }
  38777. return this._audioContext;
  38778. },
  38779. enumerable: true,
  38780. configurable: true
  38781. });
  38782. AudioEngine.prototype._unlockiOSaudio = function () {
  38783. var _this = this;
  38784. var unlockaudio = function () {
  38785. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38786. var source = _this.audioContext.createBufferSource();
  38787. source.buffer = buffer;
  38788. source.connect(_this.audioContext.destination);
  38789. source.start(0);
  38790. setTimeout(function () {
  38791. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38792. _this.unlocked = true;
  38793. window.removeEventListener('touchend', unlockaudio, false);
  38794. if (_this.onAudioUnlocked) {
  38795. _this.onAudioUnlocked();
  38796. }
  38797. }
  38798. }, 0);
  38799. };
  38800. window.addEventListener('touchend', unlockaudio, false);
  38801. };
  38802. AudioEngine.prototype._initializeAudioContext = function () {
  38803. try {
  38804. if (this.canUseWebAudio) {
  38805. this._audioContext = new AudioContext();
  38806. // create a global volume gain node
  38807. this.masterGain = this._audioContext.createGain();
  38808. this.masterGain.gain.value = 1;
  38809. this.masterGain.connect(this._audioContext.destination);
  38810. this._audioContextInitialized = true;
  38811. }
  38812. }
  38813. catch (e) {
  38814. this.canUseWebAudio = false;
  38815. BABYLON.Tools.Error("Web Audio: " + e.message);
  38816. }
  38817. };
  38818. AudioEngine.prototype.dispose = function () {
  38819. if (this.canUseWebAudio && this._audioContextInitialized) {
  38820. if (this._connectedAnalyser) {
  38821. this._connectedAnalyser.stopDebugCanvas();
  38822. this._connectedAnalyser.dispose();
  38823. this.masterGain.disconnect();
  38824. this.masterGain.connect(this._audioContext.destination);
  38825. this._connectedAnalyser = null;
  38826. }
  38827. this.masterGain.gain.value = 1;
  38828. }
  38829. this.WarnedWebAudioUnsupported = false;
  38830. };
  38831. AudioEngine.prototype.getGlobalVolume = function () {
  38832. if (this.canUseWebAudio && this._audioContextInitialized) {
  38833. return this.masterGain.gain.value;
  38834. }
  38835. else {
  38836. return -1;
  38837. }
  38838. };
  38839. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38840. if (this.canUseWebAudio && this._audioContextInitialized) {
  38841. this.masterGain.gain.value = newVolume;
  38842. }
  38843. };
  38844. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38845. if (this._connectedAnalyser) {
  38846. this._connectedAnalyser.stopDebugCanvas();
  38847. }
  38848. if (this.canUseWebAudio && this._audioContextInitialized) {
  38849. this._connectedAnalyser = analyser;
  38850. this.masterGain.disconnect();
  38851. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38852. }
  38853. };
  38854. return AudioEngine;
  38855. }());
  38856. BABYLON.AudioEngine = AudioEngine;
  38857. })(BABYLON || (BABYLON = {}));
  38858. //# sourceMappingURL=babylon.audioEngine.js.map
  38859. var BABYLON;
  38860. (function (BABYLON) {
  38861. var Sound = (function () {
  38862. /**
  38863. * Create a sound and attach it to a scene
  38864. * @param name Name of your sound
  38865. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38866. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38867. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38868. */
  38869. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38870. var _this = this;
  38871. this.autoplay = false;
  38872. this.loop = false;
  38873. this.useCustomAttenuation = false;
  38874. this.spatialSound = false;
  38875. this.refDistance = 1;
  38876. this.rolloffFactor = 1;
  38877. this.maxDistance = 100;
  38878. this.distanceModel = "linear";
  38879. this._panningModel = "equalpower";
  38880. this._playbackRate = 1;
  38881. this._streaming = false;
  38882. this._startTime = 0;
  38883. this._startOffset = 0;
  38884. this._position = BABYLON.Vector3.Zero();
  38885. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38886. this._volume = 1;
  38887. this._isLoaded = false;
  38888. this._isReadyToPlay = false;
  38889. this.isPlaying = false;
  38890. this.isPaused = false;
  38891. this._isDirectional = false;
  38892. // Used if you'd like to create a directional sound.
  38893. // If not set, the sound will be omnidirectional
  38894. this._coneInnerAngle = 360;
  38895. this._coneOuterAngle = 360;
  38896. this._coneOuterGain = 0;
  38897. this._isOutputConnected = false;
  38898. this._urlType = "Unknown";
  38899. this.name = name;
  38900. this._scene = scene;
  38901. this._readyToPlayCallback = readyToPlayCallback;
  38902. // Default custom attenuation function is a linear attenuation
  38903. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38904. if (currentDistance < maxDistance) {
  38905. return currentVolume * (1 - currentDistance / maxDistance);
  38906. }
  38907. else {
  38908. return 0;
  38909. }
  38910. };
  38911. if (options) {
  38912. this.autoplay = options.autoplay || false;
  38913. this.loop = options.loop || false;
  38914. // if volume === 0, we need another way to check this option
  38915. if (options.volume !== undefined) {
  38916. this._volume = options.volume;
  38917. }
  38918. this.spatialSound = options.spatialSound || false;
  38919. this.maxDistance = options.maxDistance || 100;
  38920. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38921. this.rolloffFactor = options.rolloffFactor || 1;
  38922. this.refDistance = options.refDistance || 1;
  38923. this.distanceModel = options.distanceModel || "linear";
  38924. this._playbackRate = options.playbackRate || 1;
  38925. this._streaming = options.streaming || false;
  38926. }
  38927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38928. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38929. this._soundGain.gain.value = this._volume;
  38930. this._inputAudioNode = this._soundGain;
  38931. this._ouputAudioNode = this._soundGain;
  38932. if (this.spatialSound) {
  38933. this._createSpatialParameters();
  38934. }
  38935. this._scene.mainSoundTrack.AddSound(this);
  38936. var validParameter = true;
  38937. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  38938. if (urlOrArrayBuffer) {
  38939. if (typeof (urlOrArrayBuffer) === "string")
  38940. this._urlType = "String";
  38941. if (Array.isArray(urlOrArrayBuffer))
  38942. this._urlType = "Array";
  38943. if (urlOrArrayBuffer instanceof ArrayBuffer)
  38944. this._urlType = "ArrayBuffer";
  38945. var urls = [];
  38946. var codecSupportedFound = false;
  38947. switch (this._urlType) {
  38948. case "ArrayBuffer":
  38949. if (urlOrArrayBuffer.byteLength > 0) {
  38950. codecSupportedFound = true;
  38951. this._soundLoaded(urlOrArrayBuffer);
  38952. }
  38953. break;
  38954. case "String":
  38955. urls.push(urlOrArrayBuffer);
  38956. case "Array":
  38957. if (urls.length === 0)
  38958. urls = urlOrArrayBuffer;
  38959. // If we found a supported format, we load it immediately and stop the loop
  38960. for (var i = 0; i < urls.length; i++) {
  38961. var url = urls[i];
  38962. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  38963. codecSupportedFound = true;
  38964. }
  38965. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  38966. codecSupportedFound = true;
  38967. }
  38968. if (url.indexOf(".wav", url.length - 4) !== -1) {
  38969. codecSupportedFound = true;
  38970. }
  38971. if (codecSupportedFound) {
  38972. // Loading sound using XHR2
  38973. if (!this._streaming) {
  38974. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  38975. }
  38976. else {
  38977. this._htmlAudioElement = new Audio(url);
  38978. this._htmlAudioElement.controls = false;
  38979. this._htmlAudioElement.loop = this.loop;
  38980. this._htmlAudioElement.crossOrigin = "anonymous";
  38981. this._htmlAudioElement.preload = "auto";
  38982. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  38983. _this._isReadyToPlay = true;
  38984. if (_this.autoplay) {
  38985. _this.play();
  38986. }
  38987. if (_this._readyToPlayCallback) {
  38988. _this._readyToPlayCallback();
  38989. }
  38990. });
  38991. document.body.appendChild(this._htmlAudioElement);
  38992. }
  38993. break;
  38994. }
  38995. }
  38996. break;
  38997. default:
  38998. validParameter = false;
  38999. break;
  39000. }
  39001. if (!validParameter) {
  39002. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39003. }
  39004. else {
  39005. if (!codecSupportedFound) {
  39006. this._isReadyToPlay = true;
  39007. // Simulating a ready to play event to avoid breaking code path
  39008. if (this._readyToPlayCallback) {
  39009. window.setTimeout(function () {
  39010. _this._readyToPlayCallback();
  39011. }, 1000);
  39012. }
  39013. }
  39014. }
  39015. }
  39016. }
  39017. else {
  39018. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39019. this._scene.mainSoundTrack.AddSound(this);
  39020. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39021. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39022. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39023. }
  39024. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39025. if (this._readyToPlayCallback) {
  39026. window.setTimeout(function () {
  39027. _this._readyToPlayCallback();
  39028. }, 1000);
  39029. }
  39030. }
  39031. }
  39032. Sound.prototype.dispose = function () {
  39033. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39034. if (this.isPlaying) {
  39035. this.stop();
  39036. }
  39037. this._isReadyToPlay = false;
  39038. if (this.soundTrackId === -1) {
  39039. this._scene.mainSoundTrack.RemoveSound(this);
  39040. }
  39041. else {
  39042. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39043. }
  39044. if (this._soundGain) {
  39045. this._soundGain.disconnect();
  39046. this._soundGain = null;
  39047. }
  39048. if (this._soundPanner) {
  39049. this._soundPanner.disconnect();
  39050. this._soundPanner = null;
  39051. }
  39052. if (this._soundSource) {
  39053. this._soundSource.disconnect();
  39054. this._soundSource = null;
  39055. }
  39056. this._audioBuffer = null;
  39057. if (this._htmlAudioElement) {
  39058. this._htmlAudioElement.pause();
  39059. this._htmlAudioElement.src = "";
  39060. document.body.removeChild(this._htmlAudioElement);
  39061. }
  39062. if (this._connectedMesh) {
  39063. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39064. this._connectedMesh = null;
  39065. }
  39066. }
  39067. };
  39068. Sound.prototype.isReady = function () {
  39069. return this._isReadyToPlay;
  39070. };
  39071. Sound.prototype._soundLoaded = function (audioData) {
  39072. var _this = this;
  39073. this._isLoaded = true;
  39074. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  39075. _this._audioBuffer = buffer;
  39076. _this._isReadyToPlay = true;
  39077. if (_this.autoplay) {
  39078. _this.play();
  39079. }
  39080. if (_this._readyToPlayCallback) {
  39081. _this._readyToPlayCallback();
  39082. }
  39083. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  39084. };
  39085. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  39086. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39087. this._audioBuffer = audioBuffer;
  39088. this._isReadyToPlay = true;
  39089. }
  39090. };
  39091. Sound.prototype.updateOptions = function (options) {
  39092. if (options) {
  39093. this.loop = options.loop || this.loop;
  39094. this.maxDistance = options.maxDistance || this.maxDistance;
  39095. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  39096. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  39097. this.refDistance = options.refDistance || this.refDistance;
  39098. this.distanceModel = options.distanceModel || this.distanceModel;
  39099. this._playbackRate = options.playbackRate || this._playbackRate;
  39100. this._updateSpatialParameters();
  39101. if (this.isPlaying) {
  39102. if (this._streaming) {
  39103. this._htmlAudioElement.playbackRate = this._playbackRate;
  39104. }
  39105. else {
  39106. this._soundSource.playbackRate.value = this._playbackRate;
  39107. }
  39108. }
  39109. }
  39110. };
  39111. Sound.prototype._createSpatialParameters = function () {
  39112. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39113. if (this._scene.headphone) {
  39114. this._panningModel = "HRTF";
  39115. }
  39116. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  39117. this._updateSpatialParameters();
  39118. this._soundPanner.connect(this._ouputAudioNode);
  39119. this._inputAudioNode = this._soundPanner;
  39120. }
  39121. };
  39122. Sound.prototype._updateSpatialParameters = function () {
  39123. if (this.spatialSound) {
  39124. if (this.useCustomAttenuation) {
  39125. // Tricks to disable in a way embedded Web Audio attenuation
  39126. this._soundPanner.distanceModel = "linear";
  39127. this._soundPanner.maxDistance = Number.MAX_VALUE;
  39128. this._soundPanner.refDistance = 1;
  39129. this._soundPanner.rolloffFactor = 1;
  39130. this._soundPanner.panningModel = this._panningModel;
  39131. }
  39132. else {
  39133. this._soundPanner.distanceModel = this.distanceModel;
  39134. this._soundPanner.maxDistance = this.maxDistance;
  39135. this._soundPanner.refDistance = this.refDistance;
  39136. this._soundPanner.rolloffFactor = this.rolloffFactor;
  39137. this._soundPanner.panningModel = this._panningModel;
  39138. }
  39139. }
  39140. };
  39141. Sound.prototype.switchPanningModelToHRTF = function () {
  39142. this._panningModel = "HRTF";
  39143. this._switchPanningModel();
  39144. };
  39145. Sound.prototype.switchPanningModelToEqualPower = function () {
  39146. this._panningModel = "equalpower";
  39147. this._switchPanningModel();
  39148. };
  39149. Sound.prototype._switchPanningModel = function () {
  39150. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39151. this._soundPanner.panningModel = this._panningModel;
  39152. }
  39153. };
  39154. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39155. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39156. if (this._isOutputConnected) {
  39157. this._ouputAudioNode.disconnect();
  39158. }
  39159. this._ouputAudioNode.connect(soundTrackAudioNode);
  39160. this._isOutputConnected = true;
  39161. }
  39162. };
  39163. /**
  39164. * Transform this sound into a directional source
  39165. * @param coneInnerAngle Size of the inner cone in degree
  39166. * @param coneOuterAngle Size of the outer cone in degree
  39167. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39168. */
  39169. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39170. if (coneOuterAngle < coneInnerAngle) {
  39171. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39172. return;
  39173. }
  39174. this._coneInnerAngle = coneInnerAngle;
  39175. this._coneOuterAngle = coneOuterAngle;
  39176. this._coneOuterGain = coneOuterGain;
  39177. this._isDirectional = true;
  39178. if (this.isPlaying && this.loop) {
  39179. this.stop();
  39180. this.play();
  39181. }
  39182. };
  39183. Sound.prototype.setPosition = function (newPosition) {
  39184. this._position = newPosition;
  39185. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39186. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39187. }
  39188. };
  39189. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39190. this._localDirection = newLocalDirection;
  39191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39192. this._updateDirection();
  39193. }
  39194. };
  39195. Sound.prototype._updateDirection = function () {
  39196. var mat = this._connectedMesh.getWorldMatrix();
  39197. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39198. direction.normalize();
  39199. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39200. };
  39201. Sound.prototype.updateDistanceFromListener = function () {
  39202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39203. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39204. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39205. }
  39206. };
  39207. Sound.prototype.setAttenuationFunction = function (callback) {
  39208. this._customAttenuationFunction = callback;
  39209. };
  39210. /**
  39211. * Play the sound
  39212. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39213. * @param offset (optional) Start the sound setting it at a specific time
  39214. */
  39215. Sound.prototype.play = function (time, offset) {
  39216. var _this = this;
  39217. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39218. try {
  39219. if (this._startOffset < 0) {
  39220. time = -this._startOffset;
  39221. this._startOffset = 0;
  39222. }
  39223. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39224. if (!this._soundSource || !this._streamingSource) {
  39225. if (this.spatialSound) {
  39226. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39227. if (this._isDirectional) {
  39228. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39229. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39230. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39231. if (this._connectedMesh) {
  39232. this._updateDirection();
  39233. }
  39234. else {
  39235. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39236. }
  39237. }
  39238. }
  39239. }
  39240. if (this._streaming) {
  39241. if (!this._streamingSource) {
  39242. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39243. this._htmlAudioElement.onended = function () { _this._onended(); };
  39244. this._htmlAudioElement.playbackRate = this._playbackRate;
  39245. }
  39246. this._streamingSource.disconnect();
  39247. this._streamingSource.connect(this._inputAudioNode);
  39248. this._htmlAudioElement.play();
  39249. }
  39250. else {
  39251. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39252. this._soundSource.buffer = this._audioBuffer;
  39253. this._soundSource.connect(this._inputAudioNode);
  39254. this._soundSource.loop = this.loop;
  39255. this._soundSource.playbackRate.value = this._playbackRate;
  39256. this._soundSource.onended = function () { _this._onended(); };
  39257. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39258. }
  39259. this._startTime = startTime;
  39260. this.isPlaying = true;
  39261. this.isPaused = false;
  39262. }
  39263. catch (ex) {
  39264. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39265. }
  39266. }
  39267. };
  39268. Sound.prototype._onended = function () {
  39269. this.isPlaying = false;
  39270. if (this.onended) {
  39271. this.onended();
  39272. }
  39273. };
  39274. /**
  39275. * Stop the sound
  39276. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39277. */
  39278. Sound.prototype.stop = function (time) {
  39279. if (this.isPlaying) {
  39280. if (this._streaming) {
  39281. this._htmlAudioElement.pause();
  39282. // Test needed for Firefox or it will generate an Invalid State Error
  39283. if (this._htmlAudioElement.currentTime > 0) {
  39284. this._htmlAudioElement.currentTime = 0;
  39285. }
  39286. }
  39287. else {
  39288. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39289. this._soundSource.stop(stopTime);
  39290. this._soundSource.onended = null;
  39291. if (!this.isPaused) {
  39292. this._startOffset = 0;
  39293. }
  39294. }
  39295. this.isPlaying = false;
  39296. }
  39297. };
  39298. Sound.prototype.pause = function () {
  39299. if (this.isPlaying) {
  39300. this.isPaused = true;
  39301. if (this._streaming) {
  39302. this._htmlAudioElement.pause();
  39303. }
  39304. else {
  39305. this.stop(0);
  39306. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39307. }
  39308. }
  39309. };
  39310. Sound.prototype.setVolume = function (newVolume, time) {
  39311. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39312. if (time) {
  39313. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39314. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39315. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39316. }
  39317. else {
  39318. this._soundGain.gain.value = newVolume;
  39319. }
  39320. }
  39321. this._volume = newVolume;
  39322. };
  39323. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39324. this._playbackRate = newPlaybackRate;
  39325. if (this.isPlaying) {
  39326. if (this._streaming) {
  39327. this._htmlAudioElement.playbackRate = this._playbackRate;
  39328. }
  39329. else {
  39330. this._soundSource.playbackRate.value = this._playbackRate;
  39331. }
  39332. }
  39333. };
  39334. Sound.prototype.getVolume = function () {
  39335. return this._volume;
  39336. };
  39337. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39338. var _this = this;
  39339. if (this._connectedMesh) {
  39340. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39341. this._registerFunc = null;
  39342. }
  39343. this._connectedMesh = meshToConnectTo;
  39344. if (!this.spatialSound) {
  39345. this.spatialSound = true;
  39346. this._createSpatialParameters();
  39347. if (this.isPlaying && this.loop) {
  39348. this.stop();
  39349. this.play();
  39350. }
  39351. }
  39352. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39353. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39354. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39355. };
  39356. Sound.prototype.detachFromMesh = function () {
  39357. if (this._connectedMesh) {
  39358. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39359. this._registerFunc = null;
  39360. this._connectedMesh = null;
  39361. }
  39362. };
  39363. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39364. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39365. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39366. this._updateDirection();
  39367. }
  39368. };
  39369. Sound.prototype.clone = function () {
  39370. var _this = this;
  39371. if (!this._streaming) {
  39372. var setBufferAndRun = function () {
  39373. if (_this._isReadyToPlay) {
  39374. clonedSound._audioBuffer = _this.getAudioBuffer();
  39375. clonedSound._isReadyToPlay = true;
  39376. if (clonedSound.autoplay) {
  39377. clonedSound.play();
  39378. }
  39379. }
  39380. else {
  39381. window.setTimeout(setBufferAndRun, 300);
  39382. }
  39383. };
  39384. var currentOptions = {
  39385. autoplay: this.autoplay, loop: this.loop,
  39386. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39387. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39388. refDistance: this.refDistance, distanceModel: this.distanceModel
  39389. };
  39390. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39391. if (this.useCustomAttenuation) {
  39392. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39393. }
  39394. clonedSound.setPosition(this._position);
  39395. clonedSound.setPlaybackRate(this._playbackRate);
  39396. setBufferAndRun();
  39397. return clonedSound;
  39398. }
  39399. else {
  39400. return null;
  39401. }
  39402. };
  39403. Sound.prototype.getAudioBuffer = function () {
  39404. return this._audioBuffer;
  39405. };
  39406. Sound.prototype.serialize = function () {
  39407. var serializationObject = {
  39408. name: this.name,
  39409. url: this.name,
  39410. autoplay: this.autoplay,
  39411. loop: this.loop,
  39412. volume: this._volume,
  39413. spatialSound: this.spatialSound,
  39414. maxDistance: this.maxDistance,
  39415. rolloffFactor: this.rolloffFactor,
  39416. refDistance: this.refDistance,
  39417. distanceModel: this.distanceModel,
  39418. playbackRate: this._playbackRate,
  39419. panningModel: this._panningModel,
  39420. soundTrackId: this.soundTrackId
  39421. };
  39422. if (this.spatialSound) {
  39423. if (this._connectedMesh)
  39424. serializationObject.connectedMeshId = this._connectedMesh.id;
  39425. serializationObject.position = this._position.asArray();
  39426. serializationObject.refDistance = this.refDistance;
  39427. serializationObject.distanceModel = this.distanceModel;
  39428. serializationObject.isDirectional = this._isDirectional;
  39429. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39430. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39431. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39432. serializationObject.coneOuterGain = this._coneOuterGain;
  39433. }
  39434. return serializationObject;
  39435. };
  39436. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39437. var soundName = parsedSound.name;
  39438. var soundUrl;
  39439. if (parsedSound.url) {
  39440. soundUrl = rootUrl + parsedSound.url;
  39441. }
  39442. else {
  39443. soundUrl = rootUrl + soundName;
  39444. }
  39445. var options = {
  39446. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39447. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39448. rolloffFactor: parsedSound.rolloffFactor,
  39449. refDistance: parsedSound.refDistance,
  39450. distanceModel: parsedSound.distanceModel,
  39451. playbackRate: parsedSound.playbackRate
  39452. };
  39453. var newSound;
  39454. if (!sourceSound) {
  39455. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39456. scene._addPendingData(newSound);
  39457. }
  39458. else {
  39459. var setBufferAndRun = function () {
  39460. if (sourceSound._isReadyToPlay) {
  39461. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39462. newSound._isReadyToPlay = true;
  39463. if (newSound.autoplay) {
  39464. newSound.play();
  39465. }
  39466. }
  39467. else {
  39468. window.setTimeout(setBufferAndRun, 300);
  39469. }
  39470. };
  39471. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39472. setBufferAndRun();
  39473. }
  39474. if (parsedSound.position) {
  39475. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39476. newSound.setPosition(soundPosition);
  39477. }
  39478. if (parsedSound.isDirectional) {
  39479. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39480. if (parsedSound.localDirectionToMesh) {
  39481. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39482. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39483. }
  39484. }
  39485. if (parsedSound.connectedMeshId) {
  39486. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39487. if (connectedMesh) {
  39488. newSound.attachToMesh(connectedMesh);
  39489. }
  39490. }
  39491. return newSound;
  39492. };
  39493. return Sound;
  39494. }());
  39495. BABYLON.Sound = Sound;
  39496. })(BABYLON || (BABYLON = {}));
  39497. //# sourceMappingURL=babylon.sound.js.map
  39498. var BABYLON;
  39499. (function (BABYLON) {
  39500. var SoundTrack = (function () {
  39501. function SoundTrack(scene, options) {
  39502. this.id = -1;
  39503. this._isMainTrack = false;
  39504. this._isInitialized = false;
  39505. this._scene = scene;
  39506. this.soundCollection = new Array();
  39507. this._options = options;
  39508. if (!this._isMainTrack) {
  39509. this._scene.soundTracks.push(this);
  39510. this.id = this._scene.soundTracks.length - 1;
  39511. }
  39512. }
  39513. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39514. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39515. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39516. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39517. if (this._options) {
  39518. if (this._options.volume) {
  39519. this._outputAudioNode.gain.value = this._options.volume;
  39520. }
  39521. if (this._options.mainTrack) {
  39522. this._isMainTrack = this._options.mainTrack;
  39523. }
  39524. }
  39525. this._isInitialized = true;
  39526. }
  39527. };
  39528. SoundTrack.prototype.dispose = function () {
  39529. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39530. if (this._connectedAnalyser) {
  39531. this._connectedAnalyser.stopDebugCanvas();
  39532. }
  39533. while (this.soundCollection.length) {
  39534. this.soundCollection[0].dispose();
  39535. }
  39536. if (this._outputAudioNode) {
  39537. this._outputAudioNode.disconnect();
  39538. }
  39539. this._outputAudioNode = null;
  39540. }
  39541. };
  39542. SoundTrack.prototype.AddSound = function (sound) {
  39543. if (!this._isInitialized) {
  39544. this._initializeSoundTrackAudioGraph();
  39545. }
  39546. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39547. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39548. }
  39549. if (sound.soundTrackId) {
  39550. if (sound.soundTrackId === -1) {
  39551. this._scene.mainSoundTrack.RemoveSound(sound);
  39552. }
  39553. else {
  39554. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39555. }
  39556. }
  39557. this.soundCollection.push(sound);
  39558. sound.soundTrackId = this.id;
  39559. };
  39560. SoundTrack.prototype.RemoveSound = function (sound) {
  39561. var index = this.soundCollection.indexOf(sound);
  39562. if (index !== -1) {
  39563. this.soundCollection.splice(index, 1);
  39564. }
  39565. };
  39566. SoundTrack.prototype.setVolume = function (newVolume) {
  39567. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39568. this._outputAudioNode.gain.value = newVolume;
  39569. }
  39570. };
  39571. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39572. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39573. for (var i = 0; i < this.soundCollection.length; i++) {
  39574. this.soundCollection[i].switchPanningModelToHRTF();
  39575. }
  39576. }
  39577. };
  39578. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39579. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39580. for (var i = 0; i < this.soundCollection.length; i++) {
  39581. this.soundCollection[i].switchPanningModelToEqualPower();
  39582. }
  39583. }
  39584. };
  39585. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39586. if (this._connectedAnalyser) {
  39587. this._connectedAnalyser.stopDebugCanvas();
  39588. }
  39589. this._connectedAnalyser = analyser;
  39590. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39591. this._outputAudioNode.disconnect();
  39592. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39593. }
  39594. };
  39595. return SoundTrack;
  39596. }());
  39597. BABYLON.SoundTrack = SoundTrack;
  39598. })(BABYLON || (BABYLON = {}));
  39599. //# sourceMappingURL=babylon.soundtrack.js.map
  39600. var BABYLON;
  39601. (function (BABYLON) {
  39602. /**
  39603. * Special Glow Blur post process only blurring the alpha channel
  39604. * It enforces keeping the most luminous color in the color channel.
  39605. */
  39606. var GlowBlurPostProcess = (function (_super) {
  39607. __extends(GlowBlurPostProcess, _super);
  39608. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  39609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39610. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  39611. _this.direction = direction;
  39612. _this.blurWidth = blurWidth;
  39613. _this.onApplyObservable.add(function (effect) {
  39614. effect.setFloat2("screenSize", _this.width, _this.height);
  39615. effect.setVector2("direction", _this.direction);
  39616. effect.setFloat("blurWidth", _this.blurWidth);
  39617. });
  39618. return _this;
  39619. }
  39620. return GlowBlurPostProcess;
  39621. }(BABYLON.PostProcess));
  39622. /**
  39623. * The highlight layer Helps adding a glow effect around a mesh.
  39624. *
  39625. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  39626. * glowy meshes to your scene.
  39627. *
  39628. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  39629. */
  39630. var HighlightLayer = (function () {
  39631. /**
  39632. * Instantiates a new highlight Layer and references it to the scene..
  39633. * @param name The name of the layer
  39634. * @param scene The scene to use the layer in
  39635. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  39636. */
  39637. function HighlightLayer(name, scene, options) {
  39638. this._vertexBuffers = {};
  39639. this._mainTextureDesiredSize = { width: 0, height: 0 };
  39640. this._meshes = {};
  39641. this._maxSize = 0;
  39642. this._shouldRender = false;
  39643. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  39644. this._excludedMeshes = {};
  39645. /**
  39646. * Specifies whether or not the inner glow is ACTIVE in the layer.
  39647. */
  39648. this.innerGlow = true;
  39649. /**
  39650. * Specifies whether or not the outer glow is ACTIVE in the layer.
  39651. */
  39652. this.outerGlow = true;
  39653. /**
  39654. * Specifies wether the highlight layer is enabled or not.
  39655. */
  39656. this.isEnabled = true;
  39657. /**
  39658. * An event triggered when the highlight layer has been disposed.
  39659. * @type {BABYLON.Observable}
  39660. */
  39661. this.onDisposeObservable = new BABYLON.Observable();
  39662. /**
  39663. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  39664. * @type {BABYLON.Observable}
  39665. */
  39666. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  39667. /**
  39668. * An event triggered when the highlight layer is being blurred.
  39669. * @type {BABYLON.Observable}
  39670. */
  39671. this.onBeforeBlurObservable = new BABYLON.Observable();
  39672. /**
  39673. * An event triggered when the highlight layer has been blurred.
  39674. * @type {BABYLON.Observable}
  39675. */
  39676. this.onAfterBlurObservable = new BABYLON.Observable();
  39677. /**
  39678. * An event triggered when the glowing blurred texture is being merged in the scene.
  39679. * @type {BABYLON.Observable}
  39680. */
  39681. this.onBeforeComposeObservable = new BABYLON.Observable();
  39682. /**
  39683. * An event triggered when the glowing blurred texture has been merged in the scene.
  39684. * @type {BABYLON.Observable}
  39685. */
  39686. this.onAfterComposeObservable = new BABYLON.Observable();
  39687. /**
  39688. * An event triggered when the highlight layer changes its size.
  39689. * @type {BABYLON.Observable}
  39690. */
  39691. this.onSizeChangedObservable = new BABYLON.Observable();
  39692. this._scene = scene;
  39693. var engine = scene.getEngine();
  39694. this._engine = engine;
  39695. this._maxSize = this._engine.getCaps().maxTextureSize;
  39696. this._scene.highlightLayers.push(this);
  39697. // Warn on stencil.
  39698. if (!this._engine.isStencilEnable) {
  39699. 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 }");
  39700. }
  39701. // Adapt options
  39702. this._options = options || {
  39703. mainTextureRatio: 0.25,
  39704. blurTextureSizeRatio: 0.5,
  39705. blurHorizontalSize: 1,
  39706. blurVerticalSize: 1,
  39707. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  39708. };
  39709. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  39710. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  39711. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  39712. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  39713. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  39714. // VBO
  39715. var vertices = [];
  39716. vertices.push(1, 1);
  39717. vertices.push(-1, 1);
  39718. vertices.push(-1, -1);
  39719. vertices.push(1, -1);
  39720. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39721. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  39722. // Indices
  39723. var indices = [];
  39724. indices.push(0);
  39725. indices.push(1);
  39726. indices.push(2);
  39727. indices.push(0);
  39728. indices.push(2);
  39729. indices.push(3);
  39730. this._indexBuffer = engine.createIndexBuffer(indices);
  39731. // Effect
  39732. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  39733. // Render target
  39734. this.setMainTextureSize();
  39735. // Create Textures and post processes
  39736. this.createTextureAndPostProcesses();
  39737. }
  39738. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  39739. /**
  39740. * Gets the horizontal size of the blur.
  39741. */
  39742. get: function () {
  39743. return this._horizontalBlurPostprocess.blurWidth;
  39744. },
  39745. /**
  39746. * Specifies the horizontal size of the blur.
  39747. */
  39748. set: function (value) {
  39749. this._horizontalBlurPostprocess.blurWidth = value;
  39750. },
  39751. enumerable: true,
  39752. configurable: true
  39753. });
  39754. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  39755. /**
  39756. * Gets the vertical size of the blur.
  39757. */
  39758. get: function () {
  39759. return this._verticalBlurPostprocess.blurWidth;
  39760. },
  39761. /**
  39762. * Specifies the vertical size of the blur.
  39763. */
  39764. set: function (value) {
  39765. this._verticalBlurPostprocess.blurWidth = value;
  39766. },
  39767. enumerable: true,
  39768. configurable: true
  39769. });
  39770. Object.defineProperty(HighlightLayer.prototype, "camera", {
  39771. /**
  39772. * Gets the camera attached to the layer.
  39773. */
  39774. get: function () {
  39775. return this._options.camera;
  39776. },
  39777. enumerable: true,
  39778. configurable: true
  39779. });
  39780. /**
  39781. * Creates the render target textures and post processes used in the highlight layer.
  39782. */
  39783. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  39784. var _this = this;
  39785. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  39786. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  39787. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  39788. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  39789. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  39790. width: this._mainTextureDesiredSize.width,
  39791. height: this._mainTextureDesiredSize.height
  39792. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39793. this._mainTexture.activeCamera = this._options.camera;
  39794. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39795. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39796. this._mainTexture.anisotropicFilteringLevel = 1;
  39797. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39798. this._mainTexture.renderParticles = false;
  39799. this._mainTexture.renderList = null;
  39800. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  39801. width: blurTextureWidth,
  39802. height: blurTextureHeight
  39803. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39804. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39805. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39806. this._blurTexture.anisotropicFilteringLevel = 16;
  39807. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39808. this._blurTexture.renderParticles = false;
  39809. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39810. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  39811. effect.setTexture("textureSampler", _this._mainTexture);
  39812. });
  39813. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  39814. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39815. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39816. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39817. });
  39818. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39819. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39820. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39821. });
  39822. }
  39823. else {
  39824. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39825. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39826. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39827. });
  39828. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39829. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39830. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39831. });
  39832. }
  39833. this._mainTexture.onAfterUnbindObservable.add(function () {
  39834. _this.onBeforeBlurObservable.notifyObservers(_this);
  39835. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  39836. _this.onAfterBlurObservable.notifyObservers(_this);
  39837. });
  39838. // Custom render function
  39839. var renderSubMesh = function (subMesh) {
  39840. var mesh = subMesh.getRenderingMesh();
  39841. var scene = _this._scene;
  39842. var engine = scene.getEngine();
  39843. // Culling
  39844. engine.setState(subMesh.getMaterial().backFaceCulling);
  39845. // Managing instances
  39846. var batch = mesh._getInstancesRenderList(subMesh._id);
  39847. if (batch.mustReturn) {
  39848. return;
  39849. }
  39850. // Excluded Mesh
  39851. if (_this._excludedMeshes[mesh.uniqueId]) {
  39852. return;
  39853. }
  39854. ;
  39855. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  39856. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  39857. var material = subMesh.getMaterial();
  39858. var emissiveTexture = null;
  39859. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  39860. emissiveTexture = material.emissiveTexture;
  39861. }
  39862. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  39863. engine.enableEffect(_this._glowMapGenerationEffect);
  39864. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  39865. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  39866. if (highlightLayerMesh) {
  39867. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  39868. }
  39869. else {
  39870. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  39871. }
  39872. // Alpha test
  39873. if (material && material.needAlphaTesting()) {
  39874. var alphaTexture = material.getAlphaTestTexture();
  39875. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  39876. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39877. }
  39878. // Glow emissive only
  39879. if (emissiveTexture) {
  39880. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  39881. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  39882. }
  39883. // Bones
  39884. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39885. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39886. }
  39887. // Draw
  39888. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  39889. }
  39890. else {
  39891. // Need to reset refresh rate of the shadowMap
  39892. _this._mainTexture.resetRefreshCounter();
  39893. }
  39894. };
  39895. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  39896. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  39897. var index;
  39898. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39899. renderSubMesh(opaqueSubMeshes.data[index]);
  39900. }
  39901. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39902. renderSubMesh(alphaTestSubMeshes.data[index]);
  39903. }
  39904. for (index = 0; index < transparentSubMeshes.length; index++) {
  39905. renderSubMesh(transparentSubMeshes.data[index]);
  39906. }
  39907. };
  39908. this._mainTexture.onClearObservable.add(function (engine) {
  39909. engine.clear(HighlightLayer.neutralColor, true, true, true);
  39910. });
  39911. };
  39912. /**
  39913. * Checks for the readiness of the element composing the layer.
  39914. * @param subMesh the mesh to check for
  39915. * @param useInstances specify wether or not to use instances to render the mesh
  39916. * @param emissiveTexture the associated emissive texture used to generate the glow
  39917. * @return true if ready otherwise, false
  39918. */
  39919. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  39920. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  39921. return false;
  39922. }
  39923. var defines = [];
  39924. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39925. var mesh = subMesh.getMesh();
  39926. var material = subMesh.getMaterial();
  39927. var uv1 = false;
  39928. var uv2 = false;
  39929. // Alpha test
  39930. if (material && material.needAlphaTesting()) {
  39931. var alphaTexture = material.getAlphaTestTexture();
  39932. if (alphaTexture) {
  39933. defines.push("#define ALPHATEST");
  39934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39935. alphaTexture.coordinatesIndex === 1) {
  39936. defines.push("#define DIFFUSEUV2");
  39937. uv2 = true;
  39938. }
  39939. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39940. defines.push("#define DIFFUSEUV1");
  39941. uv1 = true;
  39942. }
  39943. }
  39944. }
  39945. // Emissive
  39946. if (emissiveTexture) {
  39947. defines.push("#define EMISSIVE");
  39948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39949. emissiveTexture.coordinatesIndex === 1) {
  39950. defines.push("#define EMISSIVEUV2");
  39951. uv2 = true;
  39952. }
  39953. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39954. defines.push("#define EMISSIVEUV1");
  39955. uv1 = true;
  39956. }
  39957. }
  39958. if (uv1) {
  39959. attribs.push(BABYLON.VertexBuffer.UVKind);
  39960. defines.push("#define UV1");
  39961. }
  39962. if (uv2) {
  39963. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39964. defines.push("#define UV2");
  39965. }
  39966. // Bones
  39967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39970. if (mesh.numBoneInfluencers > 4) {
  39971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39973. }
  39974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39975. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39976. }
  39977. else {
  39978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39979. }
  39980. // Instances
  39981. if (useInstances) {
  39982. defines.push("#define INSTANCES");
  39983. attribs.push("world0");
  39984. attribs.push("world1");
  39985. attribs.push("world2");
  39986. attribs.push("world3");
  39987. }
  39988. // Get correct effect
  39989. var join = defines.join("\n");
  39990. if (this._cachedDefines !== join) {
  39991. this._cachedDefines = join;
  39992. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  39993. }
  39994. return this._glowMapGenerationEffect.isReady();
  39995. };
  39996. /**
  39997. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  39998. */
  39999. HighlightLayer.prototype.render = function () {
  40000. var currentEffect = this._glowMapMergeEffect;
  40001. // Check
  40002. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  40003. return;
  40004. var engine = this._scene.getEngine();
  40005. this.onBeforeComposeObservable.notifyObservers(this);
  40006. // Render
  40007. engine.enableEffect(currentEffect);
  40008. engine.setState(false);
  40009. // Cache
  40010. var previousStencilBuffer = engine.getStencilBuffer();
  40011. var previousStencilFunction = engine.getStencilFunction();
  40012. var previousStencilMask = engine.getStencilMask();
  40013. var previousAlphaMode = engine.getAlphaMode();
  40014. // Texture
  40015. currentEffect.setTexture("textureSampler", this._blurTexture);
  40016. // VBOs
  40017. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40018. // Draw order
  40019. engine.setAlphaMode(this._options.alphaBlendingMode);
  40020. engine.setStencilMask(0x00);
  40021. engine.setStencilBuffer(true);
  40022. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  40023. if (this.outerGlow) {
  40024. currentEffect.setFloat("offset", 0);
  40025. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  40026. engine.draw(true, 0, 6);
  40027. }
  40028. if (this.innerGlow) {
  40029. currentEffect.setFloat("offset", 1);
  40030. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  40031. engine.draw(true, 0, 6);
  40032. }
  40033. // Restore Cache
  40034. engine.setStencilFunction(previousStencilFunction);
  40035. engine.setStencilMask(previousStencilMask);
  40036. engine.setAlphaMode(previousAlphaMode);
  40037. engine.setStencilBuffer(previousStencilBuffer);
  40038. this.onAfterComposeObservable.notifyObservers(this);
  40039. // Handle size changes.
  40040. var size = this._mainTexture.getSize();
  40041. this.setMainTextureSize();
  40042. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  40043. // Recreate RTT and post processes on size change.
  40044. this.onSizeChangedObservable.notifyObservers(this);
  40045. this.disposeTextureAndPostProcesses();
  40046. this.createTextureAndPostProcesses();
  40047. }
  40048. };
  40049. /**
  40050. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  40051. * @param mesh The mesh to exclude from the highlight layer
  40052. */
  40053. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  40054. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  40055. if (!meshExcluded) {
  40056. this._excludedMeshes[mesh.uniqueId] = {
  40057. mesh: mesh,
  40058. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  40059. mesh.getEngine().setStencilBuffer(false);
  40060. }),
  40061. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  40062. mesh.getEngine().setStencilBuffer(true);
  40063. }),
  40064. };
  40065. }
  40066. };
  40067. /**
  40068. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  40069. * @param mesh The mesh to highlight
  40070. */
  40071. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  40072. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  40073. if (meshExcluded) {
  40074. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  40075. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  40076. }
  40077. this._excludedMeshes[mesh.uniqueId] = undefined;
  40078. };
  40079. /**
  40080. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  40081. * @param mesh The mesh to highlight
  40082. * @param color The color of the highlight
  40083. * @param glowEmissiveOnly Extract the glow from the emissive texture
  40084. */
  40085. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  40086. var _this = this;
  40087. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  40088. var meshHighlight = this._meshes[mesh.uniqueId];
  40089. if (meshHighlight) {
  40090. meshHighlight.color = color;
  40091. }
  40092. else {
  40093. this._meshes[mesh.uniqueId] = {
  40094. mesh: mesh,
  40095. color: color,
  40096. // Lambda required for capture due to Observable this context
  40097. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  40098. if (_this._excludedMeshes[mesh.uniqueId]) {
  40099. _this.defaultStencilReference(mesh);
  40100. }
  40101. else {
  40102. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  40103. }
  40104. }),
  40105. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  40106. glowEmissiveOnly: glowEmissiveOnly
  40107. };
  40108. }
  40109. this._shouldRender = true;
  40110. };
  40111. /**
  40112. * Remove a mesh from the highlight layer in order to make it stop glowing.
  40113. * @param mesh The mesh to highlight
  40114. */
  40115. HighlightLayer.prototype.removeMesh = function (mesh) {
  40116. var meshHighlight = this._meshes[mesh.uniqueId];
  40117. if (meshHighlight) {
  40118. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40119. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40120. }
  40121. this._meshes[mesh.uniqueId] = undefined;
  40122. this._shouldRender = false;
  40123. for (var meshHighlightToCheck in this._meshes) {
  40124. if (meshHighlightToCheck) {
  40125. this._shouldRender = true;
  40126. break;
  40127. }
  40128. }
  40129. };
  40130. /**
  40131. * Returns true if the layer contains information to display, otherwise false.
  40132. */
  40133. HighlightLayer.prototype.shouldRender = function () {
  40134. return this.isEnabled && this._shouldRender;
  40135. };
  40136. /**
  40137. * Sets the main texture desired size which is the closest power of two
  40138. * of the engine canvas size.
  40139. */
  40140. HighlightLayer.prototype.setMainTextureSize = function () {
  40141. if (this._options.mainTextureFixedSize) {
  40142. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  40143. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  40144. }
  40145. else {
  40146. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  40147. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  40148. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  40149. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  40150. }
  40151. };
  40152. /**
  40153. * Force the stencil to the normal expected value for none glowing parts
  40154. */
  40155. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  40156. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  40157. };
  40158. /**
  40159. * Dispose only the render target textures and post process.
  40160. */
  40161. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  40162. this._blurTexture.dispose();
  40163. this._mainTexture.dispose();
  40164. this._downSamplePostprocess.dispose();
  40165. this._horizontalBlurPostprocess.dispose();
  40166. this._verticalBlurPostprocess.dispose();
  40167. };
  40168. /**
  40169. * Dispose the highlight layer and free resources.
  40170. */
  40171. HighlightLayer.prototype.dispose = function () {
  40172. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40173. if (vertexBuffer) {
  40174. vertexBuffer.dispose();
  40175. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40176. }
  40177. if (this._indexBuffer) {
  40178. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40179. this._indexBuffer = null;
  40180. }
  40181. // Clean textures and post processes
  40182. this.disposeTextureAndPostProcesses();
  40183. // Clean mesh references
  40184. for (var id in this._meshes) {
  40185. var meshHighlight = this._meshes[id];
  40186. if (meshHighlight && meshHighlight.mesh) {
  40187. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40188. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40189. }
  40190. }
  40191. this._meshes = null;
  40192. for (var id in this._excludedMeshes) {
  40193. var meshHighlight = this._excludedMeshes[id];
  40194. if (meshHighlight) {
  40195. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  40196. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  40197. }
  40198. }
  40199. this._excludedMeshes = null;
  40200. // Remove from scene
  40201. var index = this._scene.highlightLayers.indexOf(this, 0);
  40202. if (index > -1) {
  40203. this._scene.highlightLayers.splice(index, 1);
  40204. }
  40205. // Callback
  40206. this.onDisposeObservable.notifyObservers(this);
  40207. this.onDisposeObservable.clear();
  40208. this.onBeforeRenderMainTextureObservable.clear();
  40209. this.onBeforeBlurObservable.clear();
  40210. this.onBeforeComposeObservable.clear();
  40211. this.onAfterComposeObservable.clear();
  40212. this.onSizeChangedObservable.clear();
  40213. };
  40214. return HighlightLayer;
  40215. }());
  40216. /**
  40217. * The neutral color used during the preparation of the glow effect.
  40218. * This is black by default as the blend operation is a blend operation.
  40219. */
  40220. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  40221. /**
  40222. * Stencil value used for glowing meshes.
  40223. */
  40224. HighlightLayer.glowingMeshStencilReference = 0x02;
  40225. /**
  40226. * Stencil value used for the other meshes in the scene.
  40227. */
  40228. HighlightLayer.normalMeshStencilReference = 0x01;
  40229. BABYLON.HighlightLayer = HighlightLayer;
  40230. })(BABYLON || (BABYLON = {}));
  40231. //# sourceMappingURL=babylon.highlightlayer.js.map
  40232. var BABYLON;
  40233. (function (BABYLON) {
  40234. var SIMDVector3 = (function () {
  40235. function SIMDVector3() {
  40236. }
  40237. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  40238. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  40239. };
  40240. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  40241. var m = transformation.m;
  40242. var m0 = SIMD.Float32x4.load(m, 0);
  40243. var m1 = SIMD.Float32x4.load(m, 4);
  40244. var m2 = SIMD.Float32x4.load(m, 8);
  40245. var m3 = SIMD.Float32x4.load(m, 12);
  40246. 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));
  40247. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  40248. result.x = SIMD.Float32x4.extractLane(r, 0);
  40249. result.y = SIMD.Float32x4.extractLane(r, 1);
  40250. result.z = SIMD.Float32x4.extractLane(r, 2);
  40251. };
  40252. return SIMDVector3;
  40253. }());
  40254. var SIMDMatrix = (function () {
  40255. function SIMDMatrix() {
  40256. }
  40257. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  40258. var tm = this.m;
  40259. var om = other.m;
  40260. var m0 = SIMD.Float32x4.load(om, 0);
  40261. var m1 = SIMD.Float32x4.load(om, 4);
  40262. var m2 = SIMD.Float32x4.load(om, 8);
  40263. var m3 = SIMD.Float32x4.load(om, 12);
  40264. for (var i = 0; i < 16; i += 4) {
  40265. 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)))));
  40266. }
  40267. return this;
  40268. };
  40269. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  40270. var src = this.m;
  40271. var dest = other.m;
  40272. // Load the 4 rows
  40273. var src0 = SIMD.Float32x4.load(src, 0);
  40274. var src1 = SIMD.Float32x4.load(src, 4);
  40275. var src2 = SIMD.Float32x4.load(src, 8);
  40276. var src3 = SIMD.Float32x4.load(src, 12);
  40277. // Transpose the source matrix. Sort of. Not a true transpose operation
  40278. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  40279. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  40280. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  40281. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  40282. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  40283. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  40284. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  40285. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  40286. // This is a true transposition, but it will lead to an incorrect result
  40287. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  40288. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  40289. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40290. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40291. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  40292. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  40293. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40294. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40295. // ----
  40296. tmp1 = SIMD.Float32x4.mul(row2, row3);
  40297. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40298. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  40299. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  40300. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40301. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  40302. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  40303. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  40304. // ----
  40305. tmp1 = SIMD.Float32x4.mul(row1, row2);
  40306. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40307. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  40308. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  40309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40310. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  40311. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  40312. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  40313. // ----
  40314. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  40315. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40316. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  40317. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  40318. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  40319. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40320. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  40321. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  40322. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  40323. // ----
  40324. tmp1 = SIMD.Float32x4.mul(row0, row1);
  40325. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40326. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40327. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  40328. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40329. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40330. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  40331. // ----
  40332. tmp1 = SIMD.Float32x4.mul(row0, row3);
  40333. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40334. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  40335. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  40336. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40337. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  40338. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  40339. // ----
  40340. tmp1 = SIMD.Float32x4.mul(row0, row2);
  40341. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40342. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  40343. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  40344. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40345. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  40346. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  40347. // Compute determinant
  40348. var det = SIMD.Float32x4.mul(row0, minor0);
  40349. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  40350. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  40351. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  40352. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  40353. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  40354. // These shuffles aren't necessary if the faulty transposition is done
  40355. // up at the top of this function.
  40356. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  40357. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  40358. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  40359. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  40360. // Compute final values by multiplying with 1/det
  40361. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  40362. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  40363. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  40364. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  40365. return this;
  40366. };
  40367. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  40368. var out = result.m;
  40369. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  40370. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  40371. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  40372. // cc.kmVec3Subtract(f, pCenter, pEye);
  40373. var f = SIMD.Float32x4.sub(center, eye);
  40374. // cc.kmVec3Normalize(f, f);
  40375. var tmp = SIMD.Float32x4.mul(f, f);
  40376. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40377. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40378. // cc.kmVec3Assign(up, pUp);
  40379. // cc.kmVec3Normalize(up, up);
  40380. tmp = SIMD.Float32x4.mul(up, up);
  40381. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40382. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40383. // cc.kmVec3Cross(s, f, up);
  40384. 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)));
  40385. // cc.kmVec3Normalize(s, s);
  40386. tmp = SIMD.Float32x4.mul(s, s);
  40387. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40388. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40389. // cc.kmVec3Cross(u, s, f);
  40390. 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)));
  40391. // cc.kmVec3Normalize(s, s);
  40392. tmp = SIMD.Float32x4.mul(s, s);
  40393. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40394. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40395. var zero = SIMD.Float32x4.splat(0.0);
  40396. s = SIMD.Float32x4.neg(s);
  40397. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  40398. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  40399. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  40400. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  40401. 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);
  40402. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  40403. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  40404. 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)))));
  40405. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  40406. 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)))));
  40407. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  40408. 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)))));
  40409. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  40410. 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)))));
  40411. };
  40412. return SIMDMatrix;
  40413. }());
  40414. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  40415. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  40416. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  40417. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  40418. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  40419. var SIMDHelper = (function () {
  40420. function SIMDHelper() {
  40421. }
  40422. Object.defineProperty(SIMDHelper, "IsEnabled", {
  40423. get: function () {
  40424. return SIMDHelper._isEnabled;
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. SIMDHelper.DisableSIMD = function () {
  40430. // Replace functions
  40431. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  40432. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  40433. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  40434. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  40435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  40436. SIMDHelper._isEnabled = false;
  40437. };
  40438. SIMDHelper.EnableSIMD = function () {
  40439. if (self.SIMD === undefined) {
  40440. return;
  40441. }
  40442. // check if polyfills needed
  40443. if (!self.Math.fround) {
  40444. self.Math.fround = (function (array) { return function (x) {
  40445. return array[0] = x, array[0];
  40446. }; })(new Float32Array(1));
  40447. }
  40448. if (!self.Math.imul) {
  40449. self.Math.imul = function (a, b) {
  40450. var ah = (a >>> 16) & 0xffff;
  40451. var al = a & 0xffff;
  40452. var bh = (b >>> 16) & 0xffff;
  40453. var bl = b & 0xffff;
  40454. // the shift by 0 fixes the sign on the high part
  40455. // the final |0 converts the unsigned value into a signed value
  40456. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  40457. };
  40458. }
  40459. // Replace functions
  40460. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  40461. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  40462. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  40463. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  40464. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  40465. SIMDHelper._isEnabled = true;
  40466. };
  40467. return SIMDHelper;
  40468. }());
  40469. SIMDHelper._isEnabled = false;
  40470. BABYLON.SIMDHelper = SIMDHelper;
  40471. })(BABYLON || (BABYLON = {}));
  40472. //# sourceMappingURL=babylon.math.SIMD.js.map
  40473. var BABYLON;
  40474. (function (BABYLON) {
  40475. /**
  40476. * This class describe a rectangle that were added to the map.
  40477. * You have access to its coordinates either in pixel or normalized (UV)
  40478. */
  40479. var PackedRect = (function () {
  40480. function PackedRect(root, parent, pos, size) {
  40481. this._pos = pos;
  40482. this._size = size;
  40483. this._root = root;
  40484. this._parent = parent;
  40485. this._contentSize = null;
  40486. this._bottomNode = null;
  40487. this._leftNode = null;
  40488. this._initialSize = null;
  40489. this._rightNode = null;
  40490. }
  40491. Object.defineProperty(PackedRect.prototype, "pos", {
  40492. /**
  40493. * @returns the position of this node into the map
  40494. */
  40495. get: function () {
  40496. return this._pos;
  40497. },
  40498. enumerable: true,
  40499. configurable: true
  40500. });
  40501. Object.defineProperty(PackedRect.prototype, "contentSize", {
  40502. /**
  40503. * @returns the size of the rectangle this node handles
  40504. */
  40505. get: function () {
  40506. return this._contentSize;
  40507. },
  40508. enumerable: true,
  40509. configurable: true
  40510. });
  40511. Object.defineProperty(PackedRect.prototype, "UVs", {
  40512. /**
  40513. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  40514. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  40515. */
  40516. get: function () {
  40517. return this.getUVsForCustomSize(this._root._size);
  40518. },
  40519. enumerable: true,
  40520. configurable: true
  40521. });
  40522. /**
  40523. * 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.
  40524. * This method will return the UVs for this part by given the custom size of what you really use
  40525. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  40526. */
  40527. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  40528. var mainWidth = this._root._size.width;
  40529. var mainHeight = this._root._size.height;
  40530. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  40531. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  40532. var uvs = new Array();
  40533. uvs.push(topLeft);
  40534. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  40535. uvs.push(rightBottom);
  40536. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  40537. return uvs;
  40538. };
  40539. /**
  40540. * Free this rectangle from the map.
  40541. * Call this method when you no longer need the rectangle to be in the map.
  40542. */
  40543. PackedRect.prototype.freeContent = function () {
  40544. if (!this.contentSize) {
  40545. return;
  40546. }
  40547. this._contentSize = null;
  40548. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  40549. this.attemptDefrag();
  40550. };
  40551. Object.defineProperty(PackedRect.prototype, "isUsed", {
  40552. get: function () {
  40553. return this._contentSize != null || this._leftNode != null;
  40554. },
  40555. enumerable: true,
  40556. configurable: true
  40557. });
  40558. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  40559. var node = this.findNode(contentSize);
  40560. // Not enough space...
  40561. if (!node) {
  40562. return null;
  40563. }
  40564. node.splitNode(contentSize);
  40565. return node;
  40566. };
  40567. PackedRect.prototype.findNode = function (size) {
  40568. var resNode = null;
  40569. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  40570. if (this.isUsed) {
  40571. if (this._leftNode) {
  40572. resNode = this._leftNode.findNode(size);
  40573. }
  40574. if (!resNode && this._rightNode) {
  40575. resNode = this._rightNode.findNode(size);
  40576. }
  40577. if (!resNode && this._bottomNode) {
  40578. resNode = this._bottomNode.findNode(size);
  40579. }
  40580. }
  40581. else if (this._initialSize) {
  40582. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  40583. resNode = this;
  40584. }
  40585. else {
  40586. return null;
  40587. }
  40588. }
  40589. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  40590. resNode = this;
  40591. }
  40592. return resNode;
  40593. };
  40594. PackedRect.prototype.splitNode = function (contentSize) {
  40595. // 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)
  40596. if (!this._contentSize && this._initialSize) {
  40597. this._contentSize = contentSize.clone();
  40598. 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));
  40599. return this._leftNode.splitNode(contentSize);
  40600. }
  40601. else {
  40602. this._contentSize = contentSize.clone();
  40603. this._initialSize = contentSize.clone();
  40604. if (contentSize.width !== this._size.width) {
  40605. 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));
  40606. }
  40607. if (contentSize.height !== this._size.height) {
  40608. 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));
  40609. }
  40610. return this;
  40611. }
  40612. };
  40613. PackedRect.prototype.attemptDefrag = function () {
  40614. if (!this.isUsed && this.isRecursiveFree) {
  40615. this.clearNode();
  40616. if (this._parent) {
  40617. this._parent.attemptDefrag();
  40618. }
  40619. }
  40620. };
  40621. PackedRect.prototype.clearNode = function () {
  40622. this._initialSize = null;
  40623. this._rightNode = null;
  40624. this._bottomNode = null;
  40625. };
  40626. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  40627. get: function () {
  40628. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. PackedRect.prototype.evalFreeSize = function (size) {
  40634. var levelSize = 0;
  40635. if (!this.isUsed) {
  40636. if (this._initialSize) {
  40637. levelSize = this._initialSize.surface;
  40638. }
  40639. else {
  40640. levelSize = this._size.surface;
  40641. }
  40642. }
  40643. if (this._rightNode) {
  40644. levelSize += this._rightNode.evalFreeSize(0);
  40645. }
  40646. if (this._bottomNode) {
  40647. levelSize += this._bottomNode.evalFreeSize(0);
  40648. }
  40649. return levelSize + size;
  40650. };
  40651. return PackedRect;
  40652. }());
  40653. BABYLON.PackedRect = PackedRect;
  40654. /**
  40655. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  40656. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  40657. * 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.
  40658. */
  40659. var RectPackingMap = (function (_super) {
  40660. __extends(RectPackingMap, _super);
  40661. /**
  40662. * Create an instance of the object with a dimension using the given size
  40663. * @param size The dimension of the rectangle that will contain all the sub ones.
  40664. */
  40665. function RectPackingMap(size) {
  40666. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  40667. _this._root = _this;
  40668. return _this;
  40669. }
  40670. /**
  40671. * Add a rectangle, finding the best location to store it into the map
  40672. * @param size the dimension of the rectangle to store
  40673. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  40674. */
  40675. RectPackingMap.prototype.addRect = function (size) {
  40676. var node = this.findAndSplitNode(size);
  40677. return node;
  40678. };
  40679. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  40680. /**
  40681. * Return the current space free normalized between [0;1]
  40682. * @returns {}
  40683. */
  40684. get: function () {
  40685. var freeSize = 0;
  40686. freeSize = this.evalFreeSize(freeSize);
  40687. return freeSize / (this._size.width * this._size.height);
  40688. },
  40689. enumerable: true,
  40690. configurable: true
  40691. });
  40692. return RectPackingMap;
  40693. }(PackedRect));
  40694. BABYLON.RectPackingMap = RectPackingMap;
  40695. })(BABYLON || (BABYLON = {}));
  40696. //# sourceMappingURL=babylon.rectPackingMap.js.map
  40697. var BABYLON;
  40698. (function (BABYLON) {
  40699. var DynamicFloatArrayElementInfo = (function () {
  40700. function DynamicFloatArrayElementInfo() {
  40701. }
  40702. return DynamicFloatArrayElementInfo;
  40703. }());
  40704. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  40705. /**
  40706. * 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.
  40707. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  40708. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  40709. * 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.
  40710. * 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.
  40711. * 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".
  40712. */
  40713. var DynamicFloatArray = (function () {
  40714. /**
  40715. * Construct an instance of the dynamic float array
  40716. * @param stride size of one element in float (i.e. not bytes!)
  40717. * @param initialElementCount the number of available entries at construction
  40718. */
  40719. function DynamicFloatArray(stride, initialElementCount) {
  40720. this.compareValueOffset = null;
  40721. this.sortingAscending = true;
  40722. this._stride = stride;
  40723. this.buffer = new Float32Array(stride * initialElementCount);
  40724. this._lastUsed = 0;
  40725. this._firstFree = 0;
  40726. this._allEntries = new Array(initialElementCount);
  40727. this._freeEntries = new Array(initialElementCount);
  40728. for (var i = 0; i < initialElementCount; i++) {
  40729. var element = new DynamicFloatArrayElementInfo();
  40730. element.offset = i * stride;
  40731. this._allEntries[i] = element;
  40732. this._freeEntries[initialElementCount - i - 1] = element;
  40733. }
  40734. }
  40735. /**
  40736. * Allocate an element in the array.
  40737. * @return the element info instance that contains the offset into the main buffer of the element's location.
  40738. * Beware, this offset may change when you call pack()
  40739. */
  40740. DynamicFloatArray.prototype.allocElement = function () {
  40741. if (this._freeEntries.length === 0) {
  40742. this._growBuffer();
  40743. }
  40744. var el = this._freeEntries.pop();
  40745. this._lastUsed = Math.max(el.offset, this._lastUsed);
  40746. if (el.offset === this._firstFree) {
  40747. if (this._freeEntries.length > 0) {
  40748. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  40749. }
  40750. else {
  40751. this._firstFree += this._stride;
  40752. }
  40753. }
  40754. return el;
  40755. };
  40756. /**
  40757. * Free the element corresponding to the given element info
  40758. * @param elInfo the element that describe the allocated element
  40759. */
  40760. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  40761. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  40762. this._freeEntries.push(elInfo);
  40763. };
  40764. /**
  40765. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  40766. * 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().
  40767. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  40768. */
  40769. DynamicFloatArray.prototype.pack = function () {
  40770. // no free slot? no need to pack
  40771. if (this._freeEntries.length === 0) {
  40772. return this.buffer;
  40773. }
  40774. // If the buffer is already packed the last used will always be lower than the first free
  40775. // 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.
  40776. if (this._lastUsed < this._firstFree) {
  40777. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  40778. return elementsBuffer_1;
  40779. }
  40780. var s = this._stride;
  40781. // 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
  40782. var lastFree = new DynamicFloatArrayElementInfo();
  40783. lastFree.offset = this.totalElementCount * s;
  40784. this._freeEntries.push(lastFree);
  40785. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  40786. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40787. var firstFreeSlotOffset = sortedFree[0].offset;
  40788. var freeZoneSize = 1;
  40789. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  40790. var prevOffset = sortedFree[0].offset;
  40791. for (var i = 1; i < sortedFree.length; i++) {
  40792. // 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
  40793. if (firstFreeSlotOffset >= occupiedZoneSize) {
  40794. break;
  40795. }
  40796. var curFree = sortedFree[i];
  40797. var curOffset = curFree.offset;
  40798. // Compute the distance between this offset and the previous
  40799. var distance = curOffset - prevOffset;
  40800. // If the distance is the stride size, they are adjacent, it good, move to the next
  40801. if (distance === s) {
  40802. // Free zone is one element bigger
  40803. ++freeZoneSize;
  40804. // as we're about to iterate to the next, the cur becomes the previous...
  40805. prevOffset = curOffset;
  40806. continue;
  40807. }
  40808. // Distance is bigger, which means there's x element between the previous free and this one
  40809. var usedRange = (distance / s) - 1;
  40810. // Two cases the free zone is smaller than the data to move or bigger
  40811. // Copy what can fit in the free zone
  40812. var curMoveOffset = curOffset - s;
  40813. var copyCount = Math.min(freeZoneSize, usedRange);
  40814. for (var j = 0; j < copyCount; j++) {
  40815. var freeI = firstFreeSlotOffset / s;
  40816. var curI = curMoveOffset / s;
  40817. var moveEl = sortedAll[curI];
  40818. this._moveElement(moveEl, firstFreeSlotOffset);
  40819. var replacedEl = sortedAll[freeI];
  40820. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  40821. replacedEl.offset = curMoveOffset;
  40822. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  40823. sortedAll[freeI] = moveEl;
  40824. sortedAll[curI] = replacedEl;
  40825. curMoveOffset -= s;
  40826. firstFreeSlotOffset += s;
  40827. }
  40828. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  40829. if (freeZoneSize <= usedRange) {
  40830. firstFreeSlotOffset = curMoveOffset + s;
  40831. freeZoneSize = 1 + copyCount;
  40832. }
  40833. else {
  40834. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  40835. }
  40836. // as we're about to iterate to the next, the cur becomes the previous...
  40837. prevOffset = curOffset;
  40838. }
  40839. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  40840. this._lastUsed = firstFreeSlotOffset - s;
  40841. this._firstFree = firstFreeSlotOffset;
  40842. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  40843. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  40844. this._allEntries = sortedAll;
  40845. return elementsBuffer;
  40846. };
  40847. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  40848. for (var i = 0; i < this._stride; i++) {
  40849. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  40850. }
  40851. element.offset = destOffset;
  40852. };
  40853. DynamicFloatArray.prototype._growBuffer = function () {
  40854. // Allocate the new buffer with 50% more entries, copy the content of the current one
  40855. var newElCount = Math.floor(this.totalElementCount * 1.5);
  40856. var newBuffer = new Float32Array(newElCount * this._stride);
  40857. newBuffer.set(this.buffer);
  40858. var curCount = this.totalElementCount;
  40859. var addedCount = newElCount - this.totalElementCount;
  40860. for (var i = 0; i < addedCount; i++) {
  40861. var element = new DynamicFloatArrayElementInfo();
  40862. element.offset = (curCount + i) * this.stride;
  40863. this._allEntries.push(element);
  40864. this._freeEntries[addedCount - i - 1] = element;
  40865. }
  40866. this._firstFree = curCount * this.stride;
  40867. this.buffer = newBuffer;
  40868. };
  40869. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  40870. /**
  40871. * Get the total count of entries that can fit in the current buffer
  40872. * @returns the elements count
  40873. */
  40874. get: function () {
  40875. return this._allEntries.length;
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  40881. /**
  40882. * Get the count of free entries that can still be allocated without resizing the buffer
  40883. * @returns the free elements count
  40884. */
  40885. get: function () {
  40886. return this._freeEntries.length;
  40887. },
  40888. enumerable: true,
  40889. configurable: true
  40890. });
  40891. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  40892. /**
  40893. * Get the count of allocated elements
  40894. * @returns the allocated elements count
  40895. */
  40896. get: function () {
  40897. return this._allEntries.length - this._freeEntries.length;
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  40903. /**
  40904. * Return the size of one element in float
  40905. * @returns the size in float
  40906. */
  40907. get: function () {
  40908. return this._stride;
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. DynamicFloatArray.prototype.sort = function () {
  40914. var _this = this;
  40915. if (!this.compareValueOffset) {
  40916. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  40917. }
  40918. var count = this.usedElementCount;
  40919. // Do we have to (re)create the sort table?
  40920. if (!this._sortTable || this._sortTable.length < count) {
  40921. // 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...
  40922. var newCount = Math.min(this.totalElementCount, count * 2);
  40923. this._sortTable = new Array(newCount);
  40924. }
  40925. if (!this._sortedTable || this._sortedTable.length !== count) {
  40926. this._sortedTable = new Array(count);
  40927. }
  40928. // Because, you know...
  40929. this.pack();
  40930. //let stride = this.stride;
  40931. //for (let i = 0; i < count; i++) {
  40932. // let si = this._sortTable[i];
  40933. // if (!si) {
  40934. // si = new SortInfo();
  40935. // this._sortTable[i] = si;
  40936. // }
  40937. // si.entry = this._allEntries[i];
  40938. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  40939. // si.swapedOffset = null;
  40940. // this._sortedTable[i] = si;
  40941. //}
  40942. var curOffset = 0;
  40943. var stride = this.stride;
  40944. for (var i = 0; i < count; i++, curOffset += stride) {
  40945. var si = this._sortTable[i];
  40946. if (!si) {
  40947. si = new SortInfo();
  40948. this._sortTable[i] = si;
  40949. }
  40950. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  40951. si.offset = curOffset;
  40952. si.swapedOffset = null;
  40953. this._sortedTable[i] = si;
  40954. }
  40955. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  40956. if (this.sortingAscending) {
  40957. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  40958. }
  40959. else {
  40960. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  40961. }
  40962. var swapElements = function (src, dst) {
  40963. for (var i = 0; i < stride; i++) {
  40964. var tps = _this.buffer[dst + i];
  40965. _this.buffer[dst + i] = _this.buffer[src + i];
  40966. _this.buffer[src + i] = tps;
  40967. }
  40968. };
  40969. // 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:
  40970. // 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),
  40971. // and I still want something with a good algorithm complexity.
  40972. // 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,
  40973. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  40974. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  40975. // 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
  40976. // until we find a SortInfo object without a swapedOffset which means we got the right location
  40977. // 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
  40978. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  40979. for (var i = 0; i < count; i++) {
  40980. // Get the element to move
  40981. var sourceSI = this._sortedTable[i];
  40982. var destSI = this._sortTable[i];
  40983. var sourceOff = sourceSI.offset;
  40984. // If the source changed location, find the new one
  40985. if (sourceSI.swapedOffset) {
  40986. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  40987. var curSI = sourceSI;
  40988. while (curSI.swapedOffset) {
  40989. curSI = this._sortTable[curSI.swapedOffset / stride];
  40990. }
  40991. // Finally get the right location
  40992. sourceOff = curSI.offset;
  40993. }
  40994. // Tag the element being replaced with its new location
  40995. destSI.swapedOffset = sourceOff;
  40996. // Swap elements (only if needed)
  40997. if (sourceOff !== destSI.offset) {
  40998. swapElements(sourceOff, destSI.offset);
  40999. }
  41000. // Update the offset in the corresponding DFAE
  41001. //sourceSI.entry.offset = destSI.entry.offset;
  41002. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  41003. }
  41004. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  41005. return true;
  41006. };
  41007. return DynamicFloatArray;
  41008. }());
  41009. BABYLON.DynamicFloatArray = DynamicFloatArray;
  41010. var SortInfo = (function () {
  41011. function SortInfo() {
  41012. this.compareData = this.offset = this.swapedOffset = null;
  41013. }
  41014. return SortInfo;
  41015. }());
  41016. })(BABYLON || (BABYLON = {}));
  41017. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  41018. var BABYLON;
  41019. (function (BABYLON) {
  41020. var MapTexture = (function (_super) {
  41021. __extends(MapTexture, _super);
  41022. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  41023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41024. if (useMipMap === void 0) { useMipMap = false; }
  41025. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  41026. _this.name = name;
  41027. _this._size = size;
  41028. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41029. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41030. // Create the rectPackMap that will allocate portion of the texture
  41031. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  41032. // Create the texture that will store the content
  41033. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  41034. return _this;
  41035. }
  41036. /**
  41037. * Allocate a rectangle of a given size in the texture map
  41038. * @param size the size of the rectangle to allocation
  41039. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  41040. */
  41041. MapTexture.prototype.allocateRect = function (size) {
  41042. return this._rectPackingMap.addRect(size);
  41043. };
  41044. /**
  41045. * Free a given rectangle from the texture map
  41046. * @param rectInfo the instance corresponding to the rect to free.
  41047. */
  41048. MapTexture.prototype.freeRect = function (rectInfo) {
  41049. if (rectInfo) {
  41050. rectInfo.freeContent();
  41051. }
  41052. };
  41053. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  41054. /**
  41055. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  41056. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  41057. * @returns {}
  41058. */
  41059. get: function () {
  41060. return this._rectPackingMap.freeSpace;
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. /**
  41066. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  41067. * 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.
  41068. * Don't forget to call unbindTexture when you're done rendering
  41069. * @param rect the zone to render to
  41070. * @param clear true to clear the portion's color/depth data
  41071. */
  41072. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  41073. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  41074. };
  41075. /**
  41076. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  41077. * 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.
  41078. * Don't forget to call unbindTexture when you're done rendering
  41079. * @param pos the position into the texture
  41080. * @param size the portion to fit the clip space to
  41081. * @param clear true to clear the portion's color/depth data
  41082. */
  41083. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  41084. var engine = this.getScene().getEngine();
  41085. engine.bindFramebuffer(this._texture);
  41086. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  41087. if (clear) {
  41088. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  41089. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  41090. }
  41091. };
  41092. /**
  41093. * Unbind the texture map from the rendering engine.
  41094. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  41095. * @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.
  41096. */
  41097. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  41098. // Dump ?
  41099. if (dumpForDebug) {
  41100. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  41101. }
  41102. var engine = this.getScene().getEngine();
  41103. if (this._replacedViewport) {
  41104. engine.setViewport(this._replacedViewport);
  41105. this._replacedViewport = null;
  41106. }
  41107. engine.unBindFramebuffer(this._texture);
  41108. };
  41109. Object.defineProperty(MapTexture.prototype, "canRescale", {
  41110. get: function () {
  41111. return false;
  41112. },
  41113. enumerable: true,
  41114. configurable: true
  41115. });
  41116. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  41117. // Anyway, there's not much point to use this method for this kind of texture I guess
  41118. MapTexture.prototype.clone = function () {
  41119. return null;
  41120. };
  41121. return MapTexture;
  41122. }(BABYLON.Texture));
  41123. BABYLON.MapTexture = MapTexture;
  41124. })(BABYLON || (BABYLON = {}));
  41125. //# sourceMappingURL=babylon.mapTexture.js.map
  41126. var BABYLON;
  41127. (function (BABYLON) {
  41128. var ShaderMaterial = (function (_super) {
  41129. __extends(ShaderMaterial, _super);
  41130. function ShaderMaterial(name, scene, shaderPath, options) {
  41131. var _this = _super.call(this, name, scene) || this;
  41132. _this._textures = {};
  41133. _this._textureArrays = {};
  41134. _this._floats = {};
  41135. _this._floatsArrays = {};
  41136. _this._colors3 = {};
  41137. _this._colors4 = {};
  41138. _this._vectors2 = {};
  41139. _this._vectors3 = {};
  41140. _this._vectors4 = {};
  41141. _this._matrices = {};
  41142. _this._matrices3x3 = {};
  41143. _this._matrices2x2 = {};
  41144. _this._vectors3Arrays = {};
  41145. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41146. _this._shaderPath = shaderPath;
  41147. options.needAlphaBlending = options.needAlphaBlending || false;
  41148. options.needAlphaTesting = options.needAlphaTesting || false;
  41149. options.attributes = options.attributes || ["position", "normal", "uv"];
  41150. options.uniforms = options.uniforms || ["worldViewProjection"];
  41151. options.samplers = options.samplers || [];
  41152. options.defines = options.defines || [];
  41153. _this._options = options;
  41154. return _this;
  41155. }
  41156. ShaderMaterial.prototype.getClassName = function () {
  41157. return "ShaderMaterial";
  41158. };
  41159. ShaderMaterial.prototype.needAlphaBlending = function () {
  41160. return this._options.needAlphaBlending;
  41161. };
  41162. ShaderMaterial.prototype.needAlphaTesting = function () {
  41163. return this._options.needAlphaTesting;
  41164. };
  41165. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41166. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41167. this._options.uniforms.push(uniformName);
  41168. }
  41169. };
  41170. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41171. if (this._options.samplers.indexOf(name) === -1) {
  41172. this._options.samplers.push(name);
  41173. }
  41174. this._textures[name] = texture;
  41175. return this;
  41176. };
  41177. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41178. if (this._options.samplers.indexOf(name) === -1) {
  41179. this._options.samplers.push(name);
  41180. }
  41181. this._checkUniform(name);
  41182. this._textureArrays[name] = textures;
  41183. return this;
  41184. };
  41185. ShaderMaterial.prototype.setFloat = function (name, value) {
  41186. this._checkUniform(name);
  41187. this._floats[name] = value;
  41188. return this;
  41189. };
  41190. ShaderMaterial.prototype.setFloats = function (name, value) {
  41191. this._checkUniform(name);
  41192. this._floatsArrays[name] = value;
  41193. return this;
  41194. };
  41195. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41196. this._checkUniform(name);
  41197. this._colors3[name] = value;
  41198. return this;
  41199. };
  41200. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41201. this._checkUniform(name);
  41202. this._colors4[name] = value;
  41203. return this;
  41204. };
  41205. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41206. this._checkUniform(name);
  41207. this._vectors2[name] = value;
  41208. return this;
  41209. };
  41210. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41211. this._checkUniform(name);
  41212. this._vectors3[name] = value;
  41213. return this;
  41214. };
  41215. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41216. this._checkUniform(name);
  41217. this._vectors4[name] = value;
  41218. return this;
  41219. };
  41220. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41221. this._checkUniform(name);
  41222. this._matrices[name] = value;
  41223. return this;
  41224. };
  41225. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41226. this._checkUniform(name);
  41227. this._matrices3x3[name] = value;
  41228. return this;
  41229. };
  41230. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41231. this._checkUniform(name);
  41232. this._matrices2x2[name] = value;
  41233. return this;
  41234. };
  41235. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41236. this._checkUniform(name);
  41237. this._vectors3Arrays[name] = value;
  41238. return this;
  41239. };
  41240. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41241. if (!mesh) {
  41242. return true;
  41243. }
  41244. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41245. return false;
  41246. }
  41247. return false;
  41248. };
  41249. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41250. var scene = this.getScene();
  41251. var engine = scene.getEngine();
  41252. if (!this.checkReadyOnEveryCall) {
  41253. if (this._renderId === scene.getRenderId()) {
  41254. if (this._checkCache(scene, mesh, useInstances)) {
  41255. return true;
  41256. }
  41257. }
  41258. }
  41259. // Instances
  41260. var defines = [];
  41261. var fallbacks = new BABYLON.EffectFallbacks();
  41262. if (useInstances) {
  41263. defines.push("#define INSTANCES");
  41264. }
  41265. for (var index = 0; index < this._options.defines.length; index++) {
  41266. defines.push(this._options.defines[index]);
  41267. }
  41268. // Bones
  41269. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41270. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41271. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41272. fallbacks.addCPUSkinningFallback(0, mesh);
  41273. }
  41274. // Alpha test
  41275. if (engine.getAlphaTesting()) {
  41276. defines.push("#define ALPHATEST");
  41277. }
  41278. var previousEffect = this._effect;
  41279. var join = defines.join("\n");
  41280. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41281. if (!this._effect.isReady()) {
  41282. return false;
  41283. }
  41284. if (previousEffect !== this._effect) {
  41285. scene.resetCachedMaterial();
  41286. }
  41287. this._renderId = scene.getRenderId();
  41288. return true;
  41289. };
  41290. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41291. var scene = this.getScene();
  41292. if (this._options.uniforms.indexOf("world") !== -1) {
  41293. this._effect.setMatrix("world", world);
  41294. }
  41295. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41296. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41297. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41298. }
  41299. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41300. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41301. }
  41302. };
  41303. ShaderMaterial.prototype.bind = function (world, mesh) {
  41304. // Std values
  41305. this.bindOnlyWorldMatrix(world);
  41306. if (this.getScene().getCachedMaterial() !== this) {
  41307. if (this._options.uniforms.indexOf("view") !== -1) {
  41308. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41309. }
  41310. if (this._options.uniforms.indexOf("projection") !== -1) {
  41311. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41312. }
  41313. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41314. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41315. }
  41316. // Bones
  41317. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41318. var name;
  41319. // Texture
  41320. for (name in this._textures) {
  41321. this._effect.setTexture(name, this._textures[name]);
  41322. }
  41323. // Texture arrays
  41324. for (name in this._textureArrays) {
  41325. this._effect.setTextureArray(name, this._textureArrays[name]);
  41326. }
  41327. // Float
  41328. for (name in this._floats) {
  41329. this._effect.setFloat(name, this._floats[name]);
  41330. }
  41331. // Float s
  41332. for (name in this._floatsArrays) {
  41333. this._effect.setArray(name, this._floatsArrays[name]);
  41334. }
  41335. // Color3
  41336. for (name in this._colors3) {
  41337. this._effect.setColor3(name, this._colors3[name]);
  41338. }
  41339. // Color4
  41340. for (name in this._colors4) {
  41341. var color = this._colors4[name];
  41342. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41343. }
  41344. // Vector2
  41345. for (name in this._vectors2) {
  41346. this._effect.setVector2(name, this._vectors2[name]);
  41347. }
  41348. // Vector3
  41349. for (name in this._vectors3) {
  41350. this._effect.setVector3(name, this._vectors3[name]);
  41351. }
  41352. // Vector4
  41353. for (name in this._vectors4) {
  41354. this._effect.setVector4(name, this._vectors4[name]);
  41355. }
  41356. // Matrix
  41357. for (name in this._matrices) {
  41358. this._effect.setMatrix(name, this._matrices[name]);
  41359. }
  41360. // Matrix 3x3
  41361. for (name in this._matrices3x3) {
  41362. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41363. }
  41364. // Matrix 2x2
  41365. for (name in this._matrices2x2) {
  41366. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41367. }
  41368. // Vector3Array
  41369. for (name in this._vectors3Arrays) {
  41370. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41371. }
  41372. }
  41373. _super.prototype.bind.call(this, world, mesh);
  41374. };
  41375. ShaderMaterial.prototype.clone = function (name) {
  41376. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41377. return newShaderMaterial;
  41378. };
  41379. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41380. if (forceDisposeTextures) {
  41381. var name;
  41382. for (name in this._textures) {
  41383. this._textures[name].dispose();
  41384. }
  41385. for (name in this._textureArrays) {
  41386. var array = this._textureArrays[name];
  41387. for (var index = 0; index < array.length; index++) {
  41388. array[index].dispose();
  41389. }
  41390. }
  41391. }
  41392. this._textures = {};
  41393. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41394. };
  41395. ShaderMaterial.prototype.serialize = function () {
  41396. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41397. serializationObject.customType = "BABYLON.ShaderMaterial";
  41398. serializationObject.options = this._options;
  41399. serializationObject.shaderPath = this._shaderPath;
  41400. var name;
  41401. // Texture
  41402. serializationObject.textures = {};
  41403. for (name in this._textures) {
  41404. serializationObject.textures[name] = this._textures[name].serialize();
  41405. }
  41406. // Texture arrays
  41407. serializationObject.textureArrays = {};
  41408. for (name in this._textureArrays) {
  41409. serializationObject.textureArrays[name] = [];
  41410. var array = this._textureArrays[name];
  41411. for (var index = 0; index < array.length; index++) {
  41412. serializationObject.textureArrays[name].push(array[index].serialize());
  41413. }
  41414. }
  41415. // Float
  41416. serializationObject.floats = {};
  41417. for (name in this._floats) {
  41418. serializationObject.floats[name] = this._floats[name];
  41419. }
  41420. // Float s
  41421. serializationObject.floatArrays = {};
  41422. for (name in this._floatsArrays) {
  41423. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41424. }
  41425. // Color3
  41426. serializationObject.colors3 = {};
  41427. for (name in this._colors3) {
  41428. serializationObject.colors3[name] = this._colors3[name].asArray();
  41429. }
  41430. // Color4
  41431. serializationObject.colors4 = {};
  41432. for (name in this._colors4) {
  41433. serializationObject.colors4[name] = this._colors4[name].asArray();
  41434. }
  41435. // Vector2
  41436. serializationObject.vectors2 = {};
  41437. for (name in this._vectors2) {
  41438. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41439. }
  41440. // Vector3
  41441. serializationObject.vectors3 = {};
  41442. for (name in this._vectors3) {
  41443. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41444. }
  41445. // Vector4
  41446. serializationObject.vectors4 = {};
  41447. for (name in this._vectors4) {
  41448. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41449. }
  41450. // Matrix
  41451. serializationObject.matrices = {};
  41452. for (name in this._matrices) {
  41453. serializationObject.matrices[name] = this._matrices[name].asArray();
  41454. }
  41455. // Matrix 3x3
  41456. serializationObject.matrices3x3 = {};
  41457. for (name in this._matrices3x3) {
  41458. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41459. }
  41460. // Matrix 2x2
  41461. serializationObject.matrices2x2 = {};
  41462. for (name in this._matrices2x2) {
  41463. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41464. }
  41465. // Vector3Array
  41466. serializationObject.vectors3Arrays = {};
  41467. for (name in this._vectors3Arrays) {
  41468. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41469. }
  41470. return serializationObject;
  41471. };
  41472. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41473. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41474. var name;
  41475. // Texture
  41476. for (name in source.textures) {
  41477. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41478. }
  41479. // Texture arrays
  41480. for (name in source.textureArrays) {
  41481. var array = source.textureArrays[name];
  41482. var textureArray = new Array();
  41483. for (var index = 0; index < array.length; index++) {
  41484. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41485. }
  41486. material.setTextureArray(name, textureArray);
  41487. }
  41488. // Float
  41489. for (name in source.floats) {
  41490. material.setFloat(name, source.floats[name]);
  41491. }
  41492. // Float s
  41493. for (name in source.floatsArrays) {
  41494. material.setFloats(name, source.floatsArrays[name]);
  41495. }
  41496. // Color3
  41497. for (name in source.colors3) {
  41498. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41499. }
  41500. // Color4
  41501. for (name in source.colors4) {
  41502. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41503. }
  41504. // Vector2
  41505. for (name in source.vectors2) {
  41506. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41507. }
  41508. // Vector3
  41509. for (name in source.vectors3) {
  41510. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41511. }
  41512. // Vector4
  41513. for (name in source.vectors4) {
  41514. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41515. }
  41516. // Matrix
  41517. for (name in source.matrices) {
  41518. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41519. }
  41520. // Matrix 3x3
  41521. for (name in source.matrices3x3) {
  41522. material.setMatrix3x3(name, source.matrices3x3[name]);
  41523. }
  41524. // Matrix 2x2
  41525. for (name in source.matrices2x2) {
  41526. material.setMatrix2x2(name, source.matrices2x2[name]);
  41527. }
  41528. // Vector3Array
  41529. for (name in source.vectors3Arrays) {
  41530. material.setArray3(name, source.vectors3Arrays[name]);
  41531. }
  41532. return material;
  41533. };
  41534. return ShaderMaterial;
  41535. }(BABYLON.Material));
  41536. BABYLON.ShaderMaterial = ShaderMaterial;
  41537. })(BABYLON || (BABYLON = {}));
  41538. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41539. var BABYLON;
  41540. (function (BABYLON) {
  41541. var Internals;
  41542. (function (Internals) {
  41543. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41544. // All values and structures referenced from:
  41545. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41546. var DDS_MAGIC = 0x20534444;
  41547. 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;
  41548. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41549. 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;
  41550. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41551. function FourCCToInt32(value) {
  41552. return value.charCodeAt(0) +
  41553. (value.charCodeAt(1) << 8) +
  41554. (value.charCodeAt(2) << 16) +
  41555. (value.charCodeAt(3) << 24);
  41556. }
  41557. function Int32ToFourCC(value) {
  41558. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41559. }
  41560. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41561. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41562. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41563. var headerLengthInt = 31; // The header length in 32 bit ints
  41564. // Offsets into the header array
  41565. var off_magic = 0;
  41566. var off_size = 1;
  41567. var off_flags = 2;
  41568. var off_height = 3;
  41569. var off_width = 4;
  41570. var off_mipmapCount = 7;
  41571. var off_pfFlags = 20;
  41572. var off_pfFourCC = 21;
  41573. var off_RGBbpp = 22;
  41574. var off_RMask = 23;
  41575. var off_GMask = 24;
  41576. var off_BMask = 25;
  41577. var off_AMask = 26;
  41578. var off_caps1 = 27;
  41579. var off_caps2 = 28;
  41580. ;
  41581. var DDSTools = (function () {
  41582. function DDSTools() {
  41583. }
  41584. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41585. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41586. var mipmapCount = 1;
  41587. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41588. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41589. }
  41590. return {
  41591. width: header[off_width],
  41592. height: header[off_height],
  41593. mipmapCount: mipmapCount,
  41594. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41595. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41596. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41597. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41598. };
  41599. };
  41600. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41601. var byteArray = new Uint8Array(dataLength);
  41602. var srcData = new Uint8Array(arrayBuffer);
  41603. var index = 0;
  41604. for (var y = height - 1; y >= 0; y--) {
  41605. for (var x = 0; x < width; x++) {
  41606. var srcPos = dataOffset + (x + y * width) * 4;
  41607. byteArray[index + 2] = srcData[srcPos];
  41608. byteArray[index + 1] = srcData[srcPos + 1];
  41609. byteArray[index] = srcData[srcPos + 2];
  41610. byteArray[index + 3] = srcData[srcPos + 3];
  41611. index += 4;
  41612. }
  41613. }
  41614. return byteArray;
  41615. };
  41616. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41617. var byteArray = new Uint8Array(dataLength);
  41618. var srcData = new Uint8Array(arrayBuffer);
  41619. var index = 0;
  41620. for (var y = height - 1; y >= 0; y--) {
  41621. for (var x = 0; x < width; x++) {
  41622. var srcPos = dataOffset + (x + y * width) * 3;
  41623. byteArray[index + 2] = srcData[srcPos];
  41624. byteArray[index + 1] = srcData[srcPos + 1];
  41625. byteArray[index] = srcData[srcPos + 2];
  41626. index += 3;
  41627. }
  41628. }
  41629. return byteArray;
  41630. };
  41631. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41632. var byteArray = new Uint8Array(dataLength);
  41633. var srcData = new Uint8Array(arrayBuffer);
  41634. var index = 0;
  41635. for (var y = height - 1; y >= 0; y--) {
  41636. for (var x = 0; x < width; x++) {
  41637. var srcPos = dataOffset + (x + y * width);
  41638. byteArray[index] = srcData[srcPos];
  41639. index++;
  41640. }
  41641. }
  41642. return byteArray;
  41643. };
  41644. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41645. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41646. if (header[off_magic] != DDS_MAGIC) {
  41647. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41648. return;
  41649. }
  41650. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41651. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41652. return;
  41653. }
  41654. if (info.isFourCC) {
  41655. fourCC = header[off_pfFourCC];
  41656. switch (fourCC) {
  41657. case FOURCC_DXT1:
  41658. blockBytes = 8;
  41659. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41660. break;
  41661. case FOURCC_DXT3:
  41662. blockBytes = 16;
  41663. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41664. break;
  41665. case FOURCC_DXT5:
  41666. blockBytes = 16;
  41667. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41668. break;
  41669. default:
  41670. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41671. return;
  41672. }
  41673. }
  41674. mipmapCount = 1;
  41675. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41676. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41677. }
  41678. var bpp = header[off_RGBbpp];
  41679. for (var face = 0; face < faces; face++) {
  41680. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41681. width = header[off_width];
  41682. height = header[off_height];
  41683. dataOffset = header[off_size] + 4;
  41684. for (i = 0; i < mipmapCount; ++i) {
  41685. if (info.isRGB) {
  41686. if (bpp === 24) {
  41687. dataLength = width * height * 3;
  41688. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41689. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41690. }
  41691. else {
  41692. dataLength = width * height * 4;
  41693. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41694. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41695. }
  41696. }
  41697. else if (info.isLuminance) {
  41698. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41699. var unpaddedRowSize = width;
  41700. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41701. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41702. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41703. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41704. }
  41705. else {
  41706. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41707. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41708. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41709. }
  41710. dataOffset += dataLength;
  41711. width *= 0.5;
  41712. height *= 0.5;
  41713. width = Math.max(1.0, width);
  41714. height = Math.max(1.0, height);
  41715. }
  41716. }
  41717. };
  41718. return DDSTools;
  41719. }());
  41720. Internals.DDSTools = DDSTools;
  41721. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41722. })(BABYLON || (BABYLON = {}));
  41723. //# sourceMappingURL=babylon.tools.dds.js.map
  41724. var BABYLON;
  41725. (function (BABYLON) {
  41726. var Internals;
  41727. (function (Internals) {
  41728. /**
  41729. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41730. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41731. */
  41732. var KhronosTextureContainer = (function () {
  41733. /**
  41734. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41735. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41736. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41737. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41738. */
  41739. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41740. this.arrayBuffer = arrayBuffer;
  41741. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41742. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41743. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41744. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41745. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41746. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41747. BABYLON.Tools.Error("texture missing KTX identifier");
  41748. return;
  41749. }
  41750. // load the reset of the header in native 32 bit int
  41751. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41752. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41753. var oppositeEndianess = header[0] === 0x01020304;
  41754. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41755. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41756. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41757. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41758. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41759. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41760. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41761. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41762. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41763. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41764. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41765. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41766. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41767. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41768. if (this.glType !== 0) {
  41769. BABYLON.Tools.Error("only compressed formats currently supported");
  41770. return;
  41771. }
  41772. else {
  41773. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41774. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41775. }
  41776. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41777. BABYLON.Tools.Error("only 2D textures currently supported");
  41778. return;
  41779. }
  41780. if (this.numberOfArrayElements !== 0) {
  41781. BABYLON.Tools.Error("texture arrays not currently supported");
  41782. return;
  41783. }
  41784. if (this.numberOfFaces !== facesExpected) {
  41785. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41786. return;
  41787. }
  41788. // we now have a completely validated file, so could use existence of loadType as success
  41789. // would need to make this more elaborate & adjust checks above to support more than one load type
  41790. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41791. }
  41792. // not as fast hardware based, but will probably never need to use
  41793. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41794. return ((val & 0xFF) << 24)
  41795. | ((val & 0xFF00) << 8)
  41796. | ((val >> 8) & 0xFF00)
  41797. | ((val >> 24) & 0xFF);
  41798. };
  41799. /**
  41800. * It is assumed that the texture has already been created & is currently bound
  41801. */
  41802. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41803. switch (this.loadType) {
  41804. case KhronosTextureContainer.COMPRESSED_2D:
  41805. this._upload2DCompressedLevels(gl, loadMipmaps);
  41806. break;
  41807. case KhronosTextureContainer.TEX_2D:
  41808. case KhronosTextureContainer.COMPRESSED_3D:
  41809. case KhronosTextureContainer.TEX_3D:
  41810. }
  41811. };
  41812. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41813. // initialize width & height for level 1
  41814. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41815. var width = this.pixelWidth;
  41816. var height = this.pixelHeight;
  41817. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41818. for (var level = 0; level < mipmapCount; level++) {
  41819. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41820. for (var face = 0; face < this.numberOfFaces; face++) {
  41821. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41822. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41823. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41824. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41825. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41826. }
  41827. width = Math.max(1.0, width * 0.5);
  41828. height = Math.max(1.0, height * 0.5);
  41829. }
  41830. };
  41831. return KhronosTextureContainer;
  41832. }());
  41833. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41834. // load types
  41835. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41836. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41837. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41838. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41839. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41840. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41841. })(BABYLON || (BABYLON = {}));
  41842. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41843. var BABYLON;
  41844. (function (BABYLON) {
  41845. var CannonJSPlugin = (function () {
  41846. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41847. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41848. if (iterations === void 0) { iterations = 10; }
  41849. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41850. this.name = "CannonJSPlugin";
  41851. this._physicsMaterials = [];
  41852. this._fixedTimeStep = 1 / 60;
  41853. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41854. this._currentCollisionGroup = 2;
  41855. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41856. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41857. this._tmpPosition = BABYLON.Vector3.Zero();
  41858. this._tmpQuaternion = new BABYLON.Quaternion();
  41859. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41860. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41861. this._tmpUnityRotation = new BABYLON.Quaternion();
  41862. if (!this.isSupported()) {
  41863. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41864. return;
  41865. }
  41866. this.world = new CANNON.World();
  41867. this.world.broadphase = new CANNON.NaiveBroadphase();
  41868. this.world.solver.iterations = iterations;
  41869. }
  41870. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41871. this.world.gravity.copy(gravity);
  41872. };
  41873. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41874. this._fixedTimeStep = timeStep;
  41875. };
  41876. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41877. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41878. };
  41879. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41880. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41881. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41882. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41883. };
  41884. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41885. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41886. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41887. impostor.physicsBody.applyForce(impulse, worldPoint);
  41888. };
  41889. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41890. //parent-child relationship. Does this impostor has a parent impostor?
  41891. if (impostor.parent) {
  41892. if (impostor.physicsBody) {
  41893. this.removePhysicsBody(impostor);
  41894. //TODO is that needed?
  41895. impostor.forceUpdate();
  41896. }
  41897. return;
  41898. }
  41899. //should a new body be created for this impostor?
  41900. if (impostor.isBodyInitRequired()) {
  41901. var shape = this._createShape(impostor);
  41902. //unregister events, if body is being changed
  41903. var oldBody = impostor.physicsBody;
  41904. if (oldBody) {
  41905. this.removePhysicsBody(impostor);
  41906. }
  41907. //create the body and material
  41908. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41909. var bodyCreationObject = {
  41910. mass: impostor.getParam("mass"),
  41911. material: material
  41912. };
  41913. // A simple extend, in case native options were used.
  41914. var nativeOptions = impostor.getParam("nativeOptions");
  41915. for (var key in nativeOptions) {
  41916. if (nativeOptions.hasOwnProperty(key)) {
  41917. bodyCreationObject[key] = nativeOptions[key];
  41918. }
  41919. }
  41920. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41921. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41922. this.world.addEventListener("preStep", impostor.beforeStep);
  41923. this.world.addEventListener("postStep", impostor.afterStep);
  41924. impostor.physicsBody.addShape(shape);
  41925. this.world.add(impostor.physicsBody);
  41926. //try to keep the body moving in the right direction by taking old properties.
  41927. //Should be tested!
  41928. if (oldBody) {
  41929. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41930. impostor.physicsBody[param].copy(oldBody[param]);
  41931. });
  41932. }
  41933. this._processChildMeshes(impostor);
  41934. }
  41935. //now update the body's transformation
  41936. this._updatePhysicsBodyTransformation(impostor);
  41937. };
  41938. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41939. var _this = this;
  41940. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41941. if (meshChildren.length) {
  41942. var processMesh = function (localPosition, mesh) {
  41943. var childImpostor = mesh.getPhysicsImpostor();
  41944. if (childImpostor) {
  41945. var parent = childImpostor.parent;
  41946. if (parent !== mainImpostor) {
  41947. var localPosition = mesh.position;
  41948. if (childImpostor.physicsBody) {
  41949. _this.removePhysicsBody(childImpostor);
  41950. childImpostor.physicsBody = null;
  41951. }
  41952. childImpostor.parent = mainImpostor;
  41953. childImpostor.resetUpdateFlags();
  41954. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41955. //Add the mass of the children.
  41956. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41957. }
  41958. }
  41959. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41960. };
  41961. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41962. }
  41963. };
  41964. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41965. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41966. this.world.removeEventListener("preStep", impostor.beforeStep);
  41967. this.world.removeEventListener("postStep", impostor.afterStep);
  41968. this.world.remove(impostor.physicsBody);
  41969. };
  41970. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41971. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41972. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41973. if (!mainBody || !connectedBody) {
  41974. return;
  41975. }
  41976. var constraint;
  41977. var jointData = impostorJoint.joint.jointData;
  41978. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41979. var constraintData = {
  41980. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41981. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41982. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41983. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41984. maxForce: jointData.nativeParams.maxForce,
  41985. collideConnected: !!jointData.collision
  41986. };
  41987. switch (impostorJoint.joint.type) {
  41988. case BABYLON.PhysicsJoint.HingeJoint:
  41989. case BABYLON.PhysicsJoint.Hinge2Joint:
  41990. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41991. break;
  41992. case BABYLON.PhysicsJoint.DistanceJoint:
  41993. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41994. break;
  41995. case BABYLON.PhysicsJoint.SpringJoint:
  41996. var springData = jointData;
  41997. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41998. restLength: springData.length,
  41999. stiffness: springData.stiffness,
  42000. damping: springData.damping,
  42001. localAnchorA: constraintData.pivotA,
  42002. localAnchorB: constraintData.pivotB
  42003. });
  42004. break;
  42005. case BABYLON.PhysicsJoint.LockJoint:
  42006. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  42007. break;
  42008. case BABYLON.PhysicsJoint.PointToPointJoint:
  42009. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42010. default:
  42011. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  42012. break;
  42013. }
  42014. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  42015. constraint.collideConnected = !!jointData.collision;
  42016. impostorJoint.joint.physicsJoint = constraint;
  42017. //don't add spring as constraint, as it is not one.
  42018. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  42019. this.world.addConstraint(constraint);
  42020. }
  42021. else {
  42022. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  42023. constraint.applyForce();
  42024. });
  42025. }
  42026. };
  42027. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42028. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  42029. };
  42030. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  42031. var index;
  42032. var mat;
  42033. for (index = 0; index < this._physicsMaterials.length; index++) {
  42034. mat = this._physicsMaterials[index];
  42035. if (mat.friction === friction && mat.restitution === restitution) {
  42036. return mat;
  42037. }
  42038. }
  42039. var currentMat = new CANNON.Material(name);
  42040. currentMat.friction = friction;
  42041. currentMat.restitution = restitution;
  42042. this._physicsMaterials.push(currentMat);
  42043. return currentMat;
  42044. };
  42045. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  42046. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  42047. };
  42048. CannonJSPlugin.prototype._createShape = function (impostor) {
  42049. var object = impostor.object;
  42050. var returnValue;
  42051. var extendSize = impostor.getObjectExtendSize();
  42052. switch (impostor.type) {
  42053. case BABYLON.PhysicsEngine.SphereImpostor:
  42054. var radiusX = extendSize.x;
  42055. var radiusY = extendSize.y;
  42056. var radiusZ = extendSize.z;
  42057. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  42058. break;
  42059. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  42060. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42061. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  42062. break;
  42063. case BABYLON.PhysicsImpostor.BoxImpostor:
  42064. var box = extendSize.scale(0.5);
  42065. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  42066. break;
  42067. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42068. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  42069. returnValue = new CANNON.Plane();
  42070. break;
  42071. case BABYLON.PhysicsImpostor.MeshImpostor:
  42072. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  42073. var rawFaces = object.getIndices ? object.getIndices() : [];
  42074. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  42075. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  42076. break;
  42077. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  42078. returnValue = this._createHeightmap(object);
  42079. break;
  42080. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42081. returnValue = new CANNON.Particle();
  42082. break;
  42083. }
  42084. return returnValue;
  42085. };
  42086. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  42087. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42088. var matrix = [];
  42089. //For now pointDepth will not be used and will be automatically calculated.
  42090. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  42091. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  42092. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  42093. var elementSize = dim * 2 / arraySize;
  42094. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  42095. for (var i = 0; i < pos.length; i = i + 3) {
  42096. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  42097. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  42098. var y = pos[i + 1] + minY;
  42099. if (!matrix[x]) {
  42100. matrix[x] = [];
  42101. }
  42102. if (!matrix[x][z]) {
  42103. matrix[x][z] = y;
  42104. }
  42105. matrix[x][z] = Math.max(y, matrix[x][z]);
  42106. }
  42107. for (var x = 0; x <= arraySize; ++x) {
  42108. if (!matrix[x]) {
  42109. var loc = 1;
  42110. while (!matrix[(x + loc) % arraySize]) {
  42111. loc++;
  42112. }
  42113. matrix[x] = matrix[(x + loc) % arraySize].slice();
  42114. }
  42115. for (var z = 0; z <= arraySize; ++z) {
  42116. if (!matrix[x][z]) {
  42117. var loc = 1;
  42118. var newValue;
  42119. while (newValue === undefined) {
  42120. newValue = matrix[x][(z + loc++) % arraySize];
  42121. }
  42122. matrix[x][z] = newValue;
  42123. }
  42124. }
  42125. }
  42126. var shape = new CANNON.Heightfield(matrix, {
  42127. elementSize: elementSize
  42128. });
  42129. //For future reference, needed for body transformation
  42130. shape.minY = minY;
  42131. return shape;
  42132. };
  42133. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  42134. var object = impostor.object;
  42135. //make sure it is updated...
  42136. object.computeWorldMatrix && object.computeWorldMatrix(true);
  42137. // The delta between the mesh position and the mesh bounding box center
  42138. var center = impostor.getObjectCenter();
  42139. var extendSize = impostor.getObjectExtendSize();
  42140. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  42141. this._tmpPosition.copyFrom(center);
  42142. var quaternion = object.rotationQuaternion;
  42143. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  42144. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  42145. //-90 DEG in X, precalculated
  42146. quaternion = quaternion.multiply(this._minus90X);
  42147. //Invert! (Precalculated, 90 deg in X)
  42148. //No need to clone. this will never change.
  42149. impostor.setDeltaRotation(this._plus90X);
  42150. }
  42151. //If it is a heightfield, if should be centered.
  42152. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  42153. var mesh = object;
  42154. //calculate the correct body position:
  42155. var rotationQuaternion = mesh.rotationQuaternion;
  42156. mesh.rotationQuaternion = this._tmpUnityRotation;
  42157. mesh.computeWorldMatrix(true);
  42158. //get original center with no rotation
  42159. var c = center.clone();
  42160. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  42161. //rotation is back
  42162. mesh.rotationQuaternion = rotationQuaternion;
  42163. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42164. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42165. mesh.setPivotMatrix(p);
  42166. mesh.computeWorldMatrix(true);
  42167. //calculate the translation
  42168. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42169. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42170. //add it inverted to the delta
  42171. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42172. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42173. mesh.setPivotMatrix(oldPivot);
  42174. mesh.computeWorldMatrix(true);
  42175. }
  42176. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42177. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42178. this._tmpPosition.copyFrom(object.position);
  42179. }
  42180. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42181. //Now update the impostor object
  42182. impostor.physicsBody.position.copy(this._tmpPosition);
  42183. impostor.physicsBody.quaternion.copy(quaternion);
  42184. };
  42185. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42186. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42187. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42188. };
  42189. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42190. impostor.physicsBody.position.copy(newPosition);
  42191. impostor.physicsBody.quaternion.copy(newRotation);
  42192. };
  42193. CannonJSPlugin.prototype.isSupported = function () {
  42194. return window.CANNON !== undefined;
  42195. };
  42196. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42197. impostor.physicsBody.velocity.copy(velocity);
  42198. };
  42199. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42200. impostor.physicsBody.angularVelocity.copy(velocity);
  42201. };
  42202. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42203. var v = impostor.physicsBody.velocity;
  42204. if (!v)
  42205. return null;
  42206. return new BABYLON.Vector3(v.x, v.y, v.z);
  42207. };
  42208. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42209. var v = impostor.physicsBody.angularVelocity;
  42210. if (!v)
  42211. return null;
  42212. return new BABYLON.Vector3(v.x, v.y, v.z);
  42213. };
  42214. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42215. impostor.physicsBody.mass = mass;
  42216. impostor.physicsBody.updateMassProperties();
  42217. };
  42218. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42219. impostor.physicsBody.sleep();
  42220. };
  42221. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42222. impostor.physicsBody.wakeUp();
  42223. };
  42224. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42225. joint.physicsJoint.distance = maxDistance;
  42226. };
  42227. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42228. if (!motorIndex) {
  42229. joint.physicsJoint.enableMotor();
  42230. }
  42231. };
  42232. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42233. if (!motorIndex) {
  42234. joint.physicsJoint.disableMotor();
  42235. }
  42236. };
  42237. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42238. if (!motorIndex) {
  42239. joint.physicsJoint.enableMotor();
  42240. joint.physicsJoint.setMotorSpeed(speed);
  42241. if (maxForce) {
  42242. this.setLimit(joint, maxForce);
  42243. }
  42244. }
  42245. };
  42246. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42247. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42248. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42249. };
  42250. CannonJSPlugin.prototype.dispose = function () {
  42251. //nothing to do, actually.
  42252. };
  42253. return CannonJSPlugin;
  42254. }());
  42255. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42256. })(BABYLON || (BABYLON = {}));
  42257. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  42258. var BABYLON;
  42259. (function (BABYLON) {
  42260. var OimoJSPlugin = (function () {
  42261. function OimoJSPlugin(iterations) {
  42262. this.name = "OimoJSPlugin";
  42263. this._tmpImpostorsArray = [];
  42264. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42265. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42266. this.world.worldscale(1);
  42267. this.world.clear();
  42268. //making sure no stats are calculated
  42269. this.world.isNoStat = true;
  42270. }
  42271. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42272. this.world.gravity.copy(gravity);
  42273. };
  42274. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42275. this.world.timeStep = timeStep;
  42276. };
  42277. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42278. var _this = this;
  42279. impostors.forEach(function (impostor) {
  42280. impostor.beforeStep();
  42281. });
  42282. this.world.step();
  42283. impostors.forEach(function (impostor) {
  42284. impostor.afterStep();
  42285. //update the ordered impostors array
  42286. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42287. });
  42288. //check for collisions
  42289. var contact = this.world.contacts;
  42290. while (contact !== null) {
  42291. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42292. contact = contact.next;
  42293. continue;
  42294. }
  42295. //is this body colliding with any other? get the impostor
  42296. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42297. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42298. if (!mainImpostor || !collidingImpostor) {
  42299. contact = contact.next;
  42300. continue;
  42301. }
  42302. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42303. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42304. contact = contact.next;
  42305. }
  42306. };
  42307. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42308. var mass = impostor.physicsBody.massInfo.mass;
  42309. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42310. };
  42311. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42312. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42313. this.applyImpulse(impostor, force, contactPoint);
  42314. };
  42315. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42316. var _this = this;
  42317. //parent-child relationship. Does this impostor has a parent impostor?
  42318. if (impostor.parent) {
  42319. if (impostor.physicsBody) {
  42320. this.removePhysicsBody(impostor);
  42321. //TODO is that needed?
  42322. impostor.forceUpdate();
  42323. }
  42324. return;
  42325. }
  42326. if (impostor.isBodyInitRequired()) {
  42327. var bodyConfig = {
  42328. name: impostor.uniqueId,
  42329. //Oimo must have mass, also for static objects.
  42330. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42331. size: [],
  42332. type: [],
  42333. pos: [],
  42334. rot: [],
  42335. move: impostor.getParam("mass") !== 0,
  42336. //Supporting older versions of Oimo
  42337. world: this.world
  42338. };
  42339. var impostors = [impostor];
  42340. var addToArray = function (parent) {
  42341. if (!parent.getChildMeshes)
  42342. return;
  42343. parent.getChildMeshes().forEach(function (m) {
  42344. if (m.physicsImpostor) {
  42345. impostors.push(m.physicsImpostor);
  42346. m.physicsImpostor._init();
  42347. }
  42348. });
  42349. };
  42350. addToArray(impostor.object);
  42351. var checkWithEpsilon_1 = function (value) {
  42352. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42353. };
  42354. impostors.forEach(function (i) {
  42355. //get the correct bounding box
  42356. var oldQuaternion = i.object.rotationQuaternion;
  42357. var rot = new OIMO.Euler().setFromQuaternion({
  42358. x: impostor.object.rotationQuaternion.x,
  42359. y: impostor.object.rotationQuaternion.y,
  42360. z: impostor.object.rotationQuaternion.z,
  42361. s: impostor.object.rotationQuaternion.w
  42362. });
  42363. var extendSize = i.getObjectExtendSize();
  42364. if (i === impostor) {
  42365. var center = impostor.getObjectCenter();
  42366. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42367. //Can also use Array.prototype.push.apply
  42368. bodyConfig.pos.push(center.x);
  42369. bodyConfig.pos.push(center.y);
  42370. bodyConfig.pos.push(center.z);
  42371. //tmp solution
  42372. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42373. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42374. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42375. }
  42376. else {
  42377. bodyConfig.pos.push(i.object.position.x);
  42378. bodyConfig.pos.push(i.object.position.y);
  42379. bodyConfig.pos.push(i.object.position.z);
  42380. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42381. bodyConfig.rot.push(0);
  42382. bodyConfig.rot.push(0);
  42383. bodyConfig.rot.push(0);
  42384. }
  42385. // register mesh
  42386. switch (i.type) {
  42387. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42388. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42389. case BABYLON.PhysicsImpostor.SphereImpostor:
  42390. var radiusX = extendSize.x;
  42391. var radiusY = extendSize.y;
  42392. var radiusZ = extendSize.z;
  42393. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  42394. bodyConfig.type.push('sphere');
  42395. //due to the way oimo works with compounds, add 3 times
  42396. bodyConfig.size.push(size);
  42397. bodyConfig.size.push(size);
  42398. bodyConfig.size.push(size);
  42399. break;
  42400. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42401. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  42402. var sizeY = checkWithEpsilon_1(extendSize.y);
  42403. bodyConfig.type.push('cylinder');
  42404. bodyConfig.size.push(sizeX);
  42405. bodyConfig.size.push(sizeY);
  42406. //due to the way oimo works with compounds, add one more value.
  42407. bodyConfig.size.push(sizeY);
  42408. break;
  42409. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42410. case BABYLON.PhysicsImpostor.BoxImpostor:
  42411. default:
  42412. var sizeX = checkWithEpsilon_1(extendSize.x);
  42413. var sizeY = checkWithEpsilon_1(extendSize.y);
  42414. var sizeZ = checkWithEpsilon_1(extendSize.z);
  42415. bodyConfig.type.push('box');
  42416. bodyConfig.size.push(sizeX);
  42417. bodyConfig.size.push(sizeY);
  42418. bodyConfig.size.push(sizeZ);
  42419. break;
  42420. }
  42421. //actually not needed, but hey...
  42422. i.object.rotationQuaternion = oldQuaternion;
  42423. });
  42424. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42425. }
  42426. else {
  42427. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42428. }
  42429. impostor.setDeltaPosition(this._tmpPositionVector);
  42430. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42431. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42432. };
  42433. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42434. //impostor.physicsBody.dispose();
  42435. //Same as : (older oimo versions)
  42436. this.world.removeRigidBody(impostor.physicsBody);
  42437. };
  42438. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42439. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42440. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42441. if (!mainBody || !connectedBody) {
  42442. return;
  42443. }
  42444. var jointData = impostorJoint.joint.jointData;
  42445. var options = jointData.nativeParams || {};
  42446. var type;
  42447. var nativeJointData = {
  42448. body1: mainBody,
  42449. body2: connectedBody,
  42450. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42451. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42452. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42453. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42454. min: options.min,
  42455. max: options.max,
  42456. collision: options.collision || jointData.collision,
  42457. spring: options.spring,
  42458. //supporting older version of Oimo
  42459. world: this.world
  42460. };
  42461. switch (impostorJoint.joint.type) {
  42462. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42463. type = "jointBall";
  42464. break;
  42465. case BABYLON.PhysicsJoint.SpringJoint:
  42466. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42467. var springData = jointData;
  42468. nativeJointData.min = springData.length || nativeJointData.min;
  42469. //Max should also be set, just make sure it is at least min
  42470. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42471. case BABYLON.PhysicsJoint.DistanceJoint:
  42472. type = "jointDistance";
  42473. nativeJointData.max = jointData.maxDistance;
  42474. break;
  42475. case BABYLON.PhysicsJoint.PrismaticJoint:
  42476. type = "jointPrisme";
  42477. break;
  42478. case BABYLON.PhysicsJoint.SliderJoint:
  42479. type = "jointSlide";
  42480. break;
  42481. case BABYLON.PhysicsJoint.WheelJoint:
  42482. type = "jointWheel";
  42483. break;
  42484. case BABYLON.PhysicsJoint.HingeJoint:
  42485. default:
  42486. type = "jointHinge";
  42487. break;
  42488. }
  42489. nativeJointData.type = type;
  42490. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42491. };
  42492. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42493. //Bug in Oimo prevents us from disposing a joint in the playground
  42494. //joint.joint.physicsJoint.dispose();
  42495. //So we will bruteforce it!
  42496. try {
  42497. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42498. }
  42499. catch (e) {
  42500. BABYLON.Tools.Warn(e);
  42501. }
  42502. };
  42503. OimoJSPlugin.prototype.isSupported = function () {
  42504. return OIMO !== undefined;
  42505. };
  42506. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42507. if (!impostor.physicsBody.sleeping) {
  42508. //TODO check that
  42509. if (impostor.physicsBody.shapes.next) {
  42510. var parentShape = this._getLastShape(impostor.physicsBody);
  42511. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42512. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42513. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42514. }
  42515. else {
  42516. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42517. }
  42518. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42519. impostor.object.rotationQuaternion.normalize();
  42520. }
  42521. };
  42522. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42523. var body = impostor.physicsBody;
  42524. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42525. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42526. body.syncShapes();
  42527. body.awake();
  42528. };
  42529. OimoJSPlugin.prototype._getLastShape = function (body) {
  42530. var lastShape = body.shapes;
  42531. while (lastShape.next) {
  42532. lastShape = lastShape.next;
  42533. }
  42534. return lastShape;
  42535. };
  42536. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42537. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42538. };
  42539. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42540. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42541. };
  42542. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42543. var v = impostor.physicsBody.linearVelocity;
  42544. if (!v)
  42545. return null;
  42546. return new BABYLON.Vector3(v.x, v.y, v.z);
  42547. };
  42548. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42549. var v = impostor.physicsBody.angularVelocity;
  42550. if (!v)
  42551. return null;
  42552. return new BABYLON.Vector3(v.x, v.y, v.z);
  42553. };
  42554. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42555. var staticBody = mass === 0;
  42556. //this will actually set the body's density and not its mass.
  42557. //But this is how oimo treats the mass variable.
  42558. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42559. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42560. };
  42561. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42562. impostor.physicsBody.sleep();
  42563. };
  42564. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42565. impostor.physicsBody.awake();
  42566. };
  42567. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42568. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42569. if (minDistance !== void 0) {
  42570. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42571. }
  42572. };
  42573. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42574. //TODO separate rotational and transational motors.
  42575. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42576. if (motor) {
  42577. motor.setMotor(speed, maxForce);
  42578. }
  42579. };
  42580. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42581. //TODO separate rotational and transational motors.
  42582. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42583. if (motor) {
  42584. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42585. }
  42586. };
  42587. OimoJSPlugin.prototype.dispose = function () {
  42588. this.world.clear();
  42589. };
  42590. return OimoJSPlugin;
  42591. }());
  42592. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42593. })(BABYLON || (BABYLON = {}));
  42594. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42595. var BABYLON;
  42596. (function (BABYLON) {
  42597. var DisplayPassPostProcess = (function (_super) {
  42598. __extends(DisplayPassPostProcess, _super);
  42599. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42600. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42601. }
  42602. return DisplayPassPostProcess;
  42603. }(BABYLON.PostProcess));
  42604. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42605. })(BABYLON || (BABYLON = {}));
  42606. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42607. var BABYLON;
  42608. (function (BABYLON) {
  42609. var SimplificationSettings = (function () {
  42610. function SimplificationSettings(quality, distance, optimizeMesh) {
  42611. this.quality = quality;
  42612. this.distance = distance;
  42613. this.optimizeMesh = optimizeMesh;
  42614. }
  42615. return SimplificationSettings;
  42616. }());
  42617. BABYLON.SimplificationSettings = SimplificationSettings;
  42618. var SimplificationQueue = (function () {
  42619. function SimplificationQueue() {
  42620. this.running = false;
  42621. this._simplificationArray = [];
  42622. }
  42623. SimplificationQueue.prototype.addTask = function (task) {
  42624. this._simplificationArray.push(task);
  42625. };
  42626. SimplificationQueue.prototype.executeNext = function () {
  42627. var task = this._simplificationArray.pop();
  42628. if (task) {
  42629. this.running = true;
  42630. this.runSimplification(task);
  42631. }
  42632. else {
  42633. this.running = false;
  42634. }
  42635. };
  42636. SimplificationQueue.prototype.runSimplification = function (task) {
  42637. var _this = this;
  42638. if (task.parallelProcessing) {
  42639. //parallel simplifier
  42640. task.settings.forEach(function (setting) {
  42641. var simplifier = _this.getSimplifier(task);
  42642. simplifier.simplify(setting, function (newMesh) {
  42643. task.mesh.addLODLevel(setting.distance, newMesh);
  42644. newMesh.isVisible = true;
  42645. //check if it is the last
  42646. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42647. //all done, run the success callback.
  42648. task.successCallback();
  42649. }
  42650. _this.executeNext();
  42651. });
  42652. });
  42653. }
  42654. else {
  42655. //single simplifier.
  42656. var simplifier = this.getSimplifier(task);
  42657. var runDecimation = function (setting, callback) {
  42658. simplifier.simplify(setting, function (newMesh) {
  42659. task.mesh.addLODLevel(setting.distance, newMesh);
  42660. newMesh.isVisible = true;
  42661. //run the next quality level
  42662. callback();
  42663. });
  42664. };
  42665. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42666. runDecimation(task.settings[loop.index], function () {
  42667. loop.executeNext();
  42668. });
  42669. }, function () {
  42670. //execution ended, run the success callback.
  42671. if (task.successCallback) {
  42672. task.successCallback();
  42673. }
  42674. _this.executeNext();
  42675. });
  42676. }
  42677. };
  42678. SimplificationQueue.prototype.getSimplifier = function (task) {
  42679. switch (task.simplificationType) {
  42680. case SimplificationType.QUADRATIC:
  42681. default:
  42682. return new QuadraticErrorSimplification(task.mesh);
  42683. }
  42684. };
  42685. return SimplificationQueue;
  42686. }());
  42687. BABYLON.SimplificationQueue = SimplificationQueue;
  42688. /**
  42689. * The implemented types of simplification.
  42690. * At the moment only Quadratic Error Decimation is implemented.
  42691. */
  42692. var SimplificationType;
  42693. (function (SimplificationType) {
  42694. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42695. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42696. var DecimationTriangle = (function () {
  42697. function DecimationTriangle(vertices) {
  42698. this.vertices = vertices;
  42699. this.error = new Array(4);
  42700. this.deleted = false;
  42701. this.isDirty = false;
  42702. this.deletePending = false;
  42703. this.borderFactor = 0;
  42704. }
  42705. return DecimationTriangle;
  42706. }());
  42707. BABYLON.DecimationTriangle = DecimationTriangle;
  42708. var DecimationVertex = (function () {
  42709. function DecimationVertex(position, id) {
  42710. this.position = position;
  42711. this.id = id;
  42712. this.isBorder = true;
  42713. this.q = new QuadraticMatrix();
  42714. this.triangleCount = 0;
  42715. this.triangleStart = 0;
  42716. this.originalOffsets = [];
  42717. }
  42718. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42719. this.position.copyFrom(newPosition);
  42720. };
  42721. return DecimationVertex;
  42722. }());
  42723. BABYLON.DecimationVertex = DecimationVertex;
  42724. var QuadraticMatrix = (function () {
  42725. function QuadraticMatrix(data) {
  42726. this.data = new Array(10);
  42727. for (var i = 0; i < 10; ++i) {
  42728. if (data && data[i]) {
  42729. this.data[i] = data[i];
  42730. }
  42731. else {
  42732. this.data[i] = 0;
  42733. }
  42734. }
  42735. }
  42736. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42737. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42738. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42739. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42740. return det;
  42741. };
  42742. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42743. for (var i = 0; i < 10; ++i) {
  42744. this.data[i] += matrix.data[i];
  42745. }
  42746. };
  42747. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42748. for (var i = 0; i < 10; ++i) {
  42749. this.data[i] += data[i];
  42750. }
  42751. };
  42752. QuadraticMatrix.prototype.add = function (matrix) {
  42753. var m = new QuadraticMatrix();
  42754. for (var i = 0; i < 10; ++i) {
  42755. m.data[i] = this.data[i] + matrix.data[i];
  42756. }
  42757. return m;
  42758. };
  42759. QuadraticMatrix.FromData = function (a, b, c, d) {
  42760. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42761. };
  42762. //returning an array to avoid garbage collection
  42763. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42764. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42765. };
  42766. return QuadraticMatrix;
  42767. }());
  42768. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42769. var Reference = (function () {
  42770. function Reference(vertexId, triangleId) {
  42771. this.vertexId = vertexId;
  42772. this.triangleId = triangleId;
  42773. }
  42774. return Reference;
  42775. }());
  42776. BABYLON.Reference = Reference;
  42777. /**
  42778. * An implementation of the Quadratic Error simplification algorithm.
  42779. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42780. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42781. * @author RaananW
  42782. */
  42783. var QuadraticErrorSimplification = (function () {
  42784. function QuadraticErrorSimplification(_mesh) {
  42785. this._mesh = _mesh;
  42786. this.initialized = false;
  42787. this.syncIterations = 5000;
  42788. this.aggressiveness = 7;
  42789. this.decimationIterations = 100;
  42790. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42791. }
  42792. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42793. var _this = this;
  42794. this.initDecimatedMesh();
  42795. //iterating through the submeshes array, one after the other.
  42796. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42797. _this.initWithMesh(loop.index, function () {
  42798. _this.runDecimation(settings, loop.index, function () {
  42799. loop.executeNext();
  42800. });
  42801. }, settings.optimizeMesh);
  42802. }, function () {
  42803. setTimeout(function () {
  42804. successCallback(_this._reconstructedMesh);
  42805. }, 0);
  42806. });
  42807. };
  42808. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42809. var _this = this;
  42810. var gCount = 0;
  42811. triangle.vertices.forEach(function (vertex) {
  42812. var count = 0;
  42813. var vPos = vertex.position;
  42814. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42815. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42816. ++count;
  42817. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42818. ++count;
  42819. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42820. ++count;
  42821. if (count > 1) {
  42822. ++gCount;
  42823. }
  42824. ;
  42825. });
  42826. if (gCount > 1) {
  42827. console.log(triangle, gCount);
  42828. }
  42829. return gCount > 1;
  42830. };
  42831. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42832. var _this = this;
  42833. var targetCount = ~~(this.triangles.length * settings.quality);
  42834. var deletedTriangles = 0;
  42835. var triangleCount = this.triangles.length;
  42836. var iterationFunction = function (iteration, callback) {
  42837. setTimeout(function () {
  42838. if (iteration % 5 === 0) {
  42839. _this.updateMesh(iteration === 0);
  42840. }
  42841. for (var i = 0; i < _this.triangles.length; ++i) {
  42842. _this.triangles[i].isDirty = false;
  42843. }
  42844. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42845. var trianglesIterator = function (i) {
  42846. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42847. var t = _this.triangles[tIdx];
  42848. if (!t)
  42849. return;
  42850. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42851. return;
  42852. }
  42853. for (var j = 0; j < 3; ++j) {
  42854. if (t.error[j] < threshold) {
  42855. var deleted0 = [];
  42856. var deleted1 = [];
  42857. var v0 = t.vertices[j];
  42858. var v1 = t.vertices[(j + 1) % 3];
  42859. if (v0.isBorder || v1.isBorder)
  42860. continue;
  42861. var p = BABYLON.Vector3.Zero();
  42862. var n = BABYLON.Vector3.Zero();
  42863. var uv = BABYLON.Vector2.Zero();
  42864. var color = new BABYLON.Color4(0, 0, 0, 1);
  42865. _this.calculateError(v0, v1, p, n, uv, color);
  42866. var delTr = [];
  42867. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42868. continue;
  42869. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42870. continue;
  42871. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42872. continue;
  42873. var uniqueArray = [];
  42874. delTr.forEach(function (deletedT) {
  42875. if (uniqueArray.indexOf(deletedT) === -1) {
  42876. deletedT.deletePending = true;
  42877. uniqueArray.push(deletedT);
  42878. }
  42879. });
  42880. if (uniqueArray.length % 2 !== 0) {
  42881. continue;
  42882. }
  42883. v0.q = v1.q.add(v0.q);
  42884. v0.updatePosition(p);
  42885. var tStart = _this.references.length;
  42886. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42887. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42888. var tCount = _this.references.length - tStart;
  42889. if (tCount <= v0.triangleCount) {
  42890. if (tCount) {
  42891. for (var c = 0; c < tCount; c++) {
  42892. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42893. }
  42894. }
  42895. }
  42896. else {
  42897. v0.triangleStart = tStart;
  42898. }
  42899. v0.triangleCount = tCount;
  42900. break;
  42901. }
  42902. }
  42903. };
  42904. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42905. }, 0);
  42906. };
  42907. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42908. if (triangleCount - deletedTriangles <= targetCount)
  42909. loop.breakLoop();
  42910. else {
  42911. iterationFunction(loop.index, function () {
  42912. loop.executeNext();
  42913. });
  42914. }
  42915. }, function () {
  42916. setTimeout(function () {
  42917. //reconstruct this part of the mesh
  42918. _this.reconstructMesh(submeshIndex);
  42919. successCallback();
  42920. }, 0);
  42921. });
  42922. };
  42923. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42924. var _this = this;
  42925. this.vertices = [];
  42926. this.triangles = [];
  42927. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42928. var indices = this._mesh.getIndices();
  42929. var submesh = this._mesh.subMeshes[submeshIndex];
  42930. var findInVertices = function (positionToSearch) {
  42931. if (optimizeMesh) {
  42932. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42933. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42934. return _this.vertices[ii];
  42935. }
  42936. }
  42937. }
  42938. return null;
  42939. };
  42940. var vertexReferences = [];
  42941. var vertexInit = function (i) {
  42942. var offset = i + submesh.verticesStart;
  42943. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42944. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42945. vertex.originalOffsets.push(offset);
  42946. if (vertex.id === _this.vertices.length) {
  42947. _this.vertices.push(vertex);
  42948. }
  42949. vertexReferences.push(vertex.id);
  42950. };
  42951. //var totalVertices = mesh.getTotalVertices();
  42952. var totalVertices = submesh.verticesCount;
  42953. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42954. var indicesInit = function (i) {
  42955. var offset = (submesh.indexStart / 3) + i;
  42956. var pos = (offset * 3);
  42957. var i0 = indices[pos + 0];
  42958. var i1 = indices[pos + 1];
  42959. var i2 = indices[pos + 2];
  42960. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42961. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42962. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42963. var triangle = new DecimationTriangle([v0, v1, v2]);
  42964. triangle.originalOffset = pos;
  42965. _this.triangles.push(triangle);
  42966. };
  42967. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42968. _this.init(callback);
  42969. });
  42970. });
  42971. };
  42972. QuadraticErrorSimplification.prototype.init = function (callback) {
  42973. var _this = this;
  42974. var triangleInit1 = function (i) {
  42975. var t = _this.triangles[i];
  42976. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42977. for (var j = 0; j < 3; j++) {
  42978. 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))));
  42979. }
  42980. };
  42981. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42982. var triangleInit2 = function (i) {
  42983. var t = _this.triangles[i];
  42984. for (var j = 0; j < 3; ++j) {
  42985. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42986. }
  42987. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42988. };
  42989. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42990. _this.initialized = true;
  42991. callback();
  42992. });
  42993. });
  42994. };
  42995. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42996. var newTriangles = [];
  42997. var i;
  42998. for (i = 0; i < this.vertices.length; ++i) {
  42999. this.vertices[i].triangleCount = 0;
  43000. }
  43001. var t;
  43002. var j;
  43003. for (i = 0; i < this.triangles.length; ++i) {
  43004. if (!this.triangles[i].deleted) {
  43005. t = this.triangles[i];
  43006. for (j = 0; j < 3; ++j) {
  43007. t.vertices[j].triangleCount = 1;
  43008. }
  43009. newTriangles.push(t);
  43010. }
  43011. }
  43012. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  43013. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  43014. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  43015. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  43016. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43017. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43018. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43019. var vertexCount = 0;
  43020. for (i = 0; i < this.vertices.length; ++i) {
  43021. var vertex = this.vertices[i];
  43022. vertex.id = vertexCount;
  43023. if (vertex.triangleCount) {
  43024. vertex.originalOffsets.forEach(function (originalOffset) {
  43025. newPositionData.push(vertex.position.x);
  43026. newPositionData.push(vertex.position.y);
  43027. newPositionData.push(vertex.position.z);
  43028. newNormalData.push(normalData[originalOffset * 3]);
  43029. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  43030. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  43031. if (uvs && uvs.length) {
  43032. newUVsData.push(uvs[(originalOffset * 2)]);
  43033. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  43034. }
  43035. else if (colorsData && colorsData.length) {
  43036. newColorsData.push(colorsData[(originalOffset * 4)]);
  43037. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  43038. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  43039. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  43040. }
  43041. ++vertexCount;
  43042. });
  43043. }
  43044. }
  43045. var startingIndex = this._reconstructedMesh.getTotalIndices();
  43046. var startingVertex = this._reconstructedMesh.getTotalVertices();
  43047. var submeshesArray = this._reconstructedMesh.subMeshes;
  43048. this._reconstructedMesh.subMeshes = [];
  43049. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  43050. var originalIndices = this._mesh.getIndices();
  43051. for (i = 0; i < newTriangles.length; ++i) {
  43052. t = newTriangles[i]; //now get the new referencing point for each vertex
  43053. [0, 1, 2].forEach(function (idx) {
  43054. var id = originalIndices[t.originalOffset + idx];
  43055. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  43056. if (offset < 0)
  43057. offset = 0;
  43058. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  43059. });
  43060. }
  43061. //overwriting the old vertex buffers and indices.
  43062. this._reconstructedMesh.setIndices(newIndicesArray);
  43063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  43064. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  43065. if (newUVsData.length > 0)
  43066. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  43067. if (newColorsData.length > 0)
  43068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  43069. //create submesh
  43070. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  43071. if (submeshIndex > 0) {
  43072. this._reconstructedMesh.subMeshes = [];
  43073. submeshesArray.forEach(function (submesh) {
  43074. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  43075. });
  43076. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  43077. }
  43078. };
  43079. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  43080. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  43081. this._reconstructedMesh.material = this._mesh.material;
  43082. this._reconstructedMesh.parent = this._mesh.parent;
  43083. this._reconstructedMesh.isVisible = false;
  43084. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  43085. };
  43086. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  43087. for (var i = 0; i < vertex1.triangleCount; ++i) {
  43088. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  43089. if (t.deleted)
  43090. continue;
  43091. var s = this.references[vertex1.triangleStart + i].vertexId;
  43092. var v1 = t.vertices[(s + 1) % 3];
  43093. var v2 = t.vertices[(s + 2) % 3];
  43094. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  43095. deletedArray[i] = true;
  43096. delTr.push(t);
  43097. continue;
  43098. }
  43099. var d1 = v1.position.subtract(point);
  43100. d1 = d1.normalize();
  43101. var d2 = v2.position.subtract(point);
  43102. d2 = d2.normalize();
  43103. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  43104. return true;
  43105. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  43106. deletedArray[i] = false;
  43107. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  43108. return true;
  43109. }
  43110. return false;
  43111. };
  43112. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  43113. var newDeleted = deletedTriangles;
  43114. for (var i = 0; i < vertex.triangleCount; ++i) {
  43115. var ref = this.references[vertex.triangleStart + i];
  43116. var t = this.triangles[ref.triangleId];
  43117. if (t.deleted)
  43118. continue;
  43119. if (deletedArray[i] && t.deletePending) {
  43120. t.deleted = true;
  43121. newDeleted++;
  43122. continue;
  43123. }
  43124. t.vertices[ref.vertexId] = origVertex;
  43125. t.isDirty = true;
  43126. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  43127. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  43128. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  43129. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  43130. this.references.push(ref);
  43131. }
  43132. return newDeleted;
  43133. };
  43134. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  43135. for (var i = 0; i < this.vertices.length; ++i) {
  43136. var vCount = [];
  43137. var vId = [];
  43138. var v = this.vertices[i];
  43139. var j;
  43140. for (j = 0; j < v.triangleCount; ++j) {
  43141. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  43142. for (var ii = 0; ii < 3; ii++) {
  43143. var ofs = 0;
  43144. var vv = triangle.vertices[ii];
  43145. while (ofs < vCount.length) {
  43146. if (vId[ofs] === vv.id)
  43147. break;
  43148. ++ofs;
  43149. }
  43150. if (ofs === vCount.length) {
  43151. vCount.push(1);
  43152. vId.push(vv.id);
  43153. }
  43154. else {
  43155. vCount[ofs]++;
  43156. }
  43157. }
  43158. }
  43159. for (j = 0; j < vCount.length; ++j) {
  43160. if (vCount[j] === 1) {
  43161. this.vertices[vId[j]].isBorder = true;
  43162. }
  43163. else {
  43164. this.vertices[vId[j]].isBorder = false;
  43165. }
  43166. }
  43167. }
  43168. };
  43169. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43170. if (identifyBorders === void 0) { identifyBorders = false; }
  43171. var i;
  43172. if (!identifyBorders) {
  43173. var newTrianglesVector = [];
  43174. for (i = 0; i < this.triangles.length; ++i) {
  43175. if (!this.triangles[i].deleted) {
  43176. newTrianglesVector.push(this.triangles[i]);
  43177. }
  43178. }
  43179. this.triangles = newTrianglesVector;
  43180. }
  43181. for (i = 0; i < this.vertices.length; ++i) {
  43182. this.vertices[i].triangleCount = 0;
  43183. this.vertices[i].triangleStart = 0;
  43184. }
  43185. var t;
  43186. var j;
  43187. var v;
  43188. for (i = 0; i < this.triangles.length; ++i) {
  43189. t = this.triangles[i];
  43190. for (j = 0; j < 3; ++j) {
  43191. v = t.vertices[j];
  43192. v.triangleCount++;
  43193. }
  43194. }
  43195. var tStart = 0;
  43196. for (i = 0; i < this.vertices.length; ++i) {
  43197. this.vertices[i].triangleStart = tStart;
  43198. tStart += this.vertices[i].triangleCount;
  43199. this.vertices[i].triangleCount = 0;
  43200. }
  43201. var newReferences = new Array(this.triangles.length * 3);
  43202. for (i = 0; i < this.triangles.length; ++i) {
  43203. t = this.triangles[i];
  43204. for (j = 0; j < 3; ++j) {
  43205. v = t.vertices[j];
  43206. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43207. v.triangleCount++;
  43208. }
  43209. }
  43210. this.references = newReferences;
  43211. if (identifyBorders) {
  43212. this.identifyBorder();
  43213. }
  43214. };
  43215. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43216. var x = point.x;
  43217. var y = point.y;
  43218. var z = point.z;
  43219. 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
  43220. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43221. };
  43222. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43223. var q = vertex1.q.add(vertex2.q);
  43224. var border = vertex1.isBorder && vertex2.isBorder;
  43225. var error = 0;
  43226. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43227. if (qDet !== 0 && !border) {
  43228. if (!pointResult) {
  43229. pointResult = BABYLON.Vector3.Zero();
  43230. }
  43231. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43232. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43233. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43234. error = this.vertexError(q, pointResult);
  43235. }
  43236. else {
  43237. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43238. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43239. var error1 = this.vertexError(q, vertex1.position);
  43240. var error2 = this.vertexError(q, vertex2.position);
  43241. var error3 = this.vertexError(q, p3);
  43242. error = Math.min(error1, error2, error3);
  43243. if (error === error1) {
  43244. if (pointResult) {
  43245. pointResult.copyFrom(vertex1.position);
  43246. }
  43247. }
  43248. else if (error === error2) {
  43249. if (pointResult) {
  43250. pointResult.copyFrom(vertex2.position);
  43251. }
  43252. }
  43253. else {
  43254. if (pointResult) {
  43255. pointResult.copyFrom(p3);
  43256. }
  43257. }
  43258. }
  43259. return error;
  43260. };
  43261. return QuadraticErrorSimplification;
  43262. }());
  43263. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43264. })(BABYLON || (BABYLON = {}));
  43265. //# sourceMappingURL=babylon.meshSimplification.js.map
  43266. var BABYLON;
  43267. (function (BABYLON) {
  43268. var serializedGeometries = [];
  43269. var serializeGeometry = function (geometry, serializationGeometries) {
  43270. if (serializedGeometries[geometry.id]) {
  43271. return;
  43272. }
  43273. if (geometry.doNotSerialize) {
  43274. return;
  43275. }
  43276. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43277. serializationGeometries.boxes.push(geometry.serialize());
  43278. }
  43279. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43280. serializationGeometries.spheres.push(geometry.serialize());
  43281. }
  43282. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43283. serializationGeometries.cylinders.push(geometry.serialize());
  43284. }
  43285. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43286. serializationGeometries.toruses.push(geometry.serialize());
  43287. }
  43288. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43289. serializationGeometries.grounds.push(geometry.serialize());
  43290. }
  43291. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43292. serializationGeometries.planes.push(geometry.serialize());
  43293. }
  43294. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43295. serializationGeometries.torusKnots.push(geometry.serialize());
  43296. }
  43297. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43298. throw new Error("Unknown primitive type");
  43299. }
  43300. else {
  43301. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43302. }
  43303. serializedGeometries[geometry.id] = true;
  43304. };
  43305. var serializeMesh = function (mesh, serializationScene) {
  43306. var serializationObject = {};
  43307. serializationObject.name = mesh.name;
  43308. serializationObject.id = mesh.id;
  43309. if (BABYLON.Tags.HasTags(mesh)) {
  43310. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43311. }
  43312. serializationObject.position = mesh.position.asArray();
  43313. if (mesh.rotationQuaternion) {
  43314. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43315. }
  43316. else if (mesh.rotation) {
  43317. serializationObject.rotation = mesh.rotation.asArray();
  43318. }
  43319. serializationObject.scaling = mesh.scaling.asArray();
  43320. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43321. serializationObject.isEnabled = mesh.isEnabled();
  43322. serializationObject.isVisible = mesh.isVisible;
  43323. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43324. serializationObject.pickable = mesh.isPickable;
  43325. serializationObject.receiveShadows = mesh.receiveShadows;
  43326. serializationObject.billboardMode = mesh.billboardMode;
  43327. serializationObject.visibility = mesh.visibility;
  43328. serializationObject.checkCollisions = mesh.checkCollisions;
  43329. serializationObject.isBlocker = mesh.isBlocker;
  43330. // Parent
  43331. if (mesh.parent) {
  43332. serializationObject.parentId = mesh.parent.id;
  43333. }
  43334. // Geometry
  43335. var geometry = mesh._geometry;
  43336. if (geometry) {
  43337. var geometryId = geometry.id;
  43338. serializationObject.geometryId = geometryId;
  43339. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43340. // 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
  43341. serializeGeometry(geometry, serializationScene.geometries);
  43342. }
  43343. // SubMeshes
  43344. serializationObject.subMeshes = [];
  43345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43346. var subMesh = mesh.subMeshes[subIndex];
  43347. serializationObject.subMeshes.push({
  43348. materialIndex: subMesh.materialIndex,
  43349. verticesStart: subMesh.verticesStart,
  43350. verticesCount: subMesh.verticesCount,
  43351. indexStart: subMesh.indexStart,
  43352. indexCount: subMesh.indexCount
  43353. });
  43354. }
  43355. }
  43356. // Material
  43357. if (mesh.material) {
  43358. serializationObject.materialId = mesh.material.id;
  43359. }
  43360. else {
  43361. mesh.material = null;
  43362. }
  43363. // Skeleton
  43364. if (mesh.skeleton) {
  43365. serializationObject.skeletonId = mesh.skeleton.id;
  43366. }
  43367. // Physics
  43368. //TODO implement correct serialization for physics impostors.
  43369. if (mesh.getPhysicsImpostor()) {
  43370. serializationObject.physicsMass = mesh.getPhysicsMass();
  43371. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43372. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43373. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43374. }
  43375. // Metadata
  43376. if (mesh.metadata) {
  43377. serializationObject.metadata = mesh.metadata;
  43378. }
  43379. // Instances
  43380. serializationObject.instances = [];
  43381. for (var index = 0; index < mesh.instances.length; index++) {
  43382. var instance = mesh.instances[index];
  43383. var serializationInstance = {
  43384. name: instance.name,
  43385. position: instance.position.asArray(),
  43386. scaling: instance.scaling.asArray()
  43387. };
  43388. if (instance.rotationQuaternion) {
  43389. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43390. }
  43391. else if (instance.rotation) {
  43392. serializationInstance.rotation = instance.rotation.asArray();
  43393. }
  43394. serializationObject.instances.push(serializationInstance);
  43395. // Animations
  43396. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43397. serializationInstance.ranges = instance.serializeAnimationRanges();
  43398. }
  43399. // Animations
  43400. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43401. serializationObject.ranges = mesh.serializeAnimationRanges();
  43402. // Layer mask
  43403. serializationObject.layerMask = mesh.layerMask;
  43404. // Alpha
  43405. serializationObject.alphaIndex = mesh.alphaIndex;
  43406. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  43407. // Overlay
  43408. serializationObject.overlayAlpha = mesh.overlayAlpha;
  43409. serializationObject.overlayColor = mesh.overlayColor.asArray();
  43410. serializationObject.renderOverlay = mesh.renderOverlay;
  43411. // Fog
  43412. serializationObject.applyFog = mesh.applyFog;
  43413. // Action Manager
  43414. if (mesh.actionManager) {
  43415. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43416. }
  43417. return serializationObject;
  43418. };
  43419. var finalizeSingleMesh = function (mesh, serializationObject) {
  43420. //only works if the mesh is already loaded
  43421. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43422. //serialize material
  43423. if (mesh.material) {
  43424. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43425. serializationObject.materials = serializationObject.materials || [];
  43426. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43427. serializationObject.materials.push(mesh.material.serialize());
  43428. }
  43429. }
  43430. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43431. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43432. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43433. serializationObject.multiMaterials.push(mesh.material.serialize());
  43434. }
  43435. }
  43436. }
  43437. //serialize geometry
  43438. var geometry = mesh._geometry;
  43439. if (geometry) {
  43440. if (!serializationObject.geometries) {
  43441. serializationObject.geometries = {};
  43442. serializationObject.geometries.boxes = [];
  43443. serializationObject.geometries.spheres = [];
  43444. serializationObject.geometries.cylinders = [];
  43445. serializationObject.geometries.toruses = [];
  43446. serializationObject.geometries.grounds = [];
  43447. serializationObject.geometries.planes = [];
  43448. serializationObject.geometries.torusKnots = [];
  43449. serializationObject.geometries.vertexData = [];
  43450. }
  43451. serializeGeometry(geometry, serializationObject.geometries);
  43452. }
  43453. // Skeletons
  43454. if (mesh.skeleton) {
  43455. serializationObject.skeletons = serializationObject.skeletons || [];
  43456. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43457. }
  43458. //serialize the actual mesh
  43459. serializationObject.meshes = serializationObject.meshes || [];
  43460. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43461. }
  43462. };
  43463. var SceneSerializer = (function () {
  43464. function SceneSerializer() {
  43465. }
  43466. SceneSerializer.ClearCache = function () {
  43467. serializedGeometries = [];
  43468. };
  43469. SceneSerializer.Serialize = function (scene) {
  43470. var serializationObject = {};
  43471. // Scene
  43472. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43473. serializationObject.autoClear = scene.autoClear;
  43474. serializationObject.clearColor = scene.clearColor.asArray();
  43475. serializationObject.ambientColor = scene.ambientColor.asArray();
  43476. serializationObject.gravity = scene.gravity.asArray();
  43477. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43478. serializationObject.workerCollisions = scene.workerCollisions;
  43479. // Fog
  43480. if (scene.fogMode && scene.fogMode !== 0) {
  43481. serializationObject.fogMode = scene.fogMode;
  43482. serializationObject.fogColor = scene.fogColor.asArray();
  43483. serializationObject.fogStart = scene.fogStart;
  43484. serializationObject.fogEnd = scene.fogEnd;
  43485. serializationObject.fogDensity = scene.fogDensity;
  43486. }
  43487. //Physics
  43488. if (scene.isPhysicsEnabled()) {
  43489. serializationObject.physicsEnabled = true;
  43490. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43491. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43492. }
  43493. // Metadata
  43494. if (scene.metadata) {
  43495. serializationObject.metadata = scene.metadata;
  43496. }
  43497. // Lights
  43498. serializationObject.lights = [];
  43499. var index;
  43500. var light;
  43501. for (index = 0; index < scene.lights.length; index++) {
  43502. light = scene.lights[index];
  43503. if (!light.doNotSerialize) {
  43504. serializationObject.lights.push(light.serialize());
  43505. }
  43506. }
  43507. // Cameras
  43508. serializationObject.cameras = [];
  43509. for (index = 0; index < scene.cameras.length; index++) {
  43510. var camera = scene.cameras[index];
  43511. if (!camera.doNotSerialize) {
  43512. serializationObject.cameras.push(camera.serialize());
  43513. }
  43514. }
  43515. if (scene.activeCamera) {
  43516. serializationObject.activeCameraID = scene.activeCamera.id;
  43517. }
  43518. // Animations
  43519. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43520. // Materials
  43521. serializationObject.materials = [];
  43522. serializationObject.multiMaterials = [];
  43523. var material;
  43524. for (index = 0; index < scene.materials.length; index++) {
  43525. material = scene.materials[index];
  43526. if (!material.doNotSerialize) {
  43527. serializationObject.materials.push(material.serialize());
  43528. }
  43529. }
  43530. // MultiMaterials
  43531. serializationObject.multiMaterials = [];
  43532. for (index = 0; index < scene.multiMaterials.length; index++) {
  43533. var multiMaterial = scene.multiMaterials[index];
  43534. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43535. }
  43536. // Skeletons
  43537. serializationObject.skeletons = [];
  43538. for (index = 0; index < scene.skeletons.length; index++) {
  43539. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43540. }
  43541. // Geometries
  43542. serializationObject.geometries = {};
  43543. serializationObject.geometries.boxes = [];
  43544. serializationObject.geometries.spheres = [];
  43545. serializationObject.geometries.cylinders = [];
  43546. serializationObject.geometries.toruses = [];
  43547. serializationObject.geometries.grounds = [];
  43548. serializationObject.geometries.planes = [];
  43549. serializationObject.geometries.torusKnots = [];
  43550. serializationObject.geometries.vertexData = [];
  43551. serializedGeometries = [];
  43552. var geometries = scene.getGeometries();
  43553. for (index = 0; index < geometries.length; index++) {
  43554. var geometry = geometries[index];
  43555. if (geometry.isReady()) {
  43556. serializeGeometry(geometry, serializationObject.geometries);
  43557. }
  43558. }
  43559. // Meshes
  43560. serializationObject.meshes = [];
  43561. for (index = 0; index < scene.meshes.length; index++) {
  43562. var abstractMesh = scene.meshes[index];
  43563. if (abstractMesh instanceof BABYLON.Mesh) {
  43564. var mesh = abstractMesh;
  43565. if (!mesh.doNotSerialize) {
  43566. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43567. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43568. }
  43569. }
  43570. }
  43571. }
  43572. // Particles Systems
  43573. serializationObject.particleSystems = [];
  43574. for (index = 0; index < scene.particleSystems.length; index++) {
  43575. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43576. }
  43577. // Lens flares
  43578. serializationObject.lensFlareSystems = [];
  43579. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43580. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43581. }
  43582. // Shadows
  43583. serializationObject.shadowGenerators = [];
  43584. for (index = 0; index < scene.lights.length; index++) {
  43585. light = scene.lights[index];
  43586. var shadowGenerator = light.getShadowGenerator();
  43587. // Only support serialization for official generator so far.
  43588. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43589. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43590. }
  43591. }
  43592. // Action Manager
  43593. if (scene.actionManager) {
  43594. serializationObject.actions = scene.actionManager.serialize("scene");
  43595. }
  43596. // Audio
  43597. serializationObject.sounds = [];
  43598. for (index = 0; index < scene.soundTracks.length; index++) {
  43599. var soundtrack = scene.soundTracks[index];
  43600. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43601. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43602. }
  43603. }
  43604. return serializationObject;
  43605. };
  43606. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43607. if (withParents === void 0) { withParents = false; }
  43608. if (withChildren === void 0) { withChildren = false; }
  43609. var serializationObject = {};
  43610. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43611. if (withParents || withChildren) {
  43612. //deliberate for loop! not for each, appended should be processed as well.
  43613. for (var i = 0; i < toSerialize.length; ++i) {
  43614. if (withChildren) {
  43615. toSerialize[i].getDescendants().forEach(function (node) {
  43616. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43617. toSerialize.push(node);
  43618. }
  43619. });
  43620. }
  43621. //make sure the array doesn't contain the object already
  43622. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43623. toSerialize.push(toSerialize[i].parent);
  43624. }
  43625. }
  43626. }
  43627. toSerialize.forEach(function (mesh) {
  43628. finalizeSingleMesh(mesh, serializationObject);
  43629. });
  43630. return serializationObject;
  43631. };
  43632. return SceneSerializer;
  43633. }());
  43634. BABYLON.SceneSerializer = SceneSerializer;
  43635. })(BABYLON || (BABYLON = {}));
  43636. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43637. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43638. // Huge respect for a such great lib.
  43639. // Earcut license:
  43640. // Copyright (c) 2016, Mapbox
  43641. //
  43642. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43643. // with or without fee is hereby granted, provided that the above copyright notice
  43644. // and this permission notice appear in all copies.
  43645. //
  43646. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43647. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43648. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43649. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43650. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43651. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43652. // THIS SOFTWARE.
  43653. var Earcut;
  43654. (function (Earcut) {
  43655. /**
  43656. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43657. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43658. * @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).
  43659. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43660. */
  43661. function earcut(data, holeIndices, dim) {
  43662. dim = dim || 2;
  43663. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43664. if (!outerNode)
  43665. return triangles;
  43666. var minX, minY, maxX, maxY, x, y, size;
  43667. if (hasHoles)
  43668. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43669. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43670. if (data.length > 80 * dim) {
  43671. minX = maxX = data[0];
  43672. minY = maxY = data[1];
  43673. for (var i = dim; i < outerLen; i += dim) {
  43674. x = data[i];
  43675. y = data[i + 1];
  43676. if (x < minX)
  43677. minX = x;
  43678. if (y < minY)
  43679. minY = y;
  43680. if (x > maxX)
  43681. maxX = x;
  43682. if (y > maxY)
  43683. maxY = y;
  43684. }
  43685. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43686. size = Math.max(maxX - minX, maxY - minY);
  43687. }
  43688. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43689. return triangles;
  43690. }
  43691. Earcut.earcut = earcut;
  43692. // create a circular doubly linked list from polygon points in the specified winding order
  43693. function linkedList(data, start, end, dim, clockwise) {
  43694. var i, last;
  43695. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43696. for (i = start; i < end; i += dim)
  43697. last = insertNode(i, data[i], data[i + 1], last);
  43698. }
  43699. else {
  43700. for (i = end - dim; i >= start; i -= dim)
  43701. last = insertNode(i, data[i], data[i + 1], last);
  43702. }
  43703. if (last && equals(last, last.next)) {
  43704. removeNode(last);
  43705. last = last.next;
  43706. }
  43707. return last;
  43708. }
  43709. // eliminate colinear or duplicate points
  43710. function filterPoints(start, end) {
  43711. if (!start)
  43712. return start;
  43713. if (!end)
  43714. end = start;
  43715. var p = start, again;
  43716. do {
  43717. again = false;
  43718. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43719. removeNode(p);
  43720. p = end = p.prev;
  43721. if (p === p.next)
  43722. return null;
  43723. again = true;
  43724. }
  43725. else {
  43726. p = p.next;
  43727. }
  43728. } while (again || p !== end);
  43729. return end;
  43730. }
  43731. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43732. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43733. if (!ear)
  43734. return;
  43735. // interlink polygon nodes in z-order
  43736. if (!pass && size)
  43737. indexCurve(ear, minX, minY, size);
  43738. var stop = ear, prev, next;
  43739. // iterate through ears, slicing them one by one
  43740. while (ear.prev !== ear.next) {
  43741. prev = ear.prev;
  43742. next = ear.next;
  43743. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43744. // cut off the triangle
  43745. triangles.push(prev.i / dim);
  43746. triangles.push(ear.i / dim);
  43747. triangles.push(next.i / dim);
  43748. removeNode(ear);
  43749. // skipping the next vertice leads to less sliver triangles
  43750. ear = next.next;
  43751. stop = next.next;
  43752. continue;
  43753. }
  43754. ear = next;
  43755. // if we looped through the whole remaining polygon and can't find any more ears
  43756. if (ear === stop) {
  43757. // try filtering points and slicing again
  43758. if (!pass) {
  43759. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43760. }
  43761. else if (pass === 1) {
  43762. ear = cureLocalIntersections(ear, triangles, dim);
  43763. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43764. }
  43765. else if (pass === 2) {
  43766. splitEarcut(ear, triangles, dim, minX, minY, size);
  43767. }
  43768. break;
  43769. }
  43770. }
  43771. }
  43772. // check whether a polygon node forms a valid ear with adjacent nodes
  43773. function isEar(ear) {
  43774. var a = ear.prev, b = ear, c = ear.next;
  43775. if (area(a, b, c) >= 0)
  43776. return false; // reflex, can't be an ear
  43777. // now make sure we don't have other points inside the potential ear
  43778. var p = ear.next.next;
  43779. while (p !== ear.prev) {
  43780. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43781. area(p.prev, p, p.next) >= 0)
  43782. return false;
  43783. p = p.next;
  43784. }
  43785. return true;
  43786. }
  43787. function isEarHashed(ear, minX, minY, size) {
  43788. var a = ear.prev, b = ear, c = ear.next;
  43789. if (area(a, b, c) >= 0)
  43790. return false; // reflex, can't be an ear
  43791. // triangle bbox; min & max are calculated like this for speed
  43792. 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);
  43793. // z-order range for the current triangle bbox;
  43794. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43795. // first look for points inside the triangle in increasing z-order
  43796. var p = ear.nextZ;
  43797. while (p && p.z <= maxZ) {
  43798. if (p !== ear.prev &&
  43799. p !== ear.next &&
  43800. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43801. area(p.prev, p, p.next) >= 0)
  43802. return false;
  43803. p = p.nextZ;
  43804. }
  43805. // then look for points in decreasing z-order
  43806. p = ear.prevZ;
  43807. while (p && p.z >= minZ) {
  43808. if (p !== ear.prev &&
  43809. p !== ear.next &&
  43810. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43811. area(p.prev, p, p.next) >= 0)
  43812. return false;
  43813. p = p.prevZ;
  43814. }
  43815. return true;
  43816. }
  43817. // go through all polygon nodes and cure small local self-intersections
  43818. function cureLocalIntersections(start, triangles, dim) {
  43819. var p = start;
  43820. do {
  43821. var a = p.prev, b = p.next.next;
  43822. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43823. triangles.push(a.i / dim);
  43824. triangles.push(p.i / dim);
  43825. triangles.push(b.i / dim);
  43826. // remove two nodes involved
  43827. removeNode(p);
  43828. removeNode(p.next);
  43829. p = start = b;
  43830. }
  43831. p = p.next;
  43832. } while (p !== start);
  43833. return p;
  43834. }
  43835. // try splitting polygon into two and triangulate them independently
  43836. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43837. // look for a valid diagonal that divides the polygon into two
  43838. var a = start;
  43839. do {
  43840. var b = a.next.next;
  43841. while (b !== a.prev) {
  43842. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43843. // split the polygon in two by the diagonal
  43844. var c = splitPolygon(a, b);
  43845. // filter colinear points around the cuts
  43846. a = filterPoints(a, a.next);
  43847. c = filterPoints(c, c.next);
  43848. // run earcut on each half
  43849. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43850. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43851. return;
  43852. }
  43853. b = b.next;
  43854. }
  43855. a = a.next;
  43856. } while (a !== start);
  43857. }
  43858. // link every hole into the outer loop, producing a single-ring polygon without holes
  43859. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43860. var queue = [], i, len, start, end, list;
  43861. for (i = 0, len = holeIndices.length; i < len; i++) {
  43862. start = holeIndices[i] * dim;
  43863. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43864. list = linkedList(data, start, end, dim, false);
  43865. if (list === list.next)
  43866. list.steiner = true;
  43867. queue.push(getLeftmost(list));
  43868. }
  43869. queue.sort(compareX);
  43870. // process holes from left to right
  43871. for (i = 0; i < queue.length; i++) {
  43872. eliminateHole(queue[i], outerNode);
  43873. outerNode = filterPoints(outerNode, outerNode.next);
  43874. }
  43875. return outerNode;
  43876. }
  43877. function compareX(a, b) {
  43878. return a.x - b.x;
  43879. }
  43880. // find a bridge between vertices that connects hole with an outer ring and and link it
  43881. function eliminateHole(hole, outerNode) {
  43882. outerNode = findHoleBridge(hole, outerNode);
  43883. if (outerNode) {
  43884. var b = splitPolygon(outerNode, hole);
  43885. filterPoints(b, b.next);
  43886. }
  43887. }
  43888. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43889. function findHoleBridge(hole, outerNode) {
  43890. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43891. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43892. // segment's endpoint with lesser x will be potential connection point
  43893. do {
  43894. if (hy <= p.y && hy >= p.next.y) {
  43895. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43896. if (x <= hx && x > qx) {
  43897. qx = x;
  43898. if (x === hx) {
  43899. if (hy === p.y)
  43900. return p;
  43901. if (hy === p.next.y)
  43902. return p.next;
  43903. }
  43904. m = p.x < p.next.x ? p : p.next;
  43905. }
  43906. }
  43907. p = p.next;
  43908. } while (p !== outerNode);
  43909. if (!m)
  43910. return null;
  43911. if (hx === qx)
  43912. return m.prev; // hole touches outer segment; pick lower endpoint
  43913. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43914. // if there are no points found, we have a valid connection;
  43915. // otherwise choose the point of the minimum angle with the ray as connection point
  43916. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43917. p = m.next;
  43918. while (p !== stop) {
  43919. if (hx >= p.x &&
  43920. p.x >= mx &&
  43921. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43922. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43923. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43924. m = p;
  43925. tanMin = tan;
  43926. }
  43927. }
  43928. p = p.next;
  43929. }
  43930. return m;
  43931. }
  43932. // interlink polygon nodes in z-order
  43933. function indexCurve(start, minX, minY, size) {
  43934. var p = start;
  43935. do {
  43936. if (p.z === null)
  43937. p.z = zOrder(p.x, p.y, minX, minY, size);
  43938. p.prevZ = p.prev;
  43939. p.nextZ = p.next;
  43940. p = p.next;
  43941. } while (p !== start);
  43942. p.prevZ.nextZ = null;
  43943. p.prevZ = null;
  43944. sortLinked(p);
  43945. }
  43946. // Simon Tatham's linked list merge sort algorithm
  43947. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43948. function sortLinked(list) {
  43949. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43950. do {
  43951. p = list;
  43952. list = null;
  43953. tail = null;
  43954. numMerges = 0;
  43955. while (p) {
  43956. numMerges++;
  43957. q = p;
  43958. pSize = 0;
  43959. for (i = 0; i < inSize; i++) {
  43960. pSize++;
  43961. q = q.nextZ;
  43962. if (!q)
  43963. break;
  43964. }
  43965. qSize = inSize;
  43966. while (pSize > 0 || (qSize > 0 && q)) {
  43967. if (pSize === 0) {
  43968. e = q;
  43969. q = q.nextZ;
  43970. qSize--;
  43971. }
  43972. else if (qSize === 0 || !q) {
  43973. e = p;
  43974. p = p.nextZ;
  43975. pSize--;
  43976. }
  43977. else if (p.z <= q.z) {
  43978. e = p;
  43979. p = p.nextZ;
  43980. pSize--;
  43981. }
  43982. else {
  43983. e = q;
  43984. q = q.nextZ;
  43985. qSize--;
  43986. }
  43987. if (tail)
  43988. tail.nextZ = e;
  43989. else
  43990. list = e;
  43991. e.prevZ = tail;
  43992. tail = e;
  43993. }
  43994. p = q;
  43995. }
  43996. tail.nextZ = null;
  43997. inSize *= 2;
  43998. } while (numMerges > 1);
  43999. return list;
  44000. }
  44001. // z-order of a point given coords and size of the data bounding box
  44002. function zOrder(x, y, minX, minY, size) {
  44003. // coords are transformed into non-negative 15-bit integer range
  44004. x = 32767 * (x - minX) / size;
  44005. y = 32767 * (y - minY) / size;
  44006. x = (x | (x << 8)) & 0x00FF00FF;
  44007. x = (x | (x << 4)) & 0x0F0F0F0F;
  44008. x = (x | (x << 2)) & 0x33333333;
  44009. x = (x | (x << 1)) & 0x55555555;
  44010. y = (y | (y << 8)) & 0x00FF00FF;
  44011. y = (y | (y << 4)) & 0x0F0F0F0F;
  44012. y = (y | (y << 2)) & 0x33333333;
  44013. y = (y | (y << 1)) & 0x55555555;
  44014. return x | (y << 1);
  44015. }
  44016. // find the leftmost node of a polygon ring
  44017. function getLeftmost(start) {
  44018. var p = start, leftmost = start;
  44019. do {
  44020. if (p.x < leftmost.x)
  44021. leftmost = p;
  44022. p = p.next;
  44023. } while (p !== start);
  44024. return leftmost;
  44025. }
  44026. // check if a point lies within a convex triangle
  44027. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  44028. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  44029. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  44030. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  44031. }
  44032. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  44033. function isValidDiagonal(a, b) {
  44034. return a.next.i !== b.i &&
  44035. a.prev.i !== b.i &&
  44036. !intersectsPolygon(a, b) &&
  44037. locallyInside(a, b) &&
  44038. locallyInside(b, a) &&
  44039. middleInside(a, b);
  44040. }
  44041. // signed area of a triangle
  44042. function area(p, q, r) {
  44043. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  44044. }
  44045. // check if two points are equal
  44046. function equals(p1, p2) {
  44047. return p1.x === p2.x && p1.y === p2.y;
  44048. }
  44049. // check if two segments intersect
  44050. function intersects(p1, q1, p2, q2) {
  44051. if ((equals(p1, q1) && equals(p2, q2)) ||
  44052. (equals(p1, q2) && equals(p2, q1)))
  44053. return true;
  44054. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  44055. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  44056. }
  44057. // check if a polygon diagonal intersects any polygon segments
  44058. function intersectsPolygon(a, b) {
  44059. var p = a;
  44060. do {
  44061. if (p.i !== a.i &&
  44062. p.next.i !== a.i &&
  44063. p.i !== b.i &&
  44064. p.next.i !== b.i &&
  44065. intersects(p, p.next, a, b))
  44066. return true;
  44067. p = p.next;
  44068. } while (p !== a);
  44069. return false;
  44070. }
  44071. // check if a polygon diagonal is locally inside the polygon
  44072. function locallyInside(a, b) {
  44073. return area(a.prev, a, a.next) < 0
  44074. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  44075. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  44076. }
  44077. // check if the middle point of a polygon diagonal is inside the polygon
  44078. function middleInside(a, b) {
  44079. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  44080. do {
  44081. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  44082. inside = !inside;
  44083. p = p.next;
  44084. } while (p !== a);
  44085. return inside;
  44086. }
  44087. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  44088. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  44089. function splitPolygon(a, b) {
  44090. 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;
  44091. a.next = b;
  44092. b.prev = a;
  44093. a2.next = an;
  44094. an.prev = a2;
  44095. b2.next = a2;
  44096. a2.prev = b2;
  44097. bp.next = b2;
  44098. b2.prev = bp;
  44099. return b2;
  44100. }
  44101. // create a node and optionally link it with previous one (in a circular doubly linked list)
  44102. function insertNode(i, x, y, last) {
  44103. var p = new Node(i, x, y);
  44104. if (!last) {
  44105. p.prev = p;
  44106. p.next = p;
  44107. }
  44108. else {
  44109. p.next = last.next;
  44110. p.prev = last;
  44111. last.next.prev = p;
  44112. last.next = p;
  44113. }
  44114. return p;
  44115. }
  44116. function removeNode(p) {
  44117. p.next.prev = p.prev;
  44118. p.prev.next = p.next;
  44119. if (p.prevZ)
  44120. p.prevZ.nextZ = p.nextZ;
  44121. if (p.nextZ)
  44122. p.nextZ.prevZ = p.prevZ;
  44123. }
  44124. function Node(i, x, y) {
  44125. // vertice index in coordinates array
  44126. this.i = i;
  44127. // vertex coordinates
  44128. this.x = x;
  44129. this.y = y;
  44130. // previous and next vertice nodes in a polygon ring
  44131. this.prev = null;
  44132. this.next = null;
  44133. // z-order curve value
  44134. this.z = null;
  44135. // previous and next nodes in z-order
  44136. this.prevZ = null;
  44137. this.nextZ = null;
  44138. // indicates whether this is a steiner point
  44139. this.steiner = false;
  44140. }
  44141. /**
  44142. * return a percentage difference between the polygon area and its triangulation area;
  44143. * used to verify correctness of triangulation
  44144. */
  44145. function deviation(data, holeIndices, dim, triangles) {
  44146. var hasHoles = holeIndices && holeIndices.length;
  44147. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  44148. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  44149. if (hasHoles) {
  44150. for (var i = 0, len = holeIndices.length; i < len; i++) {
  44151. var start = holeIndices[i] * dim;
  44152. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  44153. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  44154. }
  44155. }
  44156. var trianglesArea = 0;
  44157. for (i = 0; i < triangles.length; i += 3) {
  44158. var a = triangles[i] * dim;
  44159. var b = triangles[i + 1] * dim;
  44160. var c = triangles[i + 2] * dim;
  44161. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  44162. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  44163. }
  44164. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  44165. }
  44166. Earcut.deviation = deviation;
  44167. ;
  44168. function signedArea(data, start, end, dim) {
  44169. var sum = 0;
  44170. for (var i = start, j = end - dim; i < end; i += dim) {
  44171. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44172. j = i;
  44173. }
  44174. return sum;
  44175. }
  44176. /**
  44177. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  44178. */
  44179. function flatten(data) {
  44180. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  44181. for (var i = 0; i < data.length; i++) {
  44182. for (var j = 0; j < data[i].length; j++) {
  44183. for (var d = 0; d < dim; d++)
  44184. result.vertices.push(data[i][j][d]);
  44185. }
  44186. if (i > 0) {
  44187. holeIndex += data[i - 1].length;
  44188. result.holes.push(holeIndex);
  44189. }
  44190. }
  44191. return result;
  44192. }
  44193. Earcut.flatten = flatten;
  44194. ;
  44195. })(Earcut || (Earcut = {}));
  44196. //# sourceMappingURL=babylon.earcut.js.map
  44197. var BABYLON;
  44198. (function (BABYLON) {
  44199. // Unique ID when we import meshes from Babylon to CSG
  44200. var currentCSGMeshId = 0;
  44201. // # class Vertex
  44202. // Represents a vertex of a polygon. Use your own vertex class instead of this
  44203. // one to provide additional features like texture coordinates and vertex
  44204. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  44205. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  44206. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  44207. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  44208. // is not used anywhere else.
  44209. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  44210. var Vertex = (function () {
  44211. function Vertex(pos, normal, uv) {
  44212. this.pos = pos;
  44213. this.normal = normal;
  44214. this.uv = uv;
  44215. }
  44216. Vertex.prototype.clone = function () {
  44217. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  44218. };
  44219. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  44220. // orientation of a polygon is flipped.
  44221. Vertex.prototype.flip = function () {
  44222. this.normal = this.normal.scale(-1);
  44223. };
  44224. // Create a new vertex between this vertex and `other` by linearly
  44225. // interpolating all properties using a parameter of `t`. Subclasses should
  44226. // override this to interpolate additional properties.
  44227. Vertex.prototype.interpolate = function (other, t) {
  44228. 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));
  44229. };
  44230. return Vertex;
  44231. }());
  44232. // # class Plane
  44233. // Represents a plane in 3D space.
  44234. var Plane = (function () {
  44235. function Plane(normal, w) {
  44236. this.normal = normal;
  44237. this.w = w;
  44238. }
  44239. Plane.FromPoints = function (a, b, c) {
  44240. var v0 = c.subtract(a);
  44241. var v1 = b.subtract(a);
  44242. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  44243. return null;
  44244. }
  44245. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  44246. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  44247. };
  44248. Plane.prototype.clone = function () {
  44249. return new Plane(this.normal.clone(), this.w);
  44250. };
  44251. Plane.prototype.flip = function () {
  44252. this.normal.scaleInPlace(-1);
  44253. this.w = -this.w;
  44254. };
  44255. // Split `polygon` by this plane if needed, then put the polygon or polygon
  44256. // fragments in the appropriate lists. Coplanar polygons go into either
  44257. // `coplanarFront` or `coplanarBack` depending on their orientation with
  44258. // respect to this plane. Polygons in front or in back of this plane go into
  44259. // either `front` or `back`.
  44260. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  44261. var COPLANAR = 0;
  44262. var FRONT = 1;
  44263. var BACK = 2;
  44264. var SPANNING = 3;
  44265. // Classify each point as well as the entire polygon into one of the above
  44266. // four classes.
  44267. var polygonType = 0;
  44268. var types = [];
  44269. var i;
  44270. var t;
  44271. for (i = 0; i < polygon.vertices.length; i++) {
  44272. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  44273. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  44274. polygonType |= type;
  44275. types.push(type);
  44276. }
  44277. // Put the polygon in the correct list, splitting it when necessary.
  44278. switch (polygonType) {
  44279. case COPLANAR:
  44280. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  44281. break;
  44282. case FRONT:
  44283. front.push(polygon);
  44284. break;
  44285. case BACK:
  44286. back.push(polygon);
  44287. break;
  44288. case SPANNING:
  44289. var f = [], b = [];
  44290. for (i = 0; i < polygon.vertices.length; i++) {
  44291. var j = (i + 1) % polygon.vertices.length;
  44292. var ti = types[i], tj = types[j];
  44293. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44294. if (ti !== BACK)
  44295. f.push(vi);
  44296. if (ti !== FRONT)
  44297. b.push(ti !== BACK ? vi.clone() : vi);
  44298. if ((ti | tj) === SPANNING) {
  44299. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44300. var v = vi.interpolate(vj, t);
  44301. f.push(v);
  44302. b.push(v.clone());
  44303. }
  44304. }
  44305. var poly;
  44306. if (f.length >= 3) {
  44307. poly = new Polygon(f, polygon.shared);
  44308. if (poly.plane)
  44309. front.push(poly);
  44310. }
  44311. if (b.length >= 3) {
  44312. poly = new Polygon(b, polygon.shared);
  44313. if (poly.plane)
  44314. back.push(poly);
  44315. }
  44316. break;
  44317. }
  44318. };
  44319. return Plane;
  44320. }());
  44321. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44322. // point is on the plane.
  44323. Plane.EPSILON = 1e-5;
  44324. // # class Polygon
  44325. // Represents a convex polygon. The vertices used to initialize a polygon must
  44326. // be coplanar and form a convex loop.
  44327. //
  44328. // Each convex polygon has a `shared` property, which is shared between all
  44329. // polygons that are clones of each other or were split from the same polygon.
  44330. // This can be used to define per-polygon properties (such as surface color).
  44331. var Polygon = (function () {
  44332. function Polygon(vertices, shared) {
  44333. this.vertices = vertices;
  44334. this.shared = shared;
  44335. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44336. }
  44337. Polygon.prototype.clone = function () {
  44338. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44339. return new Polygon(vertices, this.shared);
  44340. };
  44341. Polygon.prototype.flip = function () {
  44342. this.vertices.reverse().map(function (v) { v.flip(); });
  44343. this.plane.flip();
  44344. };
  44345. return Polygon;
  44346. }());
  44347. // # class Node
  44348. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44349. // by picking a polygon to split along. That polygon (and all other coplanar
  44350. // polygons) are added directly to that node and the other polygons are added to
  44351. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44352. // no distinction between internal and leaf nodes.
  44353. var Node = (function () {
  44354. function Node(polygons) {
  44355. this.plane = null;
  44356. this.front = null;
  44357. this.back = null;
  44358. this.polygons = [];
  44359. if (polygons) {
  44360. this.build(polygons);
  44361. }
  44362. }
  44363. Node.prototype.clone = function () {
  44364. var node = new Node();
  44365. node.plane = this.plane && this.plane.clone();
  44366. node.front = this.front && this.front.clone();
  44367. node.back = this.back && this.back.clone();
  44368. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44369. return node;
  44370. };
  44371. // Convert solid space to empty space and empty space to solid space.
  44372. Node.prototype.invert = function () {
  44373. for (var i = 0; i < this.polygons.length; i++) {
  44374. this.polygons[i].flip();
  44375. }
  44376. if (this.plane) {
  44377. this.plane.flip();
  44378. }
  44379. if (this.front) {
  44380. this.front.invert();
  44381. }
  44382. if (this.back) {
  44383. this.back.invert();
  44384. }
  44385. var temp = this.front;
  44386. this.front = this.back;
  44387. this.back = temp;
  44388. };
  44389. // Recursively remove all polygons in `polygons` that are inside this BSP
  44390. // tree.
  44391. Node.prototype.clipPolygons = function (polygons) {
  44392. if (!this.plane)
  44393. return polygons.slice();
  44394. var front = [], back = [];
  44395. for (var i = 0; i < polygons.length; i++) {
  44396. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44397. }
  44398. if (this.front) {
  44399. front = this.front.clipPolygons(front);
  44400. }
  44401. if (this.back) {
  44402. back = this.back.clipPolygons(back);
  44403. }
  44404. else {
  44405. back = [];
  44406. }
  44407. return front.concat(back);
  44408. };
  44409. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44410. // `bsp`.
  44411. Node.prototype.clipTo = function (bsp) {
  44412. this.polygons = bsp.clipPolygons(this.polygons);
  44413. if (this.front)
  44414. this.front.clipTo(bsp);
  44415. if (this.back)
  44416. this.back.clipTo(bsp);
  44417. };
  44418. // Return a list of all polygons in this BSP tree.
  44419. Node.prototype.allPolygons = function () {
  44420. var polygons = this.polygons.slice();
  44421. if (this.front)
  44422. polygons = polygons.concat(this.front.allPolygons());
  44423. if (this.back)
  44424. polygons = polygons.concat(this.back.allPolygons());
  44425. return polygons;
  44426. };
  44427. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44428. // new polygons are filtered down to the bottom of the tree and become new
  44429. // nodes there. Each set of polygons is partitioned using the first polygon
  44430. // (no heuristic is used to pick a good split).
  44431. Node.prototype.build = function (polygons) {
  44432. if (!polygons.length)
  44433. return;
  44434. if (!this.plane)
  44435. this.plane = polygons[0].plane.clone();
  44436. var front = [], back = [];
  44437. for (var i = 0; i < polygons.length; i++) {
  44438. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44439. }
  44440. if (front.length) {
  44441. if (!this.front)
  44442. this.front = new Node();
  44443. this.front.build(front);
  44444. }
  44445. if (back.length) {
  44446. if (!this.back)
  44447. this.back = new Node();
  44448. this.back.build(back);
  44449. }
  44450. };
  44451. return Node;
  44452. }());
  44453. var CSG = (function () {
  44454. function CSG() {
  44455. this.polygons = new Array();
  44456. }
  44457. // Convert BABYLON.Mesh to BABYLON.CSG
  44458. CSG.FromMesh = function (mesh) {
  44459. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44460. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44461. if (mesh instanceof BABYLON.Mesh) {
  44462. mesh.computeWorldMatrix(true);
  44463. matrix = mesh.getWorldMatrix();
  44464. meshPosition = mesh.position.clone();
  44465. meshRotation = mesh.rotation.clone();
  44466. if (mesh.rotationQuaternion) {
  44467. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44468. }
  44469. meshScaling = mesh.scaling.clone();
  44470. }
  44471. else {
  44472. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44473. }
  44474. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44475. var subMeshes = mesh.subMeshes;
  44476. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44477. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44478. vertices = [];
  44479. for (var j = 0; j < 3; j++) {
  44480. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44481. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44482. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44483. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44484. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44485. vertex = new Vertex(position, normal, uv);
  44486. vertices.push(vertex);
  44487. }
  44488. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44489. // To handle the case of degenerated triangle
  44490. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44491. if (polygon.plane)
  44492. polygons.push(polygon);
  44493. }
  44494. }
  44495. var csg = CSG.FromPolygons(polygons);
  44496. csg.matrix = matrix;
  44497. csg.position = meshPosition;
  44498. csg.rotation = meshRotation;
  44499. csg.scaling = meshScaling;
  44500. csg.rotationQuaternion = meshRotationQuaternion;
  44501. currentCSGMeshId++;
  44502. return csg;
  44503. };
  44504. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44505. CSG.FromPolygons = function (polygons) {
  44506. var csg = new CSG();
  44507. csg.polygons = polygons;
  44508. return csg;
  44509. };
  44510. CSG.prototype.clone = function () {
  44511. var csg = new CSG();
  44512. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44513. csg.copyTransformAttributes(this);
  44514. return csg;
  44515. };
  44516. CSG.prototype.toPolygons = function () {
  44517. return this.polygons;
  44518. };
  44519. CSG.prototype.union = function (csg) {
  44520. var a = new Node(this.clone().polygons);
  44521. var b = new Node(csg.clone().polygons);
  44522. a.clipTo(b);
  44523. b.clipTo(a);
  44524. b.invert();
  44525. b.clipTo(a);
  44526. b.invert();
  44527. a.build(b.allPolygons());
  44528. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44529. };
  44530. CSG.prototype.unionInPlace = function (csg) {
  44531. var a = new Node(this.polygons);
  44532. var b = new Node(csg.polygons);
  44533. a.clipTo(b);
  44534. b.clipTo(a);
  44535. b.invert();
  44536. b.clipTo(a);
  44537. b.invert();
  44538. a.build(b.allPolygons());
  44539. this.polygons = a.allPolygons();
  44540. };
  44541. CSG.prototype.subtract = function (csg) {
  44542. var a = new Node(this.clone().polygons);
  44543. var b = new Node(csg.clone().polygons);
  44544. a.invert();
  44545. a.clipTo(b);
  44546. b.clipTo(a);
  44547. b.invert();
  44548. b.clipTo(a);
  44549. b.invert();
  44550. a.build(b.allPolygons());
  44551. a.invert();
  44552. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44553. };
  44554. CSG.prototype.subtractInPlace = function (csg) {
  44555. var a = new Node(this.polygons);
  44556. var b = new Node(csg.polygons);
  44557. a.invert();
  44558. a.clipTo(b);
  44559. b.clipTo(a);
  44560. b.invert();
  44561. b.clipTo(a);
  44562. b.invert();
  44563. a.build(b.allPolygons());
  44564. a.invert();
  44565. this.polygons = a.allPolygons();
  44566. };
  44567. CSG.prototype.intersect = function (csg) {
  44568. var a = new Node(this.clone().polygons);
  44569. var b = new Node(csg.clone().polygons);
  44570. a.invert();
  44571. b.clipTo(a);
  44572. b.invert();
  44573. a.clipTo(b);
  44574. b.clipTo(a);
  44575. a.build(b.allPolygons());
  44576. a.invert();
  44577. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44578. };
  44579. CSG.prototype.intersectInPlace = function (csg) {
  44580. var a = new Node(this.polygons);
  44581. var b = new Node(csg.polygons);
  44582. a.invert();
  44583. b.clipTo(a);
  44584. b.invert();
  44585. a.clipTo(b);
  44586. b.clipTo(a);
  44587. a.build(b.allPolygons());
  44588. a.invert();
  44589. this.polygons = a.allPolygons();
  44590. };
  44591. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44592. // not modified.
  44593. CSG.prototype.inverse = function () {
  44594. var csg = this.clone();
  44595. csg.inverseInPlace();
  44596. return csg;
  44597. };
  44598. CSG.prototype.inverseInPlace = function () {
  44599. this.polygons.map(function (p) { p.flip(); });
  44600. };
  44601. // This is used to keep meshes transformations so they can be restored
  44602. // when we build back a Babylon Mesh
  44603. // NB : All CSG operations are performed in world coordinates
  44604. CSG.prototype.copyTransformAttributes = function (csg) {
  44605. this.matrix = csg.matrix;
  44606. this.position = csg.position;
  44607. this.rotation = csg.rotation;
  44608. this.scaling = csg.scaling;
  44609. this.rotationQuaternion = csg.rotationQuaternion;
  44610. return this;
  44611. };
  44612. // Build Raw mesh from CSG
  44613. // Coordinates here are in world space
  44614. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44615. var matrix = this.matrix.clone();
  44616. matrix.invert();
  44617. 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;
  44618. if (keepSubMeshes) {
  44619. // Sort Polygons, since subMeshes are indices range
  44620. polygons.sort(function (a, b) {
  44621. if (a.shared.meshId === b.shared.meshId) {
  44622. return a.shared.subMeshId - b.shared.subMeshId;
  44623. }
  44624. else {
  44625. return a.shared.meshId - b.shared.meshId;
  44626. }
  44627. });
  44628. }
  44629. for (var i = 0, il = polygons.length; i < il; i++) {
  44630. polygon = polygons[i];
  44631. // Building SubMeshes
  44632. if (!subMesh_dict[polygon.shared.meshId]) {
  44633. subMesh_dict[polygon.shared.meshId] = {};
  44634. }
  44635. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44636. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44637. indexStart: +Infinity,
  44638. indexEnd: -Infinity,
  44639. materialIndex: polygon.shared.materialIndex
  44640. };
  44641. }
  44642. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44643. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44644. polygonIndices[0] = 0;
  44645. polygonIndices[1] = j - 1;
  44646. polygonIndices[2] = j;
  44647. for (var k = 0; k < 3; k++) {
  44648. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44649. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44650. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44651. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44652. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44653. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44654. // Check if 2 points can be merged
  44655. if (!(typeof vertex_idx !== 'undefined' &&
  44656. normals[vertex_idx * 3] === localNormal.x &&
  44657. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44658. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44659. uvs[vertex_idx * 2] === uv.x &&
  44660. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44661. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44662. uvs.push(uv.x, uv.y);
  44663. normals.push(normal.x, normal.y, normal.z);
  44664. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44665. }
  44666. indices.push(vertex_idx);
  44667. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44668. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44669. currentIndex++;
  44670. }
  44671. }
  44672. }
  44673. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44674. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44675. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44676. mesh.setIndices(indices);
  44677. if (keepSubMeshes) {
  44678. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44679. var materialIndexOffset = 0, materialMaxIndex;
  44680. mesh.subMeshes = new Array();
  44681. for (var m in subMesh_dict) {
  44682. materialMaxIndex = -1;
  44683. for (var sm in subMesh_dict[m]) {
  44684. subMesh_obj = subMesh_dict[m][sm];
  44685. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44686. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44687. }
  44688. materialIndexOffset += ++materialMaxIndex;
  44689. }
  44690. }
  44691. return mesh;
  44692. };
  44693. // Build Mesh from CSG taking material and transforms into account
  44694. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44695. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44696. mesh.material = material;
  44697. mesh.position.copyFrom(this.position);
  44698. mesh.rotation.copyFrom(this.rotation);
  44699. if (this.rotationQuaternion) {
  44700. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44701. }
  44702. mesh.scaling.copyFrom(this.scaling);
  44703. mesh.computeWorldMatrix(true);
  44704. return mesh;
  44705. };
  44706. return CSG;
  44707. }());
  44708. BABYLON.CSG = CSG;
  44709. })(BABYLON || (BABYLON = {}));
  44710. //# sourceMappingURL=babylon.csg.js.map
  44711. var BABYLON;
  44712. (function (BABYLON) {
  44713. var VRDistortionCorrectionPostProcess = (function (_super) {
  44714. __extends(VRDistortionCorrectionPostProcess, _super);
  44715. //ANY
  44716. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44717. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44718. 'LensCenter',
  44719. 'Scale',
  44720. 'ScaleIn',
  44721. 'HmdWarpParam'
  44722. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44723. _this._isRightEye = isRightEye;
  44724. _this._distortionFactors = vrMetrics.distortionK;
  44725. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44726. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44727. _this.onSizeChangedObservable.add(function () {
  44728. _this.aspectRatio = _this.width * .5 / _this.height;
  44729. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44730. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44731. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44732. });
  44733. _this.onApplyObservable.add(function (effect) {
  44734. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44735. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44736. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44737. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44738. });
  44739. return _this;
  44740. }
  44741. return VRDistortionCorrectionPostProcess;
  44742. }(BABYLON.PostProcess));
  44743. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44744. })(BABYLON || (BABYLON = {}));
  44745. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44746. // Mainly based on these 2 articles :
  44747. // 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
  44748. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44749. var BABYLON;
  44750. (function (BABYLON) {
  44751. var JoystickAxis;
  44752. (function (JoystickAxis) {
  44753. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44754. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44755. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44756. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44757. var VirtualJoystick = (function () {
  44758. function VirtualJoystick(leftJoystick) {
  44759. var _this = this;
  44760. if (leftJoystick) {
  44761. this._leftJoystick = true;
  44762. }
  44763. else {
  44764. this._leftJoystick = false;
  44765. }
  44766. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44767. VirtualJoystick._globalJoystickIndex++;
  44768. // By default left & right arrow keys are moving the X
  44769. // and up & down keys are moving the Y
  44770. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44771. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44772. this.reverseLeftRight = false;
  44773. this.reverseUpDown = false;
  44774. // collections of pointers
  44775. this._touches = new BABYLON.StringDictionary();
  44776. this.deltaPosition = BABYLON.Vector3.Zero();
  44777. this._joystickSensibility = 25;
  44778. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44779. this._rotationSpeed = 25;
  44780. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44781. this._rotateOnAxisRelativeToMesh = false;
  44782. this._onResize = function (evt) {
  44783. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44784. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44785. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44786. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44787. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44788. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44789. };
  44790. // injecting a canvas element on top of the canvas 3D game
  44791. if (!VirtualJoystick.vjCanvas) {
  44792. window.addEventListener("resize", this._onResize, false);
  44793. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44794. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44795. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44796. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44797. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44798. VirtualJoystick.vjCanvas.style.width = "100%";
  44799. VirtualJoystick.vjCanvas.style.height = "100%";
  44800. VirtualJoystick.vjCanvas.style.position = "absolute";
  44801. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44802. VirtualJoystick.vjCanvas.style.top = "0px";
  44803. VirtualJoystick.vjCanvas.style.left = "0px";
  44804. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44805. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44806. // Support for jQuery PEP polyfill
  44807. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44808. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44809. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44810. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44811. document.body.appendChild(VirtualJoystick.vjCanvas);
  44812. }
  44813. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44814. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44815. this.pressed = false;
  44816. // default joystick color
  44817. this._joystickColor = "cyan";
  44818. this._joystickPointerID = -1;
  44819. // current joystick position
  44820. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44821. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44822. // origin joystick position
  44823. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44824. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44825. this._onPointerDownHandlerRef = function (evt) {
  44826. _this._onPointerDown(evt);
  44827. };
  44828. this._onPointerMoveHandlerRef = function (evt) {
  44829. _this._onPointerMove(evt);
  44830. };
  44831. this._onPointerOutHandlerRef = function (evt) {
  44832. _this._onPointerUp(evt);
  44833. };
  44834. this._onPointerUpHandlerRef = function (evt) {
  44835. _this._onPointerUp(evt);
  44836. };
  44837. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44838. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44839. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44840. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44841. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44842. evt.preventDefault(); // Disables system menu
  44843. }, false);
  44844. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44845. }
  44846. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44847. this._joystickSensibility = newJoystickSensibility;
  44848. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44849. };
  44850. VirtualJoystick.prototype._onPointerDown = function (e) {
  44851. var positionOnScreenCondition;
  44852. e.preventDefault();
  44853. if (this._leftJoystick === true) {
  44854. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44855. }
  44856. else {
  44857. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44858. }
  44859. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44860. // First contact will be dedicated to the virtual joystick
  44861. this._joystickPointerID = e.pointerId;
  44862. this._joystickPointerStartPos.x = e.clientX;
  44863. this._joystickPointerStartPos.y = e.clientY;
  44864. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44865. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44866. this._deltaJoystickVector.x = 0;
  44867. this._deltaJoystickVector.y = 0;
  44868. this.pressed = true;
  44869. this._touches.add(e.pointerId.toString(), e);
  44870. }
  44871. else {
  44872. // You can only trigger the action buttons with a joystick declared
  44873. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44874. this._action();
  44875. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44876. }
  44877. }
  44878. };
  44879. VirtualJoystick.prototype._onPointerMove = function (e) {
  44880. // If the current pointer is the one associated to the joystick (first touch contact)
  44881. if (this._joystickPointerID == e.pointerId) {
  44882. this._joystickPointerPos.x = e.clientX;
  44883. this._joystickPointerPos.y = e.clientY;
  44884. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44885. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44886. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44887. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44888. switch (this._axisTargetedByLeftAndRight) {
  44889. case JoystickAxis.X:
  44890. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44891. break;
  44892. case JoystickAxis.Y:
  44893. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44894. break;
  44895. case JoystickAxis.Z:
  44896. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44897. break;
  44898. }
  44899. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44900. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44901. switch (this._axisTargetedByUpAndDown) {
  44902. case JoystickAxis.X:
  44903. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44904. break;
  44905. case JoystickAxis.Y:
  44906. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44907. break;
  44908. case JoystickAxis.Z:
  44909. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44910. break;
  44911. }
  44912. }
  44913. else {
  44914. var data = this._touches.get(e.pointerId.toString());
  44915. if (data) {
  44916. data.x = e.clientX;
  44917. data.y = e.clientY;
  44918. }
  44919. }
  44920. };
  44921. VirtualJoystick.prototype._onPointerUp = function (e) {
  44922. if (this._joystickPointerID == e.pointerId) {
  44923. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  44924. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  44925. this._joystickPointerID = -1;
  44926. this.pressed = false;
  44927. }
  44928. else {
  44929. var touch = this._touches.get(e.pointerId.toString());
  44930. if (touch) {
  44931. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  44932. }
  44933. }
  44934. this._deltaJoystickVector.x = 0;
  44935. this._deltaJoystickVector.y = 0;
  44936. this._touches.remove(e.pointerId.toString());
  44937. };
  44938. /**
  44939. * Change the color of the virtual joystick
  44940. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44941. */
  44942. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44943. this._joystickColor = newColor;
  44944. };
  44945. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44946. this._action = action;
  44947. };
  44948. // Define which axis you'd like to control for left & right
  44949. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44950. switch (axis) {
  44951. case JoystickAxis.X:
  44952. case JoystickAxis.Y:
  44953. case JoystickAxis.Z:
  44954. this._axisTargetedByLeftAndRight = axis;
  44955. break;
  44956. default:
  44957. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44958. break;
  44959. }
  44960. };
  44961. // Define which axis you'd like to control for up & down
  44962. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44963. switch (axis) {
  44964. case JoystickAxis.X:
  44965. case JoystickAxis.Y:
  44966. case JoystickAxis.Z:
  44967. this._axisTargetedByUpAndDown = axis;
  44968. break;
  44969. default:
  44970. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44971. break;
  44972. }
  44973. };
  44974. VirtualJoystick.prototype._clearCanvas = function () {
  44975. if (this._leftJoystick) {
  44976. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44977. }
  44978. else {
  44979. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44980. }
  44981. };
  44982. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44983. var _this = this;
  44984. if (this.pressed) {
  44985. this._touches.forEach(function (key, touch) {
  44986. if (touch.pointerId === _this._joystickPointerID) {
  44987. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  44988. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  44989. VirtualJoystick.vjCanvasContext.beginPath();
  44990. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44991. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44992. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44993. VirtualJoystick.vjCanvasContext.stroke();
  44994. VirtualJoystick.vjCanvasContext.closePath();
  44995. VirtualJoystick.vjCanvasContext.beginPath();
  44996. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44997. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44998. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44999. VirtualJoystick.vjCanvasContext.stroke();
  45000. VirtualJoystick.vjCanvasContext.closePath();
  45001. VirtualJoystick.vjCanvasContext.beginPath();
  45002. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  45003. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  45004. VirtualJoystick.vjCanvasContext.stroke();
  45005. VirtualJoystick.vjCanvasContext.closePath();
  45006. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  45007. }
  45008. else {
  45009. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  45010. VirtualJoystick.vjCanvasContext.beginPath();
  45011. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  45012. VirtualJoystick.vjCanvasContext.beginPath();
  45013. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  45014. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  45015. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  45016. VirtualJoystick.vjCanvasContext.stroke();
  45017. VirtualJoystick.vjCanvasContext.closePath();
  45018. touch.prevX = touch.x;
  45019. touch.prevY = touch.y;
  45020. }
  45021. ;
  45022. });
  45023. }
  45024. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  45025. };
  45026. VirtualJoystick.prototype.releaseCanvas = function () {
  45027. if (VirtualJoystick.vjCanvas) {
  45028. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  45029. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  45030. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  45031. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  45032. window.removeEventListener("resize", this._onResize);
  45033. document.body.removeChild(VirtualJoystick.vjCanvas);
  45034. VirtualJoystick.vjCanvas = null;
  45035. }
  45036. };
  45037. return VirtualJoystick;
  45038. }());
  45039. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  45040. VirtualJoystick._globalJoystickIndex = 0;
  45041. BABYLON.VirtualJoystick = VirtualJoystick;
  45042. })(BABYLON || (BABYLON = {}));
  45043. //# sourceMappingURL=babylon.virtualJoystick.js.map
  45044. var BABYLON;
  45045. (function (BABYLON) {
  45046. // We're mainly based on the logic defined into the FreeCamera code
  45047. var VirtualJoysticksCamera = (function (_super) {
  45048. __extends(VirtualJoysticksCamera, _super);
  45049. function VirtualJoysticksCamera(name, position, scene) {
  45050. var _this = _super.call(this, name, position, scene) || this;
  45051. _this.inputs.addVirtualJoystick();
  45052. return _this;
  45053. }
  45054. VirtualJoysticksCamera.prototype.getClassName = function () {
  45055. return "VirtualJoysticksCamera";
  45056. };
  45057. return VirtualJoysticksCamera;
  45058. }(BABYLON.FreeCamera));
  45059. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  45060. })(BABYLON || (BABYLON = {}));
  45061. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  45062. var BABYLON;
  45063. (function (BABYLON) {
  45064. var FreeCameraVirtualJoystickInput = (function () {
  45065. function FreeCameraVirtualJoystickInput() {
  45066. }
  45067. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  45068. return this._leftjoystick;
  45069. };
  45070. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  45071. return this._rightjoystick;
  45072. };
  45073. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  45074. if (this._leftjoystick) {
  45075. var camera = this.camera;
  45076. var speed = camera._computeLocalCameraSpeed() * 50;
  45077. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  45078. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  45079. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  45080. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  45081. if (!this._leftjoystick.pressed) {
  45082. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  45083. }
  45084. if (!this._rightjoystick.pressed) {
  45085. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  45086. }
  45087. }
  45088. };
  45089. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  45090. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  45091. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  45092. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  45093. this._leftjoystick.setJoystickSensibility(0.15);
  45094. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  45095. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  45096. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  45097. this._rightjoystick.reverseUpDown = true;
  45098. this._rightjoystick.setJoystickSensibility(0.05);
  45099. this._rightjoystick.setJoystickColor("yellow");
  45100. };
  45101. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  45102. this._leftjoystick.releaseCanvas();
  45103. this._rightjoystick.releaseCanvas();
  45104. };
  45105. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  45106. return "FreeCameraVirtualJoystickInput";
  45107. };
  45108. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  45109. return "virtualJoystick";
  45110. };
  45111. return FreeCameraVirtualJoystickInput;
  45112. }());
  45113. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  45114. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  45115. })(BABYLON || (BABYLON = {}));
  45116. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  45117. var BABYLON;
  45118. (function (BABYLON) {
  45119. var AnaglyphPostProcess = (function (_super) {
  45120. __extends(AnaglyphPostProcess, _super);
  45121. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  45122. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  45123. _this._passedProcess = rigCameras[0]._rigPostProcess;
  45124. _this.onApplyObservable.add(function (effect) {
  45125. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  45126. });
  45127. return _this;
  45128. }
  45129. return AnaglyphPostProcess;
  45130. }(BABYLON.PostProcess));
  45131. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  45132. })(BABYLON || (BABYLON = {}));
  45133. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  45134. var BABYLON;
  45135. (function (BABYLON) {
  45136. var OutlineRenderer = (function () {
  45137. function OutlineRenderer(scene) {
  45138. this._scene = scene;
  45139. }
  45140. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  45141. var _this = this;
  45142. if (useOverlay === void 0) { useOverlay = false; }
  45143. var scene = this._scene;
  45144. var engine = this._scene.getEngine();
  45145. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45146. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  45147. return;
  45148. }
  45149. var mesh = subMesh.getRenderingMesh();
  45150. var material = subMesh.getMaterial();
  45151. engine.enableEffect(this._effect);
  45152. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  45153. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  45154. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45155. // Bones
  45156. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45157. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45158. }
  45159. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  45160. // Alpha test
  45161. if (material && material.needAlphaTesting()) {
  45162. var alphaTexture = material.getAlphaTestTexture();
  45163. this._effect.setTexture("diffuseSampler", alphaTexture);
  45164. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45165. }
  45166. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  45167. };
  45168. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  45169. var defines = [];
  45170. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  45171. var mesh = subMesh.getMesh();
  45172. var material = subMesh.getMaterial();
  45173. // Alpha test
  45174. if (material && material.needAlphaTesting()) {
  45175. defines.push("#define ALPHATEST");
  45176. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45177. attribs.push(BABYLON.VertexBuffer.UVKind);
  45178. defines.push("#define UV1");
  45179. }
  45180. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45181. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45182. defines.push("#define UV2");
  45183. }
  45184. }
  45185. // Bones
  45186. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45189. if (mesh.numBoneInfluencers > 4) {
  45190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45192. }
  45193. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45194. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45195. }
  45196. else {
  45197. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45198. }
  45199. // Instances
  45200. if (useInstances) {
  45201. defines.push("#define INSTANCES");
  45202. attribs.push("world0");
  45203. attribs.push("world1");
  45204. attribs.push("world2");
  45205. attribs.push("world3");
  45206. }
  45207. // Get correct effect
  45208. var join = defines.join("\n");
  45209. if (this._cachedDefines !== join) {
  45210. this._cachedDefines = join;
  45211. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  45212. }
  45213. return this._effect.isReady();
  45214. };
  45215. return OutlineRenderer;
  45216. }());
  45217. BABYLON.OutlineRenderer = OutlineRenderer;
  45218. })(BABYLON || (BABYLON = {}));
  45219. //# sourceMappingURL=babylon.outlineRenderer.js.map
  45220. var BABYLON;
  45221. (function (BABYLON) {
  45222. var MeshAssetTask = (function () {
  45223. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  45224. this.name = name;
  45225. this.meshesNames = meshesNames;
  45226. this.rootUrl = rootUrl;
  45227. this.sceneFilename = sceneFilename;
  45228. this.isCompleted = false;
  45229. }
  45230. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45231. var _this = this;
  45232. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  45233. _this.loadedMeshes = meshes;
  45234. _this.loadedParticleSystems = particleSystems;
  45235. _this.loadedSkeletons = skeletons;
  45236. _this.isCompleted = true;
  45237. if (_this.onSuccess) {
  45238. _this.onSuccess(_this);
  45239. }
  45240. onSuccess();
  45241. }, null, function () {
  45242. if (_this.onError) {
  45243. _this.onError(_this);
  45244. }
  45245. onError();
  45246. });
  45247. };
  45248. return MeshAssetTask;
  45249. }());
  45250. BABYLON.MeshAssetTask = MeshAssetTask;
  45251. var TextFileAssetTask = (function () {
  45252. function TextFileAssetTask(name, url) {
  45253. this.name = name;
  45254. this.url = url;
  45255. this.isCompleted = false;
  45256. }
  45257. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45258. var _this = this;
  45259. BABYLON.Tools.LoadFile(this.url, function (data) {
  45260. _this.text = data;
  45261. _this.isCompleted = true;
  45262. if (_this.onSuccess) {
  45263. _this.onSuccess(_this);
  45264. }
  45265. onSuccess();
  45266. }, null, scene.database, false, function () {
  45267. if (_this.onError) {
  45268. _this.onError(_this);
  45269. }
  45270. onError();
  45271. });
  45272. };
  45273. return TextFileAssetTask;
  45274. }());
  45275. BABYLON.TextFileAssetTask = TextFileAssetTask;
  45276. var BinaryFileAssetTask = (function () {
  45277. function BinaryFileAssetTask(name, url) {
  45278. this.name = name;
  45279. this.url = url;
  45280. this.isCompleted = false;
  45281. }
  45282. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45283. var _this = this;
  45284. BABYLON.Tools.LoadFile(this.url, function (data) {
  45285. _this.data = data;
  45286. _this.isCompleted = true;
  45287. if (_this.onSuccess) {
  45288. _this.onSuccess(_this);
  45289. }
  45290. onSuccess();
  45291. }, null, scene.database, true, function () {
  45292. if (_this.onError) {
  45293. _this.onError(_this);
  45294. }
  45295. onError();
  45296. });
  45297. };
  45298. return BinaryFileAssetTask;
  45299. }());
  45300. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  45301. var ImageAssetTask = (function () {
  45302. function ImageAssetTask(name, url) {
  45303. this.name = name;
  45304. this.url = url;
  45305. this.isCompleted = false;
  45306. }
  45307. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45308. var _this = this;
  45309. var img = new Image();
  45310. BABYLON.Tools.SetCorsBehavior(this.url, img);
  45311. img.onload = function () {
  45312. _this.image = img;
  45313. _this.isCompleted = true;
  45314. if (_this.onSuccess) {
  45315. _this.onSuccess(_this);
  45316. }
  45317. onSuccess();
  45318. };
  45319. img.onerror = function () {
  45320. if (_this.onError) {
  45321. _this.onError(_this);
  45322. }
  45323. onError();
  45324. };
  45325. img.src = this.url;
  45326. };
  45327. return ImageAssetTask;
  45328. }());
  45329. BABYLON.ImageAssetTask = ImageAssetTask;
  45330. var TextureAssetTask = (function () {
  45331. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45333. this.name = name;
  45334. this.url = url;
  45335. this.noMipmap = noMipmap;
  45336. this.invertY = invertY;
  45337. this.samplingMode = samplingMode;
  45338. this.isCompleted = false;
  45339. }
  45340. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45341. var _this = this;
  45342. var onload = function () {
  45343. _this.isCompleted = true;
  45344. if (_this.onSuccess) {
  45345. _this.onSuccess(_this);
  45346. }
  45347. onSuccess();
  45348. };
  45349. var onerror = function () {
  45350. if (_this.onError) {
  45351. _this.onError(_this);
  45352. }
  45353. onError();
  45354. };
  45355. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45356. };
  45357. return TextureAssetTask;
  45358. }());
  45359. BABYLON.TextureAssetTask = TextureAssetTask;
  45360. var CubeTextureAssetTask = (function () {
  45361. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  45362. this.name = name;
  45363. this.url = url;
  45364. this.extensions = extensions;
  45365. this.noMipmap = noMipmap;
  45366. this.files = files;
  45367. this.isCompleted = false;
  45368. }
  45369. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45370. var _this = this;
  45371. var onload = function () {
  45372. _this.isCompleted = true;
  45373. if (_this.onSuccess) {
  45374. _this.onSuccess(_this);
  45375. }
  45376. onSuccess();
  45377. };
  45378. var onerror = function () {
  45379. if (_this.onError) {
  45380. _this.onError(_this);
  45381. }
  45382. onError();
  45383. };
  45384. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  45385. };
  45386. return CubeTextureAssetTask;
  45387. }());
  45388. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  45389. var AssetsManager = (function () {
  45390. function AssetsManager(scene) {
  45391. this.tasks = new Array();
  45392. this.waitingTasksCount = 0;
  45393. this.useDefaultLoadingScreen = true;
  45394. this._scene = scene;
  45395. }
  45396. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45397. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45398. this.tasks.push(task);
  45399. return task;
  45400. };
  45401. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45402. var task = new TextFileAssetTask(taskName, url);
  45403. this.tasks.push(task);
  45404. return task;
  45405. };
  45406. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45407. var task = new BinaryFileAssetTask(taskName, url);
  45408. this.tasks.push(task);
  45409. return task;
  45410. };
  45411. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45412. var task = new ImageAssetTask(taskName, url);
  45413. this.tasks.push(task);
  45414. return task;
  45415. };
  45416. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45418. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45419. this.tasks.push(task);
  45420. return task;
  45421. };
  45422. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45423. this.waitingTasksCount--;
  45424. if (this.waitingTasksCount === 0) {
  45425. if (this.onFinish) {
  45426. this.onFinish(this.tasks);
  45427. }
  45428. this._scene.getEngine().hideLoadingUI();
  45429. }
  45430. };
  45431. AssetsManager.prototype._runTask = function (task) {
  45432. var _this = this;
  45433. task.run(this._scene, function () {
  45434. if (_this.onTaskSuccess) {
  45435. _this.onTaskSuccess(task);
  45436. }
  45437. _this._decreaseWaitingTasksCount();
  45438. }, function () {
  45439. if (_this.onTaskError) {
  45440. _this.onTaskError(task);
  45441. }
  45442. _this._decreaseWaitingTasksCount();
  45443. });
  45444. };
  45445. AssetsManager.prototype.reset = function () {
  45446. this.tasks = new Array();
  45447. return this;
  45448. };
  45449. AssetsManager.prototype.load = function () {
  45450. this.waitingTasksCount = this.tasks.length;
  45451. if (this.waitingTasksCount === 0) {
  45452. if (this.onFinish) {
  45453. this.onFinish(this.tasks);
  45454. }
  45455. return this;
  45456. }
  45457. if (this.useDefaultLoadingScreen) {
  45458. this._scene.getEngine().displayLoadingUI();
  45459. }
  45460. for (var index = 0; index < this.tasks.length; index++) {
  45461. var task = this.tasks[index];
  45462. this._runTask(task);
  45463. }
  45464. return this;
  45465. };
  45466. return AssetsManager;
  45467. }());
  45468. BABYLON.AssetsManager = AssetsManager;
  45469. })(BABYLON || (BABYLON = {}));
  45470. //# sourceMappingURL=babylon.assetsManager.js.map
  45471. var BABYLON;
  45472. (function (BABYLON) {
  45473. var VRCameraMetrics = (function () {
  45474. function VRCameraMetrics() {
  45475. this.compensateDistortion = true;
  45476. }
  45477. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45478. get: function () {
  45479. return this.hResolution / (2 * this.vResolution);
  45480. },
  45481. enumerable: true,
  45482. configurable: true
  45483. });
  45484. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45485. get: function () {
  45486. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45487. },
  45488. enumerable: true,
  45489. configurable: true
  45490. });
  45491. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45492. get: function () {
  45493. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45494. var h = (4 * meters) / this.hScreenSize;
  45495. return BABYLON.Matrix.Translation(h, 0, 0);
  45496. },
  45497. enumerable: true,
  45498. configurable: true
  45499. });
  45500. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45501. get: function () {
  45502. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45503. var h = (4 * meters) / this.hScreenSize;
  45504. return BABYLON.Matrix.Translation(-h, 0, 0);
  45505. },
  45506. enumerable: true,
  45507. configurable: true
  45508. });
  45509. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45510. get: function () {
  45511. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45512. },
  45513. enumerable: true,
  45514. configurable: true
  45515. });
  45516. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45517. get: function () {
  45518. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45519. },
  45520. enumerable: true,
  45521. configurable: true
  45522. });
  45523. VRCameraMetrics.GetDefault = function () {
  45524. var result = new VRCameraMetrics();
  45525. result.hResolution = 1280;
  45526. result.vResolution = 800;
  45527. result.hScreenSize = 0.149759993;
  45528. result.vScreenSize = 0.0935999975;
  45529. result.vScreenCenter = 0.0467999987;
  45530. result.eyeToScreenDistance = 0.0410000011;
  45531. result.lensSeparationDistance = 0.0635000020;
  45532. result.interpupillaryDistance = 0.0640000030;
  45533. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45534. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45535. result.postProcessScaleFactor = 1.714605507808412;
  45536. result.lensCenterOffset = 0.151976421;
  45537. return result;
  45538. };
  45539. return VRCameraMetrics;
  45540. }());
  45541. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45542. })(BABYLON || (BABYLON = {}));
  45543. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45544. var BABYLON;
  45545. (function (BABYLON) {
  45546. var WebVRFreeCamera = (function (_super) {
  45547. __extends(WebVRFreeCamera, _super);
  45548. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45549. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45550. if (webVROptions === void 0) { webVROptions = {}; }
  45551. var _this = _super.call(this, name, position, scene) || this;
  45552. _this.webVROptions = webVROptions;
  45553. _this._vrDevice = null;
  45554. _this._cacheState = null;
  45555. _this._vrEnabled = false;
  45556. _this._attached = false;
  45557. //using the position provided as the current position offset
  45558. _this._positionOffset = position;
  45559. //enable VR
  45560. _this.getEngine().initWebVR();
  45561. if (!_this.getEngine().vrDisplaysPromise) {
  45562. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45563. }
  45564. else {
  45565. //TODO get the metrics updated using the device's eye parameters!
  45566. //TODO also check that the device has the right capabilities!
  45567. _this._frameData = new VRFrameData();
  45568. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45569. if (devices.length > 0) {
  45570. _this._vrEnabled = true;
  45571. if (_this.webVROptions.displayName) {
  45572. var found = devices.some(function (device) {
  45573. if (device.displayName === _this.webVROptions.displayName) {
  45574. _this._vrDevice = device;
  45575. return true;
  45576. }
  45577. else {
  45578. return false;
  45579. }
  45580. });
  45581. if (!found) {
  45582. _this._vrDevice = devices[0];
  45583. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45584. }
  45585. }
  45586. else {
  45587. //choose the first one
  45588. _this._vrDevice = devices[0];
  45589. }
  45590. //reset the rig parameters.
  45591. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45592. if (_this._attached) {
  45593. _this.getEngine().enableVR(_this._vrDevice);
  45594. }
  45595. }
  45596. else {
  45597. BABYLON.Tools.Error("No WebVR devices found!");
  45598. }
  45599. });
  45600. }
  45601. _this.rotationQuaternion = new BABYLON.Quaternion();
  45602. _this._quaternionCache = new BABYLON.Quaternion();
  45603. return _this;
  45604. }
  45605. WebVRFreeCamera.prototype._checkInputs = function () {
  45606. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45607. var currentPost = this._frameData.pose;
  45608. //make sure we have data
  45609. if (currentPost && currentPost.orientation) {
  45610. this._cacheState = currentPost;
  45611. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45612. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45613. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45614. //scale the position accordingly
  45615. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45616. //add the position offset
  45617. this.position.addInPlace(this._positionOffset);
  45618. }
  45619. }
  45620. }
  45621. _super.prototype._checkInputs.call(this);
  45622. };
  45623. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45624. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45625. this._attached = true;
  45626. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45627. if (this._vrEnabled) {
  45628. this.getEngine().enableVR(this._vrDevice);
  45629. }
  45630. };
  45631. WebVRFreeCamera.prototype.detachControl = function (element) {
  45632. _super.prototype.detachControl.call(this, element);
  45633. this._vrEnabled = false;
  45634. this._attached = false;
  45635. this.getEngine().disableVR();
  45636. };
  45637. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45638. //Backwards comp.
  45639. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45640. //this.getEngine().switchFullscreen(requestPointerlock);
  45641. };
  45642. WebVRFreeCamera.prototype.getClassName = function () {
  45643. return "WebVRFreeCamera";
  45644. };
  45645. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45646. //uses the vrDisplay's "resetPose()".
  45647. //pitch and roll won't be affected.
  45648. this._vrDevice.resetPose();
  45649. };
  45650. /**
  45651. *
  45652. * Set the position offset of the VR camera
  45653. * The offset will be added to the WebVR pose, after scaling it (if set).
  45654. *
  45655. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45656. *
  45657. * @memberOf WebVRFreeCamera
  45658. */
  45659. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45660. if (newPosition) {
  45661. this._positionOffset = newPosition;
  45662. }
  45663. else {
  45664. this._positionOffset.copyFrom(this.position);
  45665. }
  45666. };
  45667. return WebVRFreeCamera;
  45668. }(BABYLON.FreeCamera));
  45669. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45670. })(BABYLON || (BABYLON = {}));
  45671. //# sourceMappingURL=babylon.webVRCamera.js.map
  45672. var BABYLON;
  45673. (function (BABYLON) {
  45674. // Standard optimizations
  45675. var SceneOptimization = (function () {
  45676. function SceneOptimization(priority) {
  45677. if (priority === void 0) { priority = 0; }
  45678. this.priority = priority;
  45679. this.apply = function (scene) {
  45680. return true; // Return true if everything that can be done was applied
  45681. };
  45682. }
  45683. return SceneOptimization;
  45684. }());
  45685. BABYLON.SceneOptimization = SceneOptimization;
  45686. var TextureOptimization = (function (_super) {
  45687. __extends(TextureOptimization, _super);
  45688. function TextureOptimization(priority, maximumSize) {
  45689. if (priority === void 0) { priority = 0; }
  45690. if (maximumSize === void 0) { maximumSize = 1024; }
  45691. var _this = _super.call(this, priority) || this;
  45692. _this.priority = priority;
  45693. _this.maximumSize = maximumSize;
  45694. _this.apply = function (scene) {
  45695. var allDone = true;
  45696. for (var index = 0; index < scene.textures.length; index++) {
  45697. var texture = scene.textures[index];
  45698. if (!texture.canRescale) {
  45699. continue;
  45700. }
  45701. var currentSize = texture.getSize();
  45702. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45703. if (maxDimension > _this.maximumSize) {
  45704. texture.scale(0.5);
  45705. allDone = false;
  45706. }
  45707. }
  45708. return allDone;
  45709. };
  45710. return _this;
  45711. }
  45712. return TextureOptimization;
  45713. }(SceneOptimization));
  45714. BABYLON.TextureOptimization = TextureOptimization;
  45715. var HardwareScalingOptimization = (function (_super) {
  45716. __extends(HardwareScalingOptimization, _super);
  45717. function HardwareScalingOptimization(priority, maximumScale) {
  45718. if (priority === void 0) { priority = 0; }
  45719. if (maximumScale === void 0) { maximumScale = 2; }
  45720. var _this = _super.call(this, priority) || this;
  45721. _this.priority = priority;
  45722. _this.maximumScale = maximumScale;
  45723. _this._currentScale = 1;
  45724. _this.apply = function (scene) {
  45725. _this._currentScale++;
  45726. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45727. return _this._currentScale >= _this.maximumScale;
  45728. };
  45729. return _this;
  45730. }
  45731. return HardwareScalingOptimization;
  45732. }(SceneOptimization));
  45733. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45734. var ShadowsOptimization = (function (_super) {
  45735. __extends(ShadowsOptimization, _super);
  45736. function ShadowsOptimization() {
  45737. var _this = _super !== null && _super.apply(this, arguments) || this;
  45738. _this.apply = function (scene) {
  45739. scene.shadowsEnabled = false;
  45740. return true;
  45741. };
  45742. return _this;
  45743. }
  45744. return ShadowsOptimization;
  45745. }(SceneOptimization));
  45746. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45747. var PostProcessesOptimization = (function (_super) {
  45748. __extends(PostProcessesOptimization, _super);
  45749. function PostProcessesOptimization() {
  45750. var _this = _super !== null && _super.apply(this, arguments) || this;
  45751. _this.apply = function (scene) {
  45752. scene.postProcessesEnabled = false;
  45753. return true;
  45754. };
  45755. return _this;
  45756. }
  45757. return PostProcessesOptimization;
  45758. }(SceneOptimization));
  45759. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45760. var LensFlaresOptimization = (function (_super) {
  45761. __extends(LensFlaresOptimization, _super);
  45762. function LensFlaresOptimization() {
  45763. var _this = _super !== null && _super.apply(this, arguments) || this;
  45764. _this.apply = function (scene) {
  45765. scene.lensFlaresEnabled = false;
  45766. return true;
  45767. };
  45768. return _this;
  45769. }
  45770. return LensFlaresOptimization;
  45771. }(SceneOptimization));
  45772. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45773. var ParticlesOptimization = (function (_super) {
  45774. __extends(ParticlesOptimization, _super);
  45775. function ParticlesOptimization() {
  45776. var _this = _super !== null && _super.apply(this, arguments) || this;
  45777. _this.apply = function (scene) {
  45778. scene.particlesEnabled = false;
  45779. return true;
  45780. };
  45781. return _this;
  45782. }
  45783. return ParticlesOptimization;
  45784. }(SceneOptimization));
  45785. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45786. var RenderTargetsOptimization = (function (_super) {
  45787. __extends(RenderTargetsOptimization, _super);
  45788. function RenderTargetsOptimization() {
  45789. var _this = _super !== null && _super.apply(this, arguments) || this;
  45790. _this.apply = function (scene) {
  45791. scene.renderTargetsEnabled = false;
  45792. return true;
  45793. };
  45794. return _this;
  45795. }
  45796. return RenderTargetsOptimization;
  45797. }(SceneOptimization));
  45798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45799. var MergeMeshesOptimization = (function (_super) {
  45800. __extends(MergeMeshesOptimization, _super);
  45801. function MergeMeshesOptimization() {
  45802. var _this = _super !== null && _super.apply(this, arguments) || this;
  45803. _this._canBeMerged = function (abstractMesh) {
  45804. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45805. return false;
  45806. }
  45807. var mesh = abstractMesh;
  45808. if (!mesh.isVisible || !mesh.isEnabled()) {
  45809. return false;
  45810. }
  45811. if (mesh.instances.length > 0) {
  45812. return false;
  45813. }
  45814. if (mesh.skeleton || mesh.hasLODLevels) {
  45815. return false;
  45816. }
  45817. if (mesh.parent) {
  45818. return false;
  45819. }
  45820. return true;
  45821. };
  45822. _this.apply = function (scene, updateSelectionTree) {
  45823. var globalPool = scene.meshes.slice(0);
  45824. var globalLength = globalPool.length;
  45825. for (var index = 0; index < globalLength; index++) {
  45826. var currentPool = new Array();
  45827. var current = globalPool[index];
  45828. // Checks
  45829. if (!_this._canBeMerged(current)) {
  45830. continue;
  45831. }
  45832. currentPool.push(current);
  45833. // Find compatible meshes
  45834. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45835. var otherMesh = globalPool[subIndex];
  45836. if (!_this._canBeMerged(otherMesh)) {
  45837. continue;
  45838. }
  45839. if (otherMesh.material !== current.material) {
  45840. continue;
  45841. }
  45842. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45843. continue;
  45844. }
  45845. currentPool.push(otherMesh);
  45846. globalLength--;
  45847. globalPool.splice(subIndex, 1);
  45848. subIndex--;
  45849. }
  45850. if (currentPool.length < 2) {
  45851. continue;
  45852. }
  45853. // Merge meshes
  45854. BABYLON.Mesh.MergeMeshes(currentPool);
  45855. }
  45856. if (updateSelectionTree != undefined) {
  45857. if (updateSelectionTree) {
  45858. scene.createOrUpdateSelectionOctree();
  45859. }
  45860. }
  45861. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45862. scene.createOrUpdateSelectionOctree();
  45863. }
  45864. return true;
  45865. };
  45866. return _this;
  45867. }
  45868. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45869. get: function () {
  45870. return MergeMeshesOptimization._UpdateSelectionTree;
  45871. },
  45872. set: function (value) {
  45873. MergeMeshesOptimization._UpdateSelectionTree = value;
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. return MergeMeshesOptimization;
  45879. }(SceneOptimization));
  45880. MergeMeshesOptimization._UpdateSelectionTree = false;
  45881. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45882. // Options
  45883. var SceneOptimizerOptions = (function () {
  45884. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45885. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45886. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45887. this.targetFrameRate = targetFrameRate;
  45888. this.trackerDuration = trackerDuration;
  45889. this.optimizations = new Array();
  45890. }
  45891. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45892. var result = new SceneOptimizerOptions(targetFrameRate);
  45893. var priority = 0;
  45894. result.optimizations.push(new MergeMeshesOptimization(priority));
  45895. result.optimizations.push(new ShadowsOptimization(priority));
  45896. result.optimizations.push(new LensFlaresOptimization(priority));
  45897. // Next priority
  45898. priority++;
  45899. result.optimizations.push(new PostProcessesOptimization(priority));
  45900. result.optimizations.push(new ParticlesOptimization(priority));
  45901. // Next priority
  45902. priority++;
  45903. result.optimizations.push(new TextureOptimization(priority, 1024));
  45904. return result;
  45905. };
  45906. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45907. var result = new SceneOptimizerOptions(targetFrameRate);
  45908. var priority = 0;
  45909. result.optimizations.push(new MergeMeshesOptimization(priority));
  45910. result.optimizations.push(new ShadowsOptimization(priority));
  45911. result.optimizations.push(new LensFlaresOptimization(priority));
  45912. // Next priority
  45913. priority++;
  45914. result.optimizations.push(new PostProcessesOptimization(priority));
  45915. result.optimizations.push(new ParticlesOptimization(priority));
  45916. // Next priority
  45917. priority++;
  45918. result.optimizations.push(new TextureOptimization(priority, 512));
  45919. // Next priority
  45920. priority++;
  45921. result.optimizations.push(new RenderTargetsOptimization(priority));
  45922. // Next priority
  45923. priority++;
  45924. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45925. return result;
  45926. };
  45927. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45928. var result = new SceneOptimizerOptions(targetFrameRate);
  45929. var priority = 0;
  45930. result.optimizations.push(new MergeMeshesOptimization(priority));
  45931. result.optimizations.push(new ShadowsOptimization(priority));
  45932. result.optimizations.push(new LensFlaresOptimization(priority));
  45933. // Next priority
  45934. priority++;
  45935. result.optimizations.push(new PostProcessesOptimization(priority));
  45936. result.optimizations.push(new ParticlesOptimization(priority));
  45937. // Next priority
  45938. priority++;
  45939. result.optimizations.push(new TextureOptimization(priority, 256));
  45940. // Next priority
  45941. priority++;
  45942. result.optimizations.push(new RenderTargetsOptimization(priority));
  45943. // Next priority
  45944. priority++;
  45945. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45946. return result;
  45947. };
  45948. return SceneOptimizerOptions;
  45949. }());
  45950. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45951. // Scene optimizer tool
  45952. var SceneOptimizer = (function () {
  45953. function SceneOptimizer() {
  45954. }
  45955. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45956. // TODO: add an epsilon
  45957. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45958. if (onSuccess) {
  45959. onSuccess();
  45960. }
  45961. return;
  45962. }
  45963. // Apply current level of optimizations
  45964. var allDone = true;
  45965. var noOptimizationApplied = true;
  45966. for (var index = 0; index < options.optimizations.length; index++) {
  45967. var optimization = options.optimizations[index];
  45968. if (optimization.priority === currentPriorityLevel) {
  45969. noOptimizationApplied = false;
  45970. allDone = allDone && optimization.apply(scene);
  45971. }
  45972. }
  45973. // If no optimization was applied, this is a failure :(
  45974. if (noOptimizationApplied) {
  45975. if (onFailure) {
  45976. onFailure();
  45977. }
  45978. return;
  45979. }
  45980. // If all optimizations were done, move to next level
  45981. if (allDone) {
  45982. currentPriorityLevel++;
  45983. }
  45984. // Let's the system running for a specific amount of time before checking FPS
  45985. scene.executeWhenReady(function () {
  45986. setTimeout(function () {
  45987. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45988. }, options.trackerDuration);
  45989. });
  45990. };
  45991. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45992. if (!options) {
  45993. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45994. }
  45995. // Let's the system running for a specific amount of time before checking FPS
  45996. scene.executeWhenReady(function () {
  45997. setTimeout(function () {
  45998. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45999. }, options.trackerDuration);
  46000. });
  46001. };
  46002. return SceneOptimizer;
  46003. }());
  46004. BABYLON.SceneOptimizer = SceneOptimizer;
  46005. })(BABYLON || (BABYLON = {}));
  46006. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  46007. var BABYLON;
  46008. (function (BABYLON) {
  46009. var Internals;
  46010. (function (Internals) {
  46011. var MeshLODLevel = (function () {
  46012. function MeshLODLevel(distance, mesh) {
  46013. this.distance = distance;
  46014. this.mesh = mesh;
  46015. }
  46016. return MeshLODLevel;
  46017. }());
  46018. Internals.MeshLODLevel = MeshLODLevel;
  46019. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46020. })(BABYLON || (BABYLON = {}));
  46021. //# sourceMappingURL=babylon.meshLODLevel.js.map
  46022. var BABYLON;
  46023. (function (BABYLON) {
  46024. var RawTexture = (function (_super) {
  46025. __extends(RawTexture, _super);
  46026. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46027. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46028. if (invertY === void 0) { invertY = false; }
  46029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46030. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46031. _this.format = format;
  46032. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46033. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46034. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46035. return _this;
  46036. }
  46037. RawTexture.prototype.update = function (data) {
  46038. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46039. };
  46040. // Statics
  46041. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46043. if (invertY === void 0) { invertY = false; }
  46044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46045. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46046. };
  46047. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46048. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46049. if (invertY === void 0) { invertY = false; }
  46050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46052. };
  46053. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46054. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46055. if (invertY === void 0) { invertY = false; }
  46056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46057. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46058. };
  46059. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46060. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46061. if (invertY === void 0) { invertY = false; }
  46062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46063. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46064. };
  46065. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46066. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46067. if (invertY === void 0) { invertY = false; }
  46068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46069. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46070. };
  46071. return RawTexture;
  46072. }(BABYLON.Texture));
  46073. BABYLON.RawTexture = RawTexture;
  46074. })(BABYLON || (BABYLON = {}));
  46075. //# sourceMappingURL=babylon.rawTexture.js.map
  46076. var BABYLON;
  46077. (function (BABYLON) {
  46078. var IndexedVector2 = (function (_super) {
  46079. __extends(IndexedVector2, _super);
  46080. function IndexedVector2(original, index) {
  46081. var _this = _super.call(this, original.x, original.y) || this;
  46082. _this.index = index;
  46083. return _this;
  46084. }
  46085. return IndexedVector2;
  46086. }(BABYLON.Vector2));
  46087. var PolygonPoints = (function () {
  46088. function PolygonPoints() {
  46089. this.elements = new Array();
  46090. }
  46091. PolygonPoints.prototype.add = function (originalPoints) {
  46092. var _this = this;
  46093. var result = new Array();
  46094. originalPoints.forEach(function (point) {
  46095. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  46096. var newPoint = new IndexedVector2(point, _this.elements.length);
  46097. result.push(newPoint);
  46098. _this.elements.push(newPoint);
  46099. }
  46100. });
  46101. return result;
  46102. };
  46103. PolygonPoints.prototype.computeBounds = function () {
  46104. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  46105. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  46106. this.elements.forEach(function (point) {
  46107. // x
  46108. if (point.x < lmin.x) {
  46109. lmin.x = point.x;
  46110. }
  46111. else if (point.x > lmax.x) {
  46112. lmax.x = point.x;
  46113. }
  46114. // y
  46115. if (point.y < lmin.y) {
  46116. lmin.y = point.y;
  46117. }
  46118. else if (point.y > lmax.y) {
  46119. lmax.y = point.y;
  46120. }
  46121. });
  46122. return {
  46123. min: lmin,
  46124. max: lmax,
  46125. width: lmax.x - lmin.x,
  46126. height: lmax.y - lmin.y
  46127. };
  46128. };
  46129. return PolygonPoints;
  46130. }());
  46131. var Polygon = (function () {
  46132. function Polygon() {
  46133. }
  46134. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  46135. return [
  46136. new BABYLON.Vector2(xmin, ymin),
  46137. new BABYLON.Vector2(xmax, ymin),
  46138. new BABYLON.Vector2(xmax, ymax),
  46139. new BABYLON.Vector2(xmin, ymax)
  46140. ];
  46141. };
  46142. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  46143. if (cx === void 0) { cx = 0; }
  46144. if (cy === void 0) { cy = 0; }
  46145. if (numberOfSides === void 0) { numberOfSides = 32; }
  46146. var result = new Array();
  46147. var angle = 0;
  46148. var increment = (Math.PI * 2) / numberOfSides;
  46149. for (var i = 0; i < numberOfSides; i++) {
  46150. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  46151. angle -= increment;
  46152. }
  46153. return result;
  46154. };
  46155. Polygon.Parse = function (input) {
  46156. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  46157. var i, result = [];
  46158. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  46159. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  46160. }
  46161. return result;
  46162. };
  46163. Polygon.StartingAt = function (x, y) {
  46164. return BABYLON.Path2.StartingAt(x, y);
  46165. };
  46166. return Polygon;
  46167. }());
  46168. BABYLON.Polygon = Polygon;
  46169. var PolygonMeshBuilder = (function () {
  46170. function PolygonMeshBuilder(name, contours, scene) {
  46171. this._points = new PolygonPoints();
  46172. this._outlinepoints = new PolygonPoints();
  46173. this._holes = [];
  46174. this._epoints = new Array();
  46175. this._eholes = new Array();
  46176. this._name = name;
  46177. this._scene = scene;
  46178. var points;
  46179. if (contours instanceof BABYLON.Path2) {
  46180. points = contours.getPoints();
  46181. }
  46182. else {
  46183. points = contours;
  46184. }
  46185. this._addToepoint(points);
  46186. this._points.add(points);
  46187. this._outlinepoints.add(points);
  46188. }
  46189. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  46190. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  46191. var p = points_1[_i];
  46192. this._epoints.push(p.x, p.y);
  46193. }
  46194. };
  46195. PolygonMeshBuilder.prototype.addHole = function (hole) {
  46196. this._points.add(hole);
  46197. var holepoints = new PolygonPoints();
  46198. holepoints.add(hole);
  46199. this._holes.push(holepoints);
  46200. this._eholes.push(this._epoints.length / 2);
  46201. this._addToepoint(hole);
  46202. return this;
  46203. };
  46204. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  46205. var _this = this;
  46206. if (updatable === void 0) { updatable = false; }
  46207. var result = new BABYLON.Mesh(this._name, this._scene);
  46208. var normals = [];
  46209. var positions = [];
  46210. var uvs = [];
  46211. var bounds = this._points.computeBounds();
  46212. this._points.elements.forEach(function (p) {
  46213. normals.push(0, 1.0, 0);
  46214. positions.push(p.x, 0, p.y);
  46215. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  46216. });
  46217. var indices = [];
  46218. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  46219. for (var i = 0; i < res.length; i++) {
  46220. indices.push(res[i]);
  46221. }
  46222. if (depth > 0) {
  46223. var positionscount = (positions.length / 3); //get the current pointcount
  46224. this._points.elements.forEach(function (p) {
  46225. normals.push(0, -1.0, 0);
  46226. positions.push(p.x, -depth, p.y);
  46227. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  46228. });
  46229. var totalCount = indices.length;
  46230. for (var i = 0; i < totalCount; i += 3) {
  46231. var i0 = indices[i + 0];
  46232. var i1 = indices[i + 1];
  46233. var i2 = indices[i + 2];
  46234. indices.push(i2 + positionscount);
  46235. indices.push(i1 + positionscount);
  46236. indices.push(i0 + positionscount);
  46237. }
  46238. //Add the sides
  46239. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  46240. this._holes.forEach(function (hole) {
  46241. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  46242. });
  46243. }
  46244. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  46245. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  46246. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  46247. result.setIndices(indices);
  46248. return result;
  46249. };
  46250. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  46251. var StartIndex = positions.length / 3;
  46252. var ulength = 0;
  46253. for (var i = 0; i < points.elements.length; i++) {
  46254. var p = points.elements[i];
  46255. var p1;
  46256. if ((i + 1) > points.elements.length - 1) {
  46257. p1 = points.elements[0];
  46258. }
  46259. else {
  46260. p1 = points.elements[i + 1];
  46261. }
  46262. positions.push(p.x, 0, p.y);
  46263. positions.push(p.x, -depth, p.y);
  46264. positions.push(p1.x, 0, p1.y);
  46265. positions.push(p1.x, -depth, p1.y);
  46266. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  46267. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  46268. var v3 = v2.subtract(v1);
  46269. var v4 = new BABYLON.Vector3(0, 1, 0);
  46270. var vn = BABYLON.Vector3.Cross(v3, v4);
  46271. vn = vn.normalize();
  46272. uvs.push(ulength / bounds.width, 0);
  46273. uvs.push(ulength / bounds.width, 1);
  46274. ulength += v3.length();
  46275. uvs.push((ulength / bounds.width), 0);
  46276. uvs.push((ulength / bounds.width), 1);
  46277. if (!flip) {
  46278. normals.push(-vn.x, -vn.y, -vn.z);
  46279. normals.push(-vn.x, -vn.y, -vn.z);
  46280. normals.push(-vn.x, -vn.y, -vn.z);
  46281. normals.push(-vn.x, -vn.y, -vn.z);
  46282. indices.push(StartIndex);
  46283. indices.push(StartIndex + 1);
  46284. indices.push(StartIndex + 2);
  46285. indices.push(StartIndex + 1);
  46286. indices.push(StartIndex + 3);
  46287. indices.push(StartIndex + 2);
  46288. }
  46289. else {
  46290. normals.push(vn.x, vn.y, vn.z);
  46291. normals.push(vn.x, vn.y, vn.z);
  46292. normals.push(vn.x, vn.y, vn.z);
  46293. normals.push(vn.x, vn.y, vn.z);
  46294. indices.push(StartIndex);
  46295. indices.push(StartIndex + 2);
  46296. indices.push(StartIndex + 1);
  46297. indices.push(StartIndex + 1);
  46298. indices.push(StartIndex + 2);
  46299. indices.push(StartIndex + 3);
  46300. }
  46301. StartIndex += 4;
  46302. }
  46303. ;
  46304. };
  46305. return PolygonMeshBuilder;
  46306. }());
  46307. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  46308. })(BABYLON || (BABYLON = {}));
  46309. //# sourceMappingURL=babylon.polygonMesh.js.map
  46310. var BABYLON;
  46311. (function (BABYLON) {
  46312. var Octree = (function () {
  46313. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  46314. if (maxDepth === void 0) { maxDepth = 2; }
  46315. this.maxDepth = maxDepth;
  46316. this.dynamicContent = new Array();
  46317. this._maxBlockCapacity = maxBlockCapacity || 64;
  46318. this._selectionContent = new BABYLON.SmartArray(1024);
  46319. this._creationFunc = creationFunc;
  46320. }
  46321. // Methods
  46322. Octree.prototype.update = function (worldMin, worldMax, entries) {
  46323. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  46324. };
  46325. Octree.prototype.addMesh = function (entry) {
  46326. for (var index = 0; index < this.blocks.length; index++) {
  46327. var block = this.blocks[index];
  46328. block.addEntry(entry);
  46329. }
  46330. };
  46331. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  46332. this._selectionContent.reset();
  46333. for (var index = 0; index < this.blocks.length; index++) {
  46334. var block = this.blocks[index];
  46335. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  46336. }
  46337. if (allowDuplicate) {
  46338. this._selectionContent.concat(this.dynamicContent);
  46339. }
  46340. else {
  46341. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46342. }
  46343. return this._selectionContent;
  46344. };
  46345. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  46346. this._selectionContent.reset();
  46347. for (var index = 0; index < this.blocks.length; index++) {
  46348. var block = this.blocks[index];
  46349. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  46350. }
  46351. if (allowDuplicate) {
  46352. this._selectionContent.concat(this.dynamicContent);
  46353. }
  46354. else {
  46355. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46356. }
  46357. return this._selectionContent;
  46358. };
  46359. Octree.prototype.intersectsRay = function (ray) {
  46360. this._selectionContent.reset();
  46361. for (var index = 0; index < this.blocks.length; index++) {
  46362. var block = this.blocks[index];
  46363. block.intersectsRay(ray, this._selectionContent);
  46364. }
  46365. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46366. return this._selectionContent;
  46367. };
  46368. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46369. target.blocks = new Array();
  46370. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46371. // Segmenting space
  46372. for (var x = 0; x < 2; x++) {
  46373. for (var y = 0; y < 2; y++) {
  46374. for (var z = 0; z < 2; z++) {
  46375. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46376. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46377. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46378. block.addEntries(entries);
  46379. target.blocks.push(block);
  46380. }
  46381. }
  46382. }
  46383. };
  46384. return Octree;
  46385. }());
  46386. Octree.CreationFuncForMeshes = function (entry, block) {
  46387. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46388. block.entries.push(entry);
  46389. }
  46390. };
  46391. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46392. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46393. block.entries.push(entry);
  46394. }
  46395. };
  46396. BABYLON.Octree = Octree;
  46397. })(BABYLON || (BABYLON = {}));
  46398. //# sourceMappingURL=babylon.octree.js.map
  46399. var BABYLON;
  46400. (function (BABYLON) {
  46401. var OctreeBlock = (function () {
  46402. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46403. this.entries = new Array();
  46404. this._boundingVectors = new Array();
  46405. this._capacity = capacity;
  46406. this._depth = depth;
  46407. this._maxDepth = maxDepth;
  46408. this._creationFunc = creationFunc;
  46409. this._minPoint = minPoint;
  46410. this._maxPoint = maxPoint;
  46411. this._boundingVectors.push(minPoint.clone());
  46412. this._boundingVectors.push(maxPoint.clone());
  46413. this._boundingVectors.push(minPoint.clone());
  46414. this._boundingVectors[2].x = maxPoint.x;
  46415. this._boundingVectors.push(minPoint.clone());
  46416. this._boundingVectors[3].y = maxPoint.y;
  46417. this._boundingVectors.push(minPoint.clone());
  46418. this._boundingVectors[4].z = maxPoint.z;
  46419. this._boundingVectors.push(maxPoint.clone());
  46420. this._boundingVectors[5].z = minPoint.z;
  46421. this._boundingVectors.push(maxPoint.clone());
  46422. this._boundingVectors[6].x = minPoint.x;
  46423. this._boundingVectors.push(maxPoint.clone());
  46424. this._boundingVectors[7].y = minPoint.y;
  46425. }
  46426. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46427. // Property
  46428. get: function () {
  46429. return this._capacity;
  46430. },
  46431. enumerable: true,
  46432. configurable: true
  46433. });
  46434. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46435. get: function () {
  46436. return this._minPoint;
  46437. },
  46438. enumerable: true,
  46439. configurable: true
  46440. });
  46441. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46442. get: function () {
  46443. return this._maxPoint;
  46444. },
  46445. enumerable: true,
  46446. configurable: true
  46447. });
  46448. // Methods
  46449. OctreeBlock.prototype.addEntry = function (entry) {
  46450. if (this.blocks) {
  46451. for (var index = 0; index < this.blocks.length; index++) {
  46452. var block = this.blocks[index];
  46453. block.addEntry(entry);
  46454. }
  46455. return;
  46456. }
  46457. this._creationFunc(entry, this);
  46458. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46459. this.createInnerBlocks();
  46460. }
  46461. };
  46462. OctreeBlock.prototype.addEntries = function (entries) {
  46463. for (var index = 0; index < entries.length; index++) {
  46464. var mesh = entries[index];
  46465. this.addEntry(mesh);
  46466. }
  46467. };
  46468. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46469. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46470. if (this.blocks) {
  46471. for (var index = 0; index < this.blocks.length; index++) {
  46472. var block = this.blocks[index];
  46473. block.select(frustumPlanes, selection, allowDuplicate);
  46474. }
  46475. return;
  46476. }
  46477. if (allowDuplicate) {
  46478. selection.concat(this.entries);
  46479. }
  46480. else {
  46481. selection.concatWithNoDuplicate(this.entries);
  46482. }
  46483. }
  46484. };
  46485. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46486. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46487. if (this.blocks) {
  46488. for (var index = 0; index < this.blocks.length; index++) {
  46489. var block = this.blocks[index];
  46490. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46491. }
  46492. return;
  46493. }
  46494. if (allowDuplicate) {
  46495. selection.concat(this.entries);
  46496. }
  46497. else {
  46498. selection.concatWithNoDuplicate(this.entries);
  46499. }
  46500. }
  46501. };
  46502. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46503. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46504. if (this.blocks) {
  46505. for (var index = 0; index < this.blocks.length; index++) {
  46506. var block = this.blocks[index];
  46507. block.intersectsRay(ray, selection);
  46508. }
  46509. return;
  46510. }
  46511. selection.concatWithNoDuplicate(this.entries);
  46512. }
  46513. };
  46514. OctreeBlock.prototype.createInnerBlocks = function () {
  46515. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46516. };
  46517. return OctreeBlock;
  46518. }());
  46519. BABYLON.OctreeBlock = OctreeBlock;
  46520. })(BABYLON || (BABYLON = {}));
  46521. //# sourceMappingURL=babylon.octreeBlock.js.map
  46522. var BABYLON;
  46523. (function (BABYLON) {
  46524. var BlurPostProcess = (function (_super) {
  46525. __extends(BlurPostProcess, _super);
  46526. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46528. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46529. _this.direction = direction;
  46530. _this.blurWidth = blurWidth;
  46531. _this.onApplyObservable.add(function (effect) {
  46532. effect.setFloat2("screenSize", _this.width, _this.height);
  46533. effect.setVector2("direction", _this.direction);
  46534. effect.setFloat("blurWidth", _this.blurWidth);
  46535. });
  46536. return _this;
  46537. }
  46538. return BlurPostProcess;
  46539. }(BABYLON.PostProcess));
  46540. BABYLON.BlurPostProcess = BlurPostProcess;
  46541. })(BABYLON || (BABYLON = {}));
  46542. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46543. var BABYLON;
  46544. (function (BABYLON) {
  46545. var RefractionPostProcess = (function (_super) {
  46546. __extends(RefractionPostProcess, _super);
  46547. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46548. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46549. _this.color = color;
  46550. _this.depth = depth;
  46551. _this.colorLevel = colorLevel;
  46552. _this.onActivateObservable.add(function (cam) {
  46553. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46554. });
  46555. _this.onApplyObservable.add(function (effect) {
  46556. effect.setColor3("baseColor", _this.color);
  46557. effect.setFloat("depth", _this.depth);
  46558. effect.setFloat("colorLevel", _this.colorLevel);
  46559. effect.setTexture("refractionSampler", _this._refRexture);
  46560. });
  46561. return _this;
  46562. }
  46563. // Methods
  46564. RefractionPostProcess.prototype.dispose = function (camera) {
  46565. if (this._refRexture) {
  46566. this._refRexture.dispose();
  46567. }
  46568. _super.prototype.dispose.call(this, camera);
  46569. };
  46570. return RefractionPostProcess;
  46571. }(BABYLON.PostProcess));
  46572. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46573. })(BABYLON || (BABYLON = {}));
  46574. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46575. var BABYLON;
  46576. (function (BABYLON) {
  46577. var BlackAndWhitePostProcess = (function (_super) {
  46578. __extends(BlackAndWhitePostProcess, _super);
  46579. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46580. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46581. }
  46582. return BlackAndWhitePostProcess;
  46583. }(BABYLON.PostProcess));
  46584. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46585. })(BABYLON || (BABYLON = {}));
  46586. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46587. var BABYLON;
  46588. (function (BABYLON) {
  46589. var ConvolutionPostProcess = (function (_super) {
  46590. __extends(ConvolutionPostProcess, _super);
  46591. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46592. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46593. _this.kernel = kernel;
  46594. _this.onApply = function (effect) {
  46595. effect.setFloat2("screenSize", _this.width, _this.height);
  46596. effect.setArray("kernel", _this.kernel);
  46597. };
  46598. return _this;
  46599. }
  46600. return ConvolutionPostProcess;
  46601. }(BABYLON.PostProcess));
  46602. // Statics
  46603. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46604. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46605. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46606. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46607. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46608. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46609. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46610. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46611. })(BABYLON || (BABYLON = {}));
  46612. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46613. var BABYLON;
  46614. (function (BABYLON) {
  46615. var FilterPostProcess = (function (_super) {
  46616. __extends(FilterPostProcess, _super);
  46617. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46618. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46619. _this.kernelMatrix = kernelMatrix;
  46620. _this.onApply = function (effect) {
  46621. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46622. };
  46623. return _this;
  46624. }
  46625. return FilterPostProcess;
  46626. }(BABYLON.PostProcess));
  46627. BABYLON.FilterPostProcess = FilterPostProcess;
  46628. })(BABYLON || (BABYLON = {}));
  46629. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46630. var BABYLON;
  46631. (function (BABYLON) {
  46632. var FxaaPostProcess = (function (_super) {
  46633. __extends(FxaaPostProcess, _super);
  46634. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46635. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46636. _this.onSizeChangedObservable.add(function () {
  46637. _this.texelWidth = 1.0 / _this.width;
  46638. _this.texelHeight = 1.0 / _this.height;
  46639. });
  46640. _this.onApplyObservable.add(function (effect) {
  46641. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46642. });
  46643. return _this;
  46644. }
  46645. return FxaaPostProcess;
  46646. }(BABYLON.PostProcess));
  46647. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46648. })(BABYLON || (BABYLON = {}));
  46649. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46650. var BABYLON;
  46651. (function (BABYLON) {
  46652. var StereoscopicInterlacePostProcess = (function (_super) {
  46653. __extends(StereoscopicInterlacePostProcess, _super);
  46654. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46655. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46656. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46657. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46658. _this.onSizeChangedObservable.add(function () {
  46659. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46660. });
  46661. _this.onApplyObservable.add(function (effect) {
  46662. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46663. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46664. });
  46665. return _this;
  46666. }
  46667. return StereoscopicInterlacePostProcess;
  46668. }(BABYLON.PostProcess));
  46669. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46670. })(BABYLON || (BABYLON = {}));
  46671. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46672. var BABYLON;
  46673. (function (BABYLON) {
  46674. var LensFlare = (function () {
  46675. function LensFlare(size, position, color, imgUrl, system) {
  46676. this.size = size;
  46677. this.position = position;
  46678. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46679. this.dispose = function () {
  46680. if (this.texture) {
  46681. this.texture.dispose();
  46682. }
  46683. // Remove from scene
  46684. var index = this._system.lensFlares.indexOf(this);
  46685. this._system.lensFlares.splice(index, 1);
  46686. };
  46687. this.color = color || new BABYLON.Color3(1, 1, 1);
  46688. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46689. this._system = system;
  46690. system.lensFlares.push(this);
  46691. }
  46692. return LensFlare;
  46693. }());
  46694. BABYLON.LensFlare = LensFlare;
  46695. })(BABYLON || (BABYLON = {}));
  46696. //# sourceMappingURL=babylon.lensFlare.js.map
  46697. var BABYLON;
  46698. (function (BABYLON) {
  46699. var LensFlareSystem = (function () {
  46700. function LensFlareSystem(name, emitter, scene) {
  46701. this.name = name;
  46702. this.lensFlares = new Array();
  46703. this.borderLimit = 300;
  46704. this.viewportBorder = 0;
  46705. this.layerMask = 0x0FFFFFFF;
  46706. this._vertexBuffers = {};
  46707. this._isEnabled = true;
  46708. this._scene = scene;
  46709. this._emitter = emitter;
  46710. this.id = name;
  46711. scene.lensFlareSystems.push(this);
  46712. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46713. var engine = scene.getEngine();
  46714. // VBO
  46715. var vertices = [];
  46716. vertices.push(1, 1);
  46717. vertices.push(-1, 1);
  46718. vertices.push(-1, -1);
  46719. vertices.push(1, -1);
  46720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46721. // Indices
  46722. var indices = [];
  46723. indices.push(0);
  46724. indices.push(1);
  46725. indices.push(2);
  46726. indices.push(0);
  46727. indices.push(2);
  46728. indices.push(3);
  46729. this._indexBuffer = engine.createIndexBuffer(indices);
  46730. // Effects
  46731. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46732. }
  46733. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46734. get: function () {
  46735. return this._isEnabled;
  46736. },
  46737. set: function (value) {
  46738. this._isEnabled = value;
  46739. },
  46740. enumerable: true,
  46741. configurable: true
  46742. });
  46743. LensFlareSystem.prototype.getScene = function () {
  46744. return this._scene;
  46745. };
  46746. LensFlareSystem.prototype.getEmitter = function () {
  46747. return this._emitter;
  46748. };
  46749. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46750. this._emitter = newEmitter;
  46751. };
  46752. LensFlareSystem.prototype.getEmitterPosition = function () {
  46753. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46754. };
  46755. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46756. var position = this.getEmitterPosition();
  46757. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46758. this._positionX = position.x;
  46759. this._positionY = position.y;
  46760. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46761. if (this.viewportBorder > 0) {
  46762. globalViewport.x -= this.viewportBorder;
  46763. globalViewport.y -= this.viewportBorder;
  46764. globalViewport.width += this.viewportBorder * 2;
  46765. globalViewport.height += this.viewportBorder * 2;
  46766. position.x += this.viewportBorder;
  46767. position.y += this.viewportBorder;
  46768. this._positionX += this.viewportBorder;
  46769. this._positionY += this.viewportBorder;
  46770. }
  46771. if (position.z > 0) {
  46772. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46773. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46774. return true;
  46775. }
  46776. return true;
  46777. }
  46778. return false;
  46779. };
  46780. LensFlareSystem.prototype._isVisible = function () {
  46781. if (!this._isEnabled) {
  46782. return false;
  46783. }
  46784. var emitterPosition = this.getEmitterPosition();
  46785. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46786. var distance = direction.length();
  46787. direction.normalize();
  46788. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46789. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46790. return !pickInfo.hit || pickInfo.distance > distance;
  46791. };
  46792. LensFlareSystem.prototype.render = function () {
  46793. if (!this._effect.isReady())
  46794. return false;
  46795. var engine = this._scene.getEngine();
  46796. var viewport = this._scene.activeCamera.viewport;
  46797. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46798. // Position
  46799. if (!this.computeEffectivePosition(globalViewport)) {
  46800. return false;
  46801. }
  46802. // Visibility
  46803. if (!this._isVisible()) {
  46804. return false;
  46805. }
  46806. // Intensity
  46807. var awayX;
  46808. var awayY;
  46809. if (this._positionX < this.borderLimit + globalViewport.x) {
  46810. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46811. }
  46812. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46813. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46814. }
  46815. else {
  46816. awayX = 0;
  46817. }
  46818. if (this._positionY < this.borderLimit + globalViewport.y) {
  46819. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46820. }
  46821. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46822. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46823. }
  46824. else {
  46825. awayY = 0;
  46826. }
  46827. var away = (awayX > awayY) ? awayX : awayY;
  46828. away -= this.viewportBorder;
  46829. if (away > this.borderLimit) {
  46830. away = this.borderLimit;
  46831. }
  46832. var intensity = 1.0 - (away / this.borderLimit);
  46833. if (intensity < 0) {
  46834. return false;
  46835. }
  46836. if (intensity > 1.0) {
  46837. intensity = 1.0;
  46838. }
  46839. if (this.viewportBorder > 0) {
  46840. globalViewport.x += this.viewportBorder;
  46841. globalViewport.y += this.viewportBorder;
  46842. globalViewport.width -= this.viewportBorder * 2;
  46843. globalViewport.height -= this.viewportBorder * 2;
  46844. this._positionX -= this.viewportBorder;
  46845. this._positionY -= this.viewportBorder;
  46846. }
  46847. // Position
  46848. var centerX = globalViewport.x + globalViewport.width / 2;
  46849. var centerY = globalViewport.y + globalViewport.height / 2;
  46850. var distX = centerX - this._positionX;
  46851. var distY = centerY - this._positionY;
  46852. // Effects
  46853. engine.enableEffect(this._effect);
  46854. engine.setState(false);
  46855. engine.setDepthBuffer(false);
  46856. // VBOs
  46857. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46858. // Flares
  46859. for (var index = 0; index < this.lensFlares.length; index++) {
  46860. var flare = this.lensFlares[index];
  46861. engine.setAlphaMode(flare.alphaMode);
  46862. var x = centerX - (distX * flare.position);
  46863. var y = centerY - (distY * flare.position);
  46864. var cw = flare.size;
  46865. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46866. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46867. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46868. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46869. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46870. // Texture
  46871. this._effect.setTexture("textureSampler", flare.texture);
  46872. // Color
  46873. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46874. // Draw order
  46875. engine.draw(true, 0, 6);
  46876. }
  46877. engine.setDepthBuffer(true);
  46878. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46879. return true;
  46880. };
  46881. LensFlareSystem.prototype.dispose = function () {
  46882. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46883. if (vertexBuffer) {
  46884. vertexBuffer.dispose();
  46885. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46886. }
  46887. if (this._indexBuffer) {
  46888. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46889. this._indexBuffer = null;
  46890. }
  46891. while (this.lensFlares.length) {
  46892. this.lensFlares[0].dispose();
  46893. }
  46894. // Remove from scene
  46895. var index = this._scene.lensFlareSystems.indexOf(this);
  46896. this._scene.lensFlareSystems.splice(index, 1);
  46897. };
  46898. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46899. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46900. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46901. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46902. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46903. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46904. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46905. var parsedFlare = parsedLensFlareSystem.flares[index];
  46906. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46907. }
  46908. return lensFlareSystem;
  46909. };
  46910. LensFlareSystem.prototype.serialize = function () {
  46911. var serializationObject = {};
  46912. serializationObject.id = this.id;
  46913. serializationObject.name = this.name;
  46914. serializationObject.emitterId = this.getEmitter().id;
  46915. serializationObject.borderLimit = this.borderLimit;
  46916. serializationObject.flares = [];
  46917. for (var index = 0; index < this.lensFlares.length; index++) {
  46918. var flare = this.lensFlares[index];
  46919. serializationObject.flares.push({
  46920. size: flare.size,
  46921. position: flare.position,
  46922. color: flare.color.asArray(),
  46923. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46924. });
  46925. }
  46926. return serializationObject;
  46927. };
  46928. return LensFlareSystem;
  46929. }());
  46930. BABYLON.LensFlareSystem = LensFlareSystem;
  46931. })(BABYLON || (BABYLON = {}));
  46932. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46933. var BABYLON;
  46934. (function (BABYLON) {
  46935. // We're mainly based on the logic defined into the FreeCamera code
  46936. var DeviceOrientationCamera = (function (_super) {
  46937. __extends(DeviceOrientationCamera, _super);
  46938. function DeviceOrientationCamera(name, position, scene) {
  46939. var _this = _super.call(this, name, position, scene) || this;
  46940. _this._quaternionCache = new BABYLON.Quaternion();
  46941. _this.inputs.addDeviceOrientation();
  46942. return _this;
  46943. }
  46944. DeviceOrientationCamera.prototype.getClassName = function () {
  46945. return "DeviceOrientationCamera";
  46946. };
  46947. DeviceOrientationCamera.prototype._checkInputs = function () {
  46948. _super.prototype._checkInputs.call(this);
  46949. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46950. if (this._initialQuaternion) {
  46951. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46952. }
  46953. };
  46954. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46955. var _this = this;
  46956. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46957. //can only work if this camera has a rotation quaternion already.
  46958. if (!this.rotationQuaternion)
  46959. return;
  46960. if (!this._initialQuaternion) {
  46961. this._initialQuaternion = new BABYLON.Quaternion();
  46962. }
  46963. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46964. ['x', 'y', 'z'].forEach(function (axisName) {
  46965. if (!axis[axisName]) {
  46966. _this._initialQuaternion[axisName] = 0;
  46967. }
  46968. else {
  46969. _this._initialQuaternion[axisName] *= -1;
  46970. }
  46971. });
  46972. this._initialQuaternion.normalize();
  46973. //force rotation update
  46974. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46975. };
  46976. return DeviceOrientationCamera;
  46977. }(BABYLON.FreeCamera));
  46978. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46979. })(BABYLON || (BABYLON = {}));
  46980. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46981. var BABYLON;
  46982. (function (BABYLON) {
  46983. var VRDeviceOrientationFreeCamera = (function (_super) {
  46984. __extends(VRDeviceOrientationFreeCamera, _super);
  46985. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46986. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46987. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46988. var _this = _super.call(this, name, position, scene) || this;
  46989. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46990. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46991. return _this;
  46992. }
  46993. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46994. return "VRDeviceOrientationFreeCamera";
  46995. };
  46996. return VRDeviceOrientationFreeCamera;
  46997. }(BABYLON.DeviceOrientationCamera));
  46998. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46999. var VRDeviceOrientationGamepadCamera = (function (_super) {
  47000. __extends(VRDeviceOrientationGamepadCamera, _super);
  47001. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  47002. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47003. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  47004. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  47005. _this.inputs.addGamepad();
  47006. return _this;
  47007. }
  47008. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  47009. return "VRDeviceOrientationGamepadCamera";
  47010. };
  47011. return VRDeviceOrientationGamepadCamera;
  47012. }(VRDeviceOrientationFreeCamera));
  47013. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  47014. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  47015. __extends(VRDeviceOrientationArcRotateCamera, _super);
  47016. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  47017. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47018. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  47019. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  47020. vrCameraMetrics.compensateDistortion = compensateDistortion;
  47021. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  47022. _this.inputs.addVRDeviceOrientation();
  47023. return _this;
  47024. }
  47025. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  47026. return "VRDeviceOrientationArcRotateCamera";
  47027. };
  47028. return VRDeviceOrientationArcRotateCamera;
  47029. }(BABYLON.ArcRotateCamera));
  47030. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  47031. })(BABYLON || (BABYLON = {}));
  47032. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  47033. var BABYLON;
  47034. (function (BABYLON) {
  47035. // We're mainly based on the logic defined into the FreeCamera code
  47036. var UniversalCamera = (function (_super) {
  47037. __extends(UniversalCamera, _super);
  47038. //-- end properties for backward compatibility for inputs
  47039. function UniversalCamera(name, position, scene) {
  47040. var _this = _super.call(this, name, position, scene) || this;
  47041. _this.inputs.addGamepad();
  47042. return _this;
  47043. }
  47044. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  47045. //-- Begin properties for backward compatibility for inputs
  47046. get: function () {
  47047. var gamepad = this.inputs.attached["gamepad"];
  47048. if (gamepad)
  47049. return gamepad.gamepadAngularSensibility;
  47050. },
  47051. set: function (value) {
  47052. var gamepad = this.inputs.attached["gamepad"];
  47053. if (gamepad)
  47054. gamepad.gamepadAngularSensibility = value;
  47055. },
  47056. enumerable: true,
  47057. configurable: true
  47058. });
  47059. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  47060. get: function () {
  47061. var gamepad = this.inputs.attached["gamepad"];
  47062. if (gamepad)
  47063. return gamepad.gamepadMoveSensibility;
  47064. },
  47065. set: function (value) {
  47066. var gamepad = this.inputs.attached["gamepad"];
  47067. if (gamepad)
  47068. gamepad.gamepadMoveSensibility = value;
  47069. },
  47070. enumerable: true,
  47071. configurable: true
  47072. });
  47073. UniversalCamera.prototype.getClassName = function () {
  47074. return "UniversalCamera";
  47075. };
  47076. return UniversalCamera;
  47077. }(BABYLON.TouchCamera));
  47078. BABYLON.UniversalCamera = UniversalCamera;
  47079. })(BABYLON || (BABYLON = {}));
  47080. //# sourceMappingURL=babylon.universalCamera.js.map
  47081. var BABYLON;
  47082. (function (BABYLON) {
  47083. var Gamepads = (function () {
  47084. function Gamepads(ongamedpadconnected) {
  47085. var _this = this;
  47086. this.babylonGamepads = [];
  47087. this.oneGamepadConnected = false;
  47088. this.isMonitoring = false;
  47089. this.gamepadEventSupported = 'GamepadEvent' in window;
  47090. this.gamepadSupportAvailable = (navigator.getGamepads ||
  47091. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  47092. this._callbackGamepadConnected = ongamedpadconnected;
  47093. if (this.gamepadSupportAvailable) {
  47094. // Checking if the gamepad connected event is supported (like in Firefox)
  47095. if (this.gamepadEventSupported) {
  47096. this._onGamepadConnectedEvent = function (evt) {
  47097. _this._onGamepadConnected(evt);
  47098. };
  47099. this._onGamepadDisonnectedEvent = function (evt) {
  47100. _this._onGamepadDisconnected(evt);
  47101. };
  47102. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47103. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47104. }
  47105. else {
  47106. this._startMonitoringGamepads();
  47107. }
  47108. }
  47109. }
  47110. Gamepads.prototype.dispose = function () {
  47111. if (Gamepads.gamepadDOMInfo) {
  47112. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47113. }
  47114. if (this._onGamepadConnectedEvent) {
  47115. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47116. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47117. this._onGamepadConnectedEvent = null;
  47118. this._onGamepadDisonnectedEvent = null;
  47119. }
  47120. };
  47121. Gamepads.prototype._onGamepadConnected = function (evt) {
  47122. var newGamepad = this._addNewGamepad(evt.gamepad);
  47123. if (this._callbackGamepadConnected)
  47124. this._callbackGamepadConnected(newGamepad);
  47125. this._startMonitoringGamepads();
  47126. };
  47127. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47128. if (!this.oneGamepadConnected) {
  47129. this.oneGamepadConnected = true;
  47130. if (Gamepads.gamepadDOMInfo) {
  47131. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47132. Gamepads.gamepadDOMInfo = null;
  47133. }
  47134. }
  47135. var newGamepad;
  47136. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47137. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47138. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47139. }
  47140. else {
  47141. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47142. }
  47143. this.babylonGamepads.push(newGamepad);
  47144. return newGamepad;
  47145. };
  47146. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47147. // Remove the gamepad from the list of gamepads to monitor.
  47148. for (var i in this.babylonGamepads) {
  47149. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47150. this.babylonGamepads.splice(+i, 1);
  47151. break;
  47152. }
  47153. }
  47154. // If no gamepads are left, stop the polling loop.
  47155. if (this.babylonGamepads.length == 0) {
  47156. this._stopMonitoringGamepads();
  47157. }
  47158. };
  47159. Gamepads.prototype._startMonitoringGamepads = function () {
  47160. if (!this.isMonitoring) {
  47161. this.isMonitoring = true;
  47162. this._checkGamepadsStatus();
  47163. }
  47164. };
  47165. Gamepads.prototype._stopMonitoringGamepads = function () {
  47166. this.isMonitoring = false;
  47167. };
  47168. Gamepads.prototype._checkGamepadsStatus = function () {
  47169. var _this = this;
  47170. // updating gamepad objects
  47171. this._updateGamepadObjects();
  47172. for (var i in this.babylonGamepads) {
  47173. this.babylonGamepads[i].update();
  47174. }
  47175. if (this.isMonitoring) {
  47176. if (window.requestAnimationFrame) {
  47177. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47178. }
  47179. else if (window.mozRequestAnimationFrame) {
  47180. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47181. }
  47182. else if (window.webkitRequestAnimationFrame) {
  47183. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47184. }
  47185. }
  47186. };
  47187. // This function is called only on Chrome, which does not yet support
  47188. // connection/disconnection events, but requires you to monitor
  47189. // an array for changes.
  47190. Gamepads.prototype._updateGamepadObjects = function () {
  47191. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47192. for (var i = 0; i < gamepads.length; i++) {
  47193. if (gamepads[i]) {
  47194. if (!(gamepads[i].index in this.babylonGamepads)) {
  47195. var newGamepad = this._addNewGamepad(gamepads[i]);
  47196. if (this._callbackGamepadConnected) {
  47197. this._callbackGamepadConnected(newGamepad);
  47198. }
  47199. }
  47200. else {
  47201. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47202. }
  47203. }
  47204. }
  47205. };
  47206. return Gamepads;
  47207. }());
  47208. BABYLON.Gamepads = Gamepads;
  47209. var StickValues = (function () {
  47210. function StickValues(x, y) {
  47211. this.x = x;
  47212. this.y = y;
  47213. }
  47214. return StickValues;
  47215. }());
  47216. BABYLON.StickValues = StickValues;
  47217. var Gamepad = (function () {
  47218. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47219. if (leftStickX === void 0) { leftStickX = 0; }
  47220. if (leftStickY === void 0) { leftStickY = 1; }
  47221. if (rightStickX === void 0) { rightStickX = 2; }
  47222. if (rightStickY === void 0) { rightStickY = 3; }
  47223. this.id = id;
  47224. this.index = index;
  47225. this.browserGamepad = browserGamepad;
  47226. this._leftStickAxisX = leftStickX;
  47227. this._leftStickAxisY = leftStickY;
  47228. this._rightStickAxisX = rightStickX;
  47229. this._rightStickAxisY = rightStickY;
  47230. if (this.browserGamepad.axes.length >= 2) {
  47231. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47232. }
  47233. if (this.browserGamepad.axes.length >= 4) {
  47234. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47235. }
  47236. }
  47237. Gamepad.prototype.onleftstickchanged = function (callback) {
  47238. this._onleftstickchanged = callback;
  47239. };
  47240. Gamepad.prototype.onrightstickchanged = function (callback) {
  47241. this._onrightstickchanged = callback;
  47242. };
  47243. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47244. get: function () {
  47245. return this._leftStick;
  47246. },
  47247. set: function (newValues) {
  47248. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47249. this._onleftstickchanged(newValues);
  47250. }
  47251. this._leftStick = newValues;
  47252. },
  47253. enumerable: true,
  47254. configurable: true
  47255. });
  47256. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47257. get: function () {
  47258. return this._rightStick;
  47259. },
  47260. set: function (newValues) {
  47261. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47262. this._onrightstickchanged(newValues);
  47263. }
  47264. this._rightStick = newValues;
  47265. },
  47266. enumerable: true,
  47267. configurable: true
  47268. });
  47269. Gamepad.prototype.update = function () {
  47270. if (this._leftStick) {
  47271. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47272. }
  47273. if (this._rightStick) {
  47274. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47275. }
  47276. };
  47277. return Gamepad;
  47278. }());
  47279. BABYLON.Gamepad = Gamepad;
  47280. var GenericPad = (function (_super) {
  47281. __extends(GenericPad, _super);
  47282. function GenericPad(id, index, gamepad) {
  47283. var _this = _super.call(this, id, index, gamepad) || this;
  47284. _this.id = id;
  47285. _this.index = index;
  47286. _this.gamepad = gamepad;
  47287. _this._buttons = new Array(gamepad.buttons.length);
  47288. return _this;
  47289. }
  47290. GenericPad.prototype.onbuttondown = function (callback) {
  47291. this._onbuttondown = callback;
  47292. };
  47293. GenericPad.prototype.onbuttonup = function (callback) {
  47294. this._onbuttonup = callback;
  47295. };
  47296. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47297. if (newValue !== currentValue) {
  47298. if (this._onbuttondown && newValue === 1) {
  47299. this._onbuttondown(buttonIndex);
  47300. }
  47301. if (this._onbuttonup && newValue === 0) {
  47302. this._onbuttonup(buttonIndex);
  47303. }
  47304. }
  47305. return newValue;
  47306. };
  47307. GenericPad.prototype.update = function () {
  47308. _super.prototype.update.call(this);
  47309. for (var index = 0; index < this._buttons.length; index++) {
  47310. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47311. }
  47312. };
  47313. return GenericPad;
  47314. }(Gamepad));
  47315. BABYLON.GenericPad = GenericPad;
  47316. var Xbox360Button;
  47317. (function (Xbox360Button) {
  47318. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47319. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47320. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47321. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47322. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47323. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47324. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47325. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47326. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47327. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47328. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47329. var Xbox360Dpad;
  47330. (function (Xbox360Dpad) {
  47331. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47332. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47333. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47334. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47335. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47336. var Xbox360Pad = (function (_super) {
  47337. __extends(Xbox360Pad, _super);
  47338. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47339. if (xboxOne === void 0) { xboxOne = false; }
  47340. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47341. _this._leftTrigger = 0;
  47342. _this._rightTrigger = 0;
  47343. _this._buttonA = 0;
  47344. _this._buttonB = 0;
  47345. _this._buttonX = 0;
  47346. _this._buttonY = 0;
  47347. _this._buttonBack = 0;
  47348. _this._buttonStart = 0;
  47349. _this._buttonLB = 0;
  47350. _this._buttonRB = 0;
  47351. _this._buttonLeftStick = 0;
  47352. _this._buttonRightStick = 0;
  47353. _this._dPadUp = 0;
  47354. _this._dPadDown = 0;
  47355. _this._dPadLeft = 0;
  47356. _this._dPadRight = 0;
  47357. _this._isXboxOnePad = false;
  47358. _this._isXboxOnePad = xboxOne;
  47359. return _this;
  47360. }
  47361. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47362. this._onlefttriggerchanged = callback;
  47363. };
  47364. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47365. this._onrighttriggerchanged = callback;
  47366. };
  47367. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47368. get: function () {
  47369. return this._leftTrigger;
  47370. },
  47371. set: function (newValue) {
  47372. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47373. this._onlefttriggerchanged(newValue);
  47374. }
  47375. this._leftTrigger = newValue;
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47381. get: function () {
  47382. return this._rightTrigger;
  47383. },
  47384. set: function (newValue) {
  47385. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47386. this._onrighttriggerchanged(newValue);
  47387. }
  47388. this._rightTrigger = newValue;
  47389. },
  47390. enumerable: true,
  47391. configurable: true
  47392. });
  47393. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47394. this._onbuttondown = callback;
  47395. };
  47396. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47397. this._onbuttonup = callback;
  47398. };
  47399. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47400. this._ondpaddown = callback;
  47401. };
  47402. Xbox360Pad.prototype.ondpadup = function (callback) {
  47403. this._ondpadup = callback;
  47404. };
  47405. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47406. if (newValue !== currentValue) {
  47407. if (this._onbuttondown && newValue === 1) {
  47408. this._onbuttondown(buttonType);
  47409. }
  47410. if (this._onbuttonup && newValue === 0) {
  47411. this._onbuttonup(buttonType);
  47412. }
  47413. }
  47414. return newValue;
  47415. };
  47416. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47417. if (newValue !== currentValue) {
  47418. if (this._ondpaddown && newValue === 1) {
  47419. this._ondpaddown(buttonType);
  47420. }
  47421. if (this._ondpadup && newValue === 0) {
  47422. this._ondpadup(buttonType);
  47423. }
  47424. }
  47425. return newValue;
  47426. };
  47427. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47428. get: function () {
  47429. return this._buttonA;
  47430. },
  47431. set: function (value) {
  47432. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47433. },
  47434. enumerable: true,
  47435. configurable: true
  47436. });
  47437. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47438. get: function () {
  47439. return this._buttonB;
  47440. },
  47441. set: function (value) {
  47442. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47443. },
  47444. enumerable: true,
  47445. configurable: true
  47446. });
  47447. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47448. get: function () {
  47449. return this._buttonX;
  47450. },
  47451. set: function (value) {
  47452. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47453. },
  47454. enumerable: true,
  47455. configurable: true
  47456. });
  47457. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47458. get: function () {
  47459. return this._buttonY;
  47460. },
  47461. set: function (value) {
  47462. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47463. },
  47464. enumerable: true,
  47465. configurable: true
  47466. });
  47467. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47468. get: function () {
  47469. return this._buttonStart;
  47470. },
  47471. set: function (value) {
  47472. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47478. get: function () {
  47479. return this._buttonBack;
  47480. },
  47481. set: function (value) {
  47482. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47488. get: function () {
  47489. return this._buttonLB;
  47490. },
  47491. set: function (value) {
  47492. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47493. },
  47494. enumerable: true,
  47495. configurable: true
  47496. });
  47497. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47498. get: function () {
  47499. return this._buttonRB;
  47500. },
  47501. set: function (value) {
  47502. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47503. },
  47504. enumerable: true,
  47505. configurable: true
  47506. });
  47507. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47508. get: function () {
  47509. return this._buttonLeftStick;
  47510. },
  47511. set: function (value) {
  47512. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47513. },
  47514. enumerable: true,
  47515. configurable: true
  47516. });
  47517. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47518. get: function () {
  47519. return this._buttonRightStick;
  47520. },
  47521. set: function (value) {
  47522. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47523. },
  47524. enumerable: true,
  47525. configurable: true
  47526. });
  47527. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47528. get: function () {
  47529. return this._dPadUp;
  47530. },
  47531. set: function (value) {
  47532. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47538. get: function () {
  47539. return this._dPadDown;
  47540. },
  47541. set: function (value) {
  47542. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47548. get: function () {
  47549. return this._dPadLeft;
  47550. },
  47551. set: function (value) {
  47552. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47558. get: function () {
  47559. return this._dPadRight;
  47560. },
  47561. set: function (value) {
  47562. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Xbox360Pad.prototype.update = function () {
  47568. _super.prototype.update.call(this);
  47569. if (this._isXboxOnePad) {
  47570. this.buttonA = this.browserGamepad.buttons[0].value;
  47571. this.buttonB = this.browserGamepad.buttons[1].value;
  47572. this.buttonX = this.browserGamepad.buttons[2].value;
  47573. this.buttonY = this.browserGamepad.buttons[3].value;
  47574. this.buttonLB = this.browserGamepad.buttons[4].value;
  47575. this.buttonRB = this.browserGamepad.buttons[5].value;
  47576. this.leftTrigger = this.browserGamepad.axes[2];
  47577. this.rightTrigger = this.browserGamepad.axes[5];
  47578. this.buttonBack = this.browserGamepad.buttons[9].value;
  47579. this.buttonStart = this.browserGamepad.buttons[8].value;
  47580. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47581. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47582. this.dPadUp = this.browserGamepad.buttons[11].value;
  47583. this.dPadDown = this.browserGamepad.buttons[12].value;
  47584. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47585. this.dPadRight = this.browserGamepad.buttons[14].value;
  47586. }
  47587. else {
  47588. this.buttonA = this.browserGamepad.buttons[0].value;
  47589. this.buttonB = this.browserGamepad.buttons[1].value;
  47590. this.buttonX = this.browserGamepad.buttons[2].value;
  47591. this.buttonY = this.browserGamepad.buttons[3].value;
  47592. this.buttonLB = this.browserGamepad.buttons[4].value;
  47593. this.buttonRB = this.browserGamepad.buttons[5].value;
  47594. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47595. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47596. this.buttonBack = this.browserGamepad.buttons[8].value;
  47597. this.buttonStart = this.browserGamepad.buttons[9].value;
  47598. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47599. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47600. this.dPadUp = this.browserGamepad.buttons[12].value;
  47601. this.dPadDown = this.browserGamepad.buttons[13].value;
  47602. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47603. this.dPadRight = this.browserGamepad.buttons[15].value;
  47604. }
  47605. };
  47606. return Xbox360Pad;
  47607. }(Gamepad));
  47608. BABYLON.Xbox360Pad = Xbox360Pad;
  47609. })(BABYLON || (BABYLON = {}));
  47610. //# sourceMappingURL=babylon.gamepads.js.map
  47611. var BABYLON;
  47612. (function (BABYLON) {
  47613. // We're mainly based on the logic defined into the FreeCamera code
  47614. var GamepadCamera = (function (_super) {
  47615. __extends(GamepadCamera, _super);
  47616. //-- end properties for backward compatibility for inputs
  47617. function GamepadCamera(name, position, scene) {
  47618. var _this = this;
  47619. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47620. _this = _super.call(this, name, position, scene) || this;
  47621. return _this;
  47622. }
  47623. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47624. //-- Begin properties for backward compatibility for inputs
  47625. get: function () {
  47626. var gamepad = this.inputs.attached["gamepad"];
  47627. if (gamepad)
  47628. return gamepad.gamepadAngularSensibility;
  47629. },
  47630. set: function (value) {
  47631. var gamepad = this.inputs.attached["gamepad"];
  47632. if (gamepad)
  47633. gamepad.gamepadAngularSensibility = value;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47639. get: function () {
  47640. var gamepad = this.inputs.attached["gamepad"];
  47641. if (gamepad)
  47642. return gamepad.gamepadMoveSensibility;
  47643. },
  47644. set: function (value) {
  47645. var gamepad = this.inputs.attached["gamepad"];
  47646. if (gamepad)
  47647. gamepad.gamepadMoveSensibility = value;
  47648. },
  47649. enumerable: true,
  47650. configurable: true
  47651. });
  47652. GamepadCamera.prototype.getClassName = function () {
  47653. return "GamepadCamera";
  47654. };
  47655. return GamepadCamera;
  47656. }(BABYLON.UniversalCamera));
  47657. BABYLON.GamepadCamera = GamepadCamera;
  47658. })(BABYLON || (BABYLON = {}));
  47659. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47660. var BABYLON;
  47661. (function (BABYLON) {
  47662. var Analyser = (function () {
  47663. function Analyser(scene) {
  47664. this.SMOOTHING = 0.75;
  47665. this.FFT_SIZE = 512;
  47666. this.BARGRAPHAMPLITUDE = 256;
  47667. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47668. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47669. this._scene = scene;
  47670. this._audioEngine = BABYLON.Engine.audioEngine;
  47671. if (this._audioEngine.canUseWebAudio) {
  47672. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47673. this._webAudioAnalyser.minDecibels = -140;
  47674. this._webAudioAnalyser.maxDecibels = 0;
  47675. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47676. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47677. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47678. }
  47679. }
  47680. Analyser.prototype.getFrequencyBinCount = function () {
  47681. if (this._audioEngine.canUseWebAudio) {
  47682. return this._webAudioAnalyser.frequencyBinCount;
  47683. }
  47684. else {
  47685. return 0;
  47686. }
  47687. };
  47688. Analyser.prototype.getByteFrequencyData = function () {
  47689. if (this._audioEngine.canUseWebAudio) {
  47690. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47691. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47692. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47693. }
  47694. return this._byteFreqs;
  47695. };
  47696. Analyser.prototype.getByteTimeDomainData = function () {
  47697. if (this._audioEngine.canUseWebAudio) {
  47698. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47699. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47700. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47701. }
  47702. return this._byteTime;
  47703. };
  47704. Analyser.prototype.getFloatFrequencyData = function () {
  47705. if (this._audioEngine.canUseWebAudio) {
  47706. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47707. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47708. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47709. }
  47710. return this._floatFreqs;
  47711. };
  47712. Analyser.prototype.drawDebugCanvas = function () {
  47713. var _this = this;
  47714. if (this._audioEngine.canUseWebAudio) {
  47715. if (!this._debugCanvas) {
  47716. this._debugCanvas = document.createElement("canvas");
  47717. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47718. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47719. this._debugCanvas.style.position = "absolute";
  47720. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47721. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47722. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47723. document.body.appendChild(this._debugCanvas);
  47724. this._registerFunc = function () {
  47725. _this.drawDebugCanvas();
  47726. };
  47727. this._scene.registerBeforeRender(this._registerFunc);
  47728. }
  47729. if (this._registerFunc) {
  47730. var workingArray = this.getByteFrequencyData();
  47731. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47732. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47733. // Draw the frequency domain chart.
  47734. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47735. var value = workingArray[i];
  47736. var percent = value / this.BARGRAPHAMPLITUDE;
  47737. var height = this.DEBUGCANVASSIZE.height * percent;
  47738. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47739. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47740. var hue = i / this.getFrequencyBinCount() * 360;
  47741. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47742. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47743. }
  47744. }
  47745. }
  47746. };
  47747. Analyser.prototype.stopDebugCanvas = function () {
  47748. if (this._debugCanvas) {
  47749. this._scene.unregisterBeforeRender(this._registerFunc);
  47750. this._registerFunc = null;
  47751. document.body.removeChild(this._debugCanvas);
  47752. this._debugCanvas = null;
  47753. this._debugCanvasContext = null;
  47754. }
  47755. };
  47756. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47757. if (this._audioEngine.canUseWebAudio) {
  47758. inputAudioNode.connect(this._webAudioAnalyser);
  47759. this._webAudioAnalyser.connect(outputAudioNode);
  47760. }
  47761. };
  47762. Analyser.prototype.dispose = function () {
  47763. if (this._audioEngine.canUseWebAudio) {
  47764. this._webAudioAnalyser.disconnect();
  47765. }
  47766. };
  47767. return Analyser;
  47768. }());
  47769. BABYLON.Analyser = Analyser;
  47770. })(BABYLON || (BABYLON = {}));
  47771. //# sourceMappingURL=babylon.analyser.js.map
  47772. var BABYLON;
  47773. (function (BABYLON) {
  47774. var DepthRenderer = (function () {
  47775. function DepthRenderer(scene, type) {
  47776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47777. var _this = this;
  47778. this._viewMatrix = BABYLON.Matrix.Zero();
  47779. this._projectionMatrix = BABYLON.Matrix.Zero();
  47780. this._transformMatrix = BABYLON.Matrix.Zero();
  47781. this._worldViewProjection = BABYLON.Matrix.Zero();
  47782. this._scene = scene;
  47783. var engine = scene.getEngine();
  47784. // Render target
  47785. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47786. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47787. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47788. this._depthMap.refreshRate = 1;
  47789. this._depthMap.renderParticles = false;
  47790. this._depthMap.renderList = null;
  47791. // set default depth value to 1.0 (far away)
  47792. this._depthMap.onClearObservable.add(function (engine) {
  47793. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47794. });
  47795. // Custom render function
  47796. var renderSubMesh = function (subMesh) {
  47797. var mesh = subMesh.getRenderingMesh();
  47798. var scene = _this._scene;
  47799. var engine = scene.getEngine();
  47800. // Culling
  47801. engine.setState(subMesh.getMaterial().backFaceCulling);
  47802. // Managing instances
  47803. var batch = mesh._getInstancesRenderList(subMesh._id);
  47804. if (batch.mustReturn) {
  47805. return;
  47806. }
  47807. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47808. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47809. engine.enableEffect(_this._effect);
  47810. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47811. var material = subMesh.getMaterial();
  47812. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47813. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47814. // Alpha test
  47815. if (material && material.needAlphaTesting()) {
  47816. var alphaTexture = material.getAlphaTestTexture();
  47817. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47818. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47819. }
  47820. // Bones
  47821. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47822. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47823. }
  47824. // Draw
  47825. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47826. }
  47827. };
  47828. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47829. var index;
  47830. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47831. renderSubMesh(opaqueSubMeshes.data[index]);
  47832. }
  47833. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47834. renderSubMesh(alphaTestSubMeshes.data[index]);
  47835. }
  47836. };
  47837. }
  47838. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47839. var material = subMesh.getMaterial();
  47840. if (material.disableDepthWrite) {
  47841. return false;
  47842. }
  47843. var defines = [];
  47844. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47845. var mesh = subMesh.getMesh();
  47846. var scene = mesh.getScene();
  47847. // Alpha test
  47848. if (material && material.needAlphaTesting()) {
  47849. defines.push("#define ALPHATEST");
  47850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47851. attribs.push(BABYLON.VertexBuffer.UVKind);
  47852. defines.push("#define UV1");
  47853. }
  47854. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47855. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47856. defines.push("#define UV2");
  47857. }
  47858. }
  47859. // Bones
  47860. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47863. if (mesh.numBoneInfluencers > 4) {
  47864. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47865. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47866. }
  47867. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47868. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47869. }
  47870. else {
  47871. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47872. }
  47873. // Instances
  47874. if (useInstances) {
  47875. defines.push("#define INSTANCES");
  47876. attribs.push("world0");
  47877. attribs.push("world1");
  47878. attribs.push("world2");
  47879. attribs.push("world3");
  47880. }
  47881. // Get correct effect
  47882. var join = defines.join("\n");
  47883. if (this._cachedDefines !== join) {
  47884. this._cachedDefines = join;
  47885. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47886. }
  47887. return this._effect.isReady();
  47888. };
  47889. DepthRenderer.prototype.getDepthMap = function () {
  47890. return this._depthMap;
  47891. };
  47892. // Methods
  47893. DepthRenderer.prototype.dispose = function () {
  47894. this._depthMap.dispose();
  47895. };
  47896. return DepthRenderer;
  47897. }());
  47898. BABYLON.DepthRenderer = DepthRenderer;
  47899. })(BABYLON || (BABYLON = {}));
  47900. //# sourceMappingURL=babylon.depthRenderer.js.map
  47901. var BABYLON;
  47902. (function (BABYLON) {
  47903. var SSAORenderingPipeline = (function (_super) {
  47904. __extends(SSAORenderingPipeline, _super);
  47905. /**
  47906. * @constructor
  47907. * @param {string} name - The rendering pipeline name
  47908. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47909. * @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 }
  47910. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47911. */
  47912. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47913. var _this = _super.call(this, scene.getEngine(), name) || this;
  47914. // Members
  47915. /**
  47916. * The PassPostProcess id in the pipeline that contains the original scene color
  47917. * @type {string}
  47918. */
  47919. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47920. /**
  47921. * The SSAO PostProcess id in the pipeline
  47922. * @type {string}
  47923. */
  47924. _this.SSAORenderEffect = "SSAORenderEffect";
  47925. /**
  47926. * The horizontal blur PostProcess id in the pipeline
  47927. * @type {string}
  47928. */
  47929. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47930. /**
  47931. * The vertical blur PostProcess id in the pipeline
  47932. * @type {string}
  47933. */
  47934. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47935. /**
  47936. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47937. * @type {string}
  47938. */
  47939. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47940. /**
  47941. * The output strength of the SSAO post-process. Default value is 1.0.
  47942. * @type {number}
  47943. */
  47944. _this.totalStrength = 1.0;
  47945. /**
  47946. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47947. * @type {number}
  47948. */
  47949. _this.radius = 0.0001;
  47950. /**
  47951. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47952. * Must not be equal to fallOff and superior to fallOff.
  47953. * Default value is 0.975
  47954. * @type {number}
  47955. */
  47956. _this.area = 0.0075;
  47957. /**
  47958. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47959. * Must not be equal to area and inferior to area.
  47960. * Default value is 0.0
  47961. * @type {number}
  47962. */
  47963. _this.fallOff = 0.000001;
  47964. /**
  47965. * The base color of the SSAO post-process
  47966. * The final result is "base + ssao" between [0, 1]
  47967. * @type {number}
  47968. */
  47969. _this.base = 0.5;
  47970. _this._firstUpdate = true;
  47971. _this._scene = scene;
  47972. // Set up assets
  47973. _this._createRandomTexture();
  47974. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47975. var ssaoRatio = ratio.ssaoRatio || ratio;
  47976. var combineRatio = ratio.combineRatio || ratio;
  47977. _this._ratio = {
  47978. ssaoRatio: ssaoRatio,
  47979. combineRatio: combineRatio
  47980. };
  47981. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47982. _this._createSSAOPostProcess(ssaoRatio);
  47983. _this._createBlurPostProcess(ssaoRatio);
  47984. _this._createSSAOCombinePostProcess(combineRatio);
  47985. // Set up pipeline
  47986. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47987. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47988. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47989. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47990. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47991. // Finish
  47992. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47993. if (cameras)
  47994. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47995. return _this;
  47996. }
  47997. // Public Methods
  47998. /**
  47999. * Returns the horizontal blur PostProcess
  48000. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  48001. */
  48002. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  48003. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  48004. return null;
  48005. };
  48006. /**
  48007. * Returns the vertical blur PostProcess
  48008. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  48009. */
  48010. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  48011. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  48012. return null;
  48013. };
  48014. /**
  48015. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  48016. */
  48017. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48018. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48019. for (var i = 0; i < this._scene.cameras.length; i++) {
  48020. var camera = this._scene.cameras[i];
  48021. this._originalColorPostProcess.dispose(camera);
  48022. this._ssaoPostProcess.dispose(camera);
  48023. this._blurHPostProcess.dispose(camera);
  48024. this._blurVPostProcess.dispose(camera);
  48025. this._ssaoCombinePostProcess.dispose(camera);
  48026. }
  48027. this._randomTexture.dispose();
  48028. if (disableDepthRender)
  48029. this._scene.disableDepthRenderer();
  48030. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48031. _super.prototype.dispose.call(this);
  48032. };
  48033. // Private Methods
  48034. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  48035. var _this = this;
  48036. /*
  48037. var samplerOffsets = [
  48038. -8.0, -6.0, -4.0, -2.0,
  48039. 0.0,
  48040. 2.0, 4.0, 6.0, 8.0
  48041. ];
  48042. */
  48043. var samples = 16;
  48044. var samplerOffsets = [];
  48045. for (var i = -8; i < 8; i++) {
  48046. samplerOffsets.push(i * 2);
  48047. }
  48048. 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");
  48049. this._blurHPostProcess.onApply = function (effect) {
  48050. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  48051. effect.setTexture("depthSampler", _this._depthTexture);
  48052. if (_this._firstUpdate) {
  48053. effect.setArray("samplerOffsets", samplerOffsets);
  48054. }
  48055. };
  48056. 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");
  48057. this._blurVPostProcess.onApply = function (effect) {
  48058. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  48059. effect.setTexture("depthSampler", _this._depthTexture);
  48060. if (_this._firstUpdate) {
  48061. effect.setArray("samplerOffsets", samplerOffsets);
  48062. _this._firstUpdate = false;
  48063. }
  48064. };
  48065. };
  48066. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  48067. var _this = this;
  48068. var numSamples = 16;
  48069. var sampleSphere = [
  48070. 0.5381, 0.1856, -0.4319,
  48071. 0.1379, 0.2486, 0.4430,
  48072. 0.3371, 0.5679, -0.0057,
  48073. -0.6999, -0.0451, -0.0019,
  48074. 0.0689, -0.1598, -0.8547,
  48075. 0.0560, 0.0069, -0.1843,
  48076. -0.0146, 0.1402, 0.0762,
  48077. 0.0100, -0.1924, -0.0344,
  48078. -0.3577, -0.5301, -0.4358,
  48079. -0.3169, 0.1063, 0.0158,
  48080. 0.0103, -0.5869, 0.0046,
  48081. -0.0897, -0.4940, 0.3287,
  48082. 0.7119, -0.0154, -0.0918,
  48083. -0.0533, 0.0596, -0.5411,
  48084. 0.0352, -0.0631, 0.5460,
  48085. -0.4776, 0.2847, -0.0271
  48086. ];
  48087. var samplesFactor = 1.0 / numSamples;
  48088. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  48089. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  48090. "area", "fallOff", "base", "range", "viewport"
  48091. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  48092. var viewport = new BABYLON.Vector2(0, 0);
  48093. this._ssaoPostProcess.onApply = function (effect) {
  48094. if (_this._firstUpdate) {
  48095. effect.setArray3("sampleSphere", sampleSphere);
  48096. effect.setFloat("samplesFactor", samplesFactor);
  48097. effect.setFloat("randTextureTiles", 4.0);
  48098. }
  48099. effect.setFloat("totalStrength", _this.totalStrength);
  48100. effect.setFloat("radius", _this.radius);
  48101. effect.setFloat("area", _this.area);
  48102. effect.setFloat("fallOff", _this.fallOff);
  48103. effect.setFloat("base", _this.base);
  48104. effect.setTexture("textureSampler", _this._depthTexture);
  48105. effect.setTexture("randomSampler", _this._randomTexture);
  48106. };
  48107. };
  48108. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  48109. var _this = this;
  48110. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48111. this._ssaoCombinePostProcess.onApply = function (effect) {
  48112. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  48113. };
  48114. };
  48115. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  48116. var size = 512;
  48117. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48118. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48119. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48120. var context = this._randomTexture.getContext();
  48121. var rand = function (min, max) {
  48122. return Math.random() * (max - min) + min;
  48123. };
  48124. var randVector = BABYLON.Vector3.Zero();
  48125. for (var x = 0; x < size; x++) {
  48126. for (var y = 0; y < size; y++) {
  48127. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  48128. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  48129. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  48130. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  48131. context.fillRect(x, y, 1, 1);
  48132. }
  48133. }
  48134. this._randomTexture.update(false);
  48135. };
  48136. return SSAORenderingPipeline;
  48137. }(BABYLON.PostProcessRenderPipeline));
  48138. __decorate([
  48139. BABYLON.serialize()
  48140. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  48141. __decorate([
  48142. BABYLON.serialize()
  48143. ], SSAORenderingPipeline.prototype, "radius", void 0);
  48144. __decorate([
  48145. BABYLON.serialize()
  48146. ], SSAORenderingPipeline.prototype, "area", void 0);
  48147. __decorate([
  48148. BABYLON.serialize()
  48149. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], SSAORenderingPipeline.prototype, "base", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  48156. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  48157. })(BABYLON || (BABYLON = {}));
  48158. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  48159. var BABYLON;
  48160. (function (BABYLON) {
  48161. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48162. var VolumetricLightScatteringPostProcess = (function (_super) {
  48163. __extends(VolumetricLightScatteringPostProcess, _super);
  48164. /**
  48165. * @constructor
  48166. * @param {string} name - The post-process name
  48167. * @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)
  48168. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48169. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48170. * @param {number} samples - The post-process quality, default 100
  48171. * @param {number} samplingMode - The post-process filtering mode
  48172. * @param {BABYLON.Engine} engine - The babylon engine
  48173. * @param {boolean} reusable - If the post-process is reusable
  48174. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48175. */
  48176. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48177. if (samples === void 0) { samples = 100; }
  48178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48179. 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;
  48180. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48181. /**
  48182. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48183. * @type {Vector3}
  48184. */
  48185. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48186. /**
  48187. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48188. * @type {boolean}
  48189. */
  48190. _this.useCustomMeshPosition = false;
  48191. /**
  48192. * If the post-process should inverse the light scattering direction
  48193. * @type {boolean}
  48194. */
  48195. _this.invert = true;
  48196. /**
  48197. * Array containing the excluded meshes not rendered in the internal pass
  48198. */
  48199. _this.excludedMeshes = new Array();
  48200. /**
  48201. * Controls the overall intensity of the post-process
  48202. * @type {number}
  48203. */
  48204. _this.exposure = 0.3;
  48205. /**
  48206. * Dissipates each sample's contribution in range [0, 1]
  48207. * @type {number}
  48208. */
  48209. _this.decay = 0.96815;
  48210. /**
  48211. * Controls the overall intensity of each sample
  48212. * @type {number}
  48213. */
  48214. _this.weight = 0.58767;
  48215. /**
  48216. * Controls the density of each sample
  48217. * @type {number}
  48218. */
  48219. _this.density = 0.926;
  48220. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48221. var engine = scene.getEngine();
  48222. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48223. // Configure mesh
  48224. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48225. // Configure
  48226. _this._createPass(scene, ratio.passRatio || ratio);
  48227. _this.onActivate = function (camera) {
  48228. if (!_this.isSupported) {
  48229. _this.dispose(camera);
  48230. }
  48231. _this.onActivate = null;
  48232. };
  48233. _this.onApplyObservable.add(function (effect) {
  48234. _this._updateMeshScreenCoordinates(scene);
  48235. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48236. effect.setFloat("exposure", _this.exposure);
  48237. effect.setFloat("decay", _this.decay);
  48238. effect.setFloat("weight", _this.weight);
  48239. effect.setFloat("density", _this.density);
  48240. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48241. });
  48242. return _this;
  48243. }
  48244. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48245. get: function () {
  48246. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48247. return false;
  48248. },
  48249. set: function (useDiffuseColor) {
  48250. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48256. var mesh = subMesh.getMesh();
  48257. // Render this.mesh as default
  48258. if (mesh === this.mesh) {
  48259. return mesh.material.isReady(mesh);
  48260. }
  48261. var defines = [];
  48262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48263. var material = subMesh.getMaterial();
  48264. var needUV = false;
  48265. // Alpha test
  48266. if (material) {
  48267. if (material.needAlphaTesting()) {
  48268. defines.push("#define ALPHATEST");
  48269. }
  48270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48271. attribs.push(BABYLON.VertexBuffer.UVKind);
  48272. defines.push("#define UV1");
  48273. }
  48274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48276. defines.push("#define UV2");
  48277. }
  48278. }
  48279. // Bones
  48280. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48284. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48285. }
  48286. else {
  48287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48288. }
  48289. // Instances
  48290. if (useInstances) {
  48291. defines.push("#define INSTANCES");
  48292. attribs.push("world0");
  48293. attribs.push("world1");
  48294. attribs.push("world2");
  48295. attribs.push("world3");
  48296. }
  48297. // Get correct effect
  48298. var join = defines.join("\n");
  48299. if (this._cachedDefines !== join) {
  48300. this._cachedDefines = join;
  48301. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48302. }
  48303. return this._volumetricLightScatteringPass.isReady();
  48304. };
  48305. /**
  48306. * Sets the new light position for light scattering effect
  48307. * @param {BABYLON.Vector3} The new custom light position
  48308. */
  48309. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48310. this.customMeshPosition = position;
  48311. };
  48312. /**
  48313. * Returns the light position for light scattering effect
  48314. * @return {BABYLON.Vector3} The custom light position
  48315. */
  48316. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48317. return this.customMeshPosition;
  48318. };
  48319. /**
  48320. * Disposes the internal assets and detaches the post-process from the camera
  48321. */
  48322. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48323. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48324. if (rttIndex !== -1) {
  48325. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48326. }
  48327. this._volumetricLightScatteringRTT.dispose();
  48328. _super.prototype.dispose.call(this, camera);
  48329. };
  48330. /**
  48331. * Returns the render target texture used by the post-process
  48332. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48333. */
  48334. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48335. return this._volumetricLightScatteringRTT;
  48336. };
  48337. // Private methods
  48338. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48339. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48340. return true;
  48341. }
  48342. return false;
  48343. };
  48344. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48345. var _this = this;
  48346. var engine = scene.getEngine();
  48347. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48348. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48349. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48350. this._volumetricLightScatteringRTT.renderList = null;
  48351. this._volumetricLightScatteringRTT.renderParticles = false;
  48352. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48353. // Custom render function for submeshes
  48354. var renderSubMesh = function (subMesh) {
  48355. var mesh = subMesh.getRenderingMesh();
  48356. if (_this._meshExcluded(mesh)) {
  48357. return;
  48358. }
  48359. var scene = mesh.getScene();
  48360. var engine = scene.getEngine();
  48361. // Culling
  48362. engine.setState(subMesh.getMaterial().backFaceCulling);
  48363. // Managing instances
  48364. var batch = mesh._getInstancesRenderList(subMesh._id);
  48365. if (batch.mustReturn) {
  48366. return;
  48367. }
  48368. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48369. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48370. var effect = _this._volumetricLightScatteringPass;
  48371. if (mesh === _this.mesh) {
  48372. effect = subMesh.getMaterial().getEffect();
  48373. }
  48374. engine.enableEffect(effect);
  48375. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48376. if (mesh === _this.mesh) {
  48377. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48378. }
  48379. else {
  48380. var material = subMesh.getMaterial();
  48381. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48382. // Alpha test
  48383. if (material && material.needAlphaTesting()) {
  48384. var alphaTexture = material.getAlphaTestTexture();
  48385. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48386. if (alphaTexture) {
  48387. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48388. }
  48389. }
  48390. // Bones
  48391. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48392. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48393. }
  48394. }
  48395. // Draw
  48396. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48397. }
  48398. };
  48399. // Render target texture callbacks
  48400. var savedSceneClearColor;
  48401. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48402. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48403. savedSceneClearColor = scene.clearColor;
  48404. scene.clearColor = sceneClearColor;
  48405. });
  48406. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48407. scene.clearColor = savedSceneClearColor;
  48408. });
  48409. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48410. var engine = scene.getEngine();
  48411. var index;
  48412. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48413. renderSubMesh(opaqueSubMeshes.data[index]);
  48414. }
  48415. engine.setAlphaTesting(true);
  48416. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48417. renderSubMesh(alphaTestSubMeshes.data[index]);
  48418. }
  48419. engine.setAlphaTesting(false);
  48420. if (transparentSubMeshes.length) {
  48421. // Sort sub meshes
  48422. for (index = 0; index < transparentSubMeshes.length; index++) {
  48423. var submesh = transparentSubMeshes.data[index];
  48424. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48425. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48426. }
  48427. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48428. sortedArray.sort(function (a, b) {
  48429. // Alpha index first
  48430. if (a._alphaIndex > b._alphaIndex) {
  48431. return 1;
  48432. }
  48433. if (a._alphaIndex < b._alphaIndex) {
  48434. return -1;
  48435. }
  48436. // Then distance to camera
  48437. if (a._distanceToCamera < b._distanceToCamera) {
  48438. return 1;
  48439. }
  48440. if (a._distanceToCamera > b._distanceToCamera) {
  48441. return -1;
  48442. }
  48443. return 0;
  48444. });
  48445. // Render sub meshes
  48446. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48447. for (index = 0; index < sortedArray.length; index++) {
  48448. renderSubMesh(sortedArray[index]);
  48449. }
  48450. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48451. }
  48452. };
  48453. };
  48454. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48455. var transform = scene.getTransformMatrix();
  48456. var meshPosition;
  48457. if (this.useCustomMeshPosition) {
  48458. meshPosition = this.customMeshPosition;
  48459. }
  48460. else if (this.attachedNode) {
  48461. meshPosition = this.attachedNode.position;
  48462. }
  48463. else {
  48464. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48465. }
  48466. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48467. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48468. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48469. if (this.invert)
  48470. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48471. };
  48472. // Static methods
  48473. /**
  48474. * Creates a default mesh for the Volumeric Light Scattering post-process
  48475. * @param {string} The mesh name
  48476. * @param {BABYLON.Scene} The scene where to create the mesh
  48477. * @return {BABYLON.Mesh} the default mesh
  48478. */
  48479. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48480. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48481. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48482. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48483. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48484. mesh.material = material;
  48485. return mesh;
  48486. };
  48487. return VolumetricLightScatteringPostProcess;
  48488. }(BABYLON.PostProcess));
  48489. __decorate([
  48490. BABYLON.serializeAsVector3()
  48491. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48492. __decorate([
  48493. BABYLON.serialize()
  48494. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48495. __decorate([
  48496. BABYLON.serialize()
  48497. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48498. __decorate([
  48499. BABYLON.serializeAsMeshReference()
  48500. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48501. __decorate([
  48502. BABYLON.serialize()
  48503. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48504. __decorate([
  48505. BABYLON.serialize()
  48506. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48507. __decorate([
  48508. BABYLON.serialize()
  48509. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48510. __decorate([
  48511. BABYLON.serialize()
  48512. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48513. __decorate([
  48514. BABYLON.serialize()
  48515. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48516. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48517. })(BABYLON || (BABYLON = {}));
  48518. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48519. // BABYLON.JS Chromatic Aberration GLSL Shader
  48520. // Author: Olivier Guyot
  48521. // Separates very slightly R, G and B colors on the edges of the screen
  48522. // Inspired by Francois Tarlier & Martins Upitis
  48523. var BABYLON;
  48524. (function (BABYLON) {
  48525. var LensRenderingPipeline = (function (_super) {
  48526. __extends(LensRenderingPipeline, _super);
  48527. /**
  48528. * @constructor
  48529. *
  48530. * Effect parameters are as follow:
  48531. * {
  48532. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48533. * edge_blur: number; // from 0 to x (1 for realism)
  48534. * distortion: number; // from 0 to x (1 for realism)
  48535. * grain_amount: number; // from 0 to 1
  48536. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48537. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48538. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48539. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48540. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48541. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48542. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48543. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48544. * }
  48545. * Note: if an effect parameter is unset, effect is disabled
  48546. *
  48547. * @param {string} name - The rendering pipeline name
  48548. * @param {object} parameters - An object containing all parameters (see above)
  48549. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48550. * @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)
  48551. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48552. */
  48553. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48554. if (ratio === void 0) { ratio = 1.0; }
  48555. var _this = _super.call(this, scene.getEngine(), name) || this;
  48556. // Lens effects can be of the following:
  48557. // - chromatic aberration (slight shift of RGB colors)
  48558. // - blur on the edge of the lens
  48559. // - lens distortion
  48560. // - depth-of-field blur & highlights enhancing
  48561. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48562. // - grain effect (noise or custom texture)
  48563. // Two additional texture samplers are needed:
  48564. // - depth map (for depth-of-field)
  48565. // - grain texture
  48566. /**
  48567. * The chromatic aberration PostProcess id in the pipeline
  48568. * @type {string}
  48569. */
  48570. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48571. /**
  48572. * The highlights enhancing PostProcess id in the pipeline
  48573. * @type {string}
  48574. */
  48575. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48576. /**
  48577. * The depth-of-field PostProcess id in the pipeline
  48578. * @type {string}
  48579. */
  48580. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48581. _this._scene = scene;
  48582. // Fetch texture samplers
  48583. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48584. if (parameters.grain_texture) {
  48585. _this._grainTexture = parameters.grain_texture;
  48586. }
  48587. else {
  48588. _this._createGrainTexture();
  48589. }
  48590. // save parameters
  48591. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48592. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48593. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48594. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48595. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48596. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48597. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48598. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48599. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48600. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48601. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48602. // Create effects
  48603. _this._createChromaticAberrationPostProcess(ratio);
  48604. _this._createHighlightsPostProcess(ratio);
  48605. _this._createDepthOfFieldPostProcess(ratio / 4);
  48606. // Set up pipeline
  48607. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48608. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48609. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48610. if (_this._highlightsGain === -1) {
  48611. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48612. }
  48613. // Finish
  48614. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48615. if (cameras) {
  48616. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48617. }
  48618. return _this;
  48619. }
  48620. // public methods (self explanatory)
  48621. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48622. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48623. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48624. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48625. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48626. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48627. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48628. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48629. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48630. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48631. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48632. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48633. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48634. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48635. };
  48636. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48637. this._highlightsPostProcess.updateEffect();
  48638. };
  48639. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48640. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48641. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48642. this._highlightsGain = amount;
  48643. };
  48644. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48645. if (this._highlightsGain === -1) {
  48646. this._highlightsGain = 1.0;
  48647. }
  48648. this._highlightsThreshold = amount;
  48649. };
  48650. LensRenderingPipeline.prototype.disableHighlights = function () {
  48651. this._highlightsGain = -1;
  48652. };
  48653. /**
  48654. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48655. */
  48656. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48657. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48658. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48659. this._chromaticAberrationPostProcess = undefined;
  48660. this._highlightsPostProcess = undefined;
  48661. this._depthOfFieldPostProcess = undefined;
  48662. this._grainTexture.dispose();
  48663. if (disableDepthRender)
  48664. this._scene.disableDepthRenderer();
  48665. };
  48666. // colors shifting and distortion
  48667. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48668. var _this = this;
  48669. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48670. [], // samplers
  48671. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48672. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48673. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48674. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48675. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48676. };
  48677. };
  48678. // highlights enhancing
  48679. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48680. var _this = this;
  48681. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48682. [], // samplers
  48683. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48684. this._highlightsPostProcess.onApply = function (effect) {
  48685. effect.setFloat('gain', _this._highlightsGain);
  48686. effect.setFloat('threshold', _this._highlightsThreshold);
  48687. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48688. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48689. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48690. };
  48691. };
  48692. // colors shifting and distortion
  48693. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48694. var _this = this;
  48695. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48696. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48697. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48698. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48699. this._depthOfFieldPostProcess.onApply = function (effect) {
  48700. effect.setTexture("depthSampler", _this._depthTexture);
  48701. effect.setTexture("grainSampler", _this._grainTexture);
  48702. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48703. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48704. effect.setFloat('grain_amount', _this._grainAmount);
  48705. effect.setBool('blur_noise', _this._blurNoise);
  48706. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48707. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48708. effect.setFloat('distortion', _this._distortion);
  48709. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48710. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48711. effect.setFloat('aperture', _this._dofAperture);
  48712. effect.setFloat('darken', _this._dofDarken);
  48713. effect.setFloat('edge_blur', _this._edgeBlur);
  48714. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48715. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48716. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48717. };
  48718. };
  48719. // creates a black and white random noise texture, 512x512
  48720. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48721. var size = 512;
  48722. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48723. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48724. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48725. var context = this._grainTexture.getContext();
  48726. var rand = function (min, max) {
  48727. return Math.random() * (max - min) + min;
  48728. };
  48729. var value;
  48730. for (var x = 0; x < size; x++) {
  48731. for (var y = 0; y < size; y++) {
  48732. value = Math.floor(rand(0.42, 0.58) * 255);
  48733. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48734. context.fillRect(x, y, 1, 1);
  48735. }
  48736. }
  48737. this._grainTexture.update(false);
  48738. };
  48739. return LensRenderingPipeline;
  48740. }(BABYLON.PostProcessRenderPipeline));
  48741. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48742. })(BABYLON || (BABYLON = {}));
  48743. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48744. //
  48745. // This post-process allows the modification of rendered colors by using
  48746. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48747. //
  48748. // The object needs to be provided an url to a texture containing the color
  48749. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48750. // Use an image editing software to tweak the LUT to match your needs.
  48751. //
  48752. // For an example of a color LUT, see here:
  48753. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48754. // For explanations on color grading, see here:
  48755. // http://udn.epicgames.com/Three/ColorGrading.html
  48756. //
  48757. var BABYLON;
  48758. (function (BABYLON) {
  48759. var ColorCorrectionPostProcess = (function (_super) {
  48760. __extends(ColorCorrectionPostProcess, _super);
  48761. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48762. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48763. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48764. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48765. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48766. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48767. _this.onApply = function (effect) {
  48768. effect.setTexture("colorTable", _this._colorTableTexture);
  48769. };
  48770. return _this;
  48771. }
  48772. return ColorCorrectionPostProcess;
  48773. }(BABYLON.PostProcess));
  48774. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48775. })(BABYLON || (BABYLON = {}));
  48776. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48777. var BABYLON;
  48778. (function (BABYLON) {
  48779. var AnaglyphFreeCamera = (function (_super) {
  48780. __extends(AnaglyphFreeCamera, _super);
  48781. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48782. var _this = _super.call(this, name, position, scene) || this;
  48783. _this.interaxialDistance = interaxialDistance;
  48784. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48785. return _this;
  48786. }
  48787. AnaglyphFreeCamera.prototype.getClassName = function () {
  48788. return "AnaglyphFreeCamera";
  48789. };
  48790. return AnaglyphFreeCamera;
  48791. }(BABYLON.FreeCamera));
  48792. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48793. var AnaglyphArcRotateCamera = (function (_super) {
  48794. __extends(AnaglyphArcRotateCamera, _super);
  48795. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48796. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48797. _this.interaxialDistance = interaxialDistance;
  48798. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48799. return _this;
  48800. }
  48801. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48802. return "AnaglyphArcRotateCamera";
  48803. };
  48804. return AnaglyphArcRotateCamera;
  48805. }(BABYLON.ArcRotateCamera));
  48806. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48807. var AnaglyphGamepadCamera = (function (_super) {
  48808. __extends(AnaglyphGamepadCamera, _super);
  48809. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48810. var _this = _super.call(this, name, position, scene) || this;
  48811. _this.interaxialDistance = interaxialDistance;
  48812. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48813. return _this;
  48814. }
  48815. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48816. return "AnaglyphGamepadCamera";
  48817. };
  48818. return AnaglyphGamepadCamera;
  48819. }(BABYLON.GamepadCamera));
  48820. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48821. var AnaglyphUniversalCamera = (function (_super) {
  48822. __extends(AnaglyphUniversalCamera, _super);
  48823. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48824. var _this = _super.call(this, name, position, scene) || this;
  48825. _this.interaxialDistance = interaxialDistance;
  48826. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48827. return _this;
  48828. }
  48829. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48830. return "AnaglyphUniversalCamera";
  48831. };
  48832. return AnaglyphUniversalCamera;
  48833. }(BABYLON.UniversalCamera));
  48834. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48835. var StereoscopicFreeCamera = (function (_super) {
  48836. __extends(StereoscopicFreeCamera, _super);
  48837. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48838. var _this = _super.call(this, name, position, scene) || this;
  48839. _this.interaxialDistance = interaxialDistance;
  48840. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48841. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48842. return _this;
  48843. }
  48844. StereoscopicFreeCamera.prototype.getClassName = function () {
  48845. return "StereoscopicFreeCamera";
  48846. };
  48847. return StereoscopicFreeCamera;
  48848. }(BABYLON.FreeCamera));
  48849. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48850. var StereoscopicArcRotateCamera = (function (_super) {
  48851. __extends(StereoscopicArcRotateCamera, _super);
  48852. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48853. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48854. _this.interaxialDistance = interaxialDistance;
  48855. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48856. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48857. return _this;
  48858. }
  48859. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48860. return "StereoscopicArcRotateCamera";
  48861. };
  48862. return StereoscopicArcRotateCamera;
  48863. }(BABYLON.ArcRotateCamera));
  48864. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48865. var StereoscopicGamepadCamera = (function (_super) {
  48866. __extends(StereoscopicGamepadCamera, _super);
  48867. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48868. var _this = _super.call(this, name, position, scene) || this;
  48869. _this.interaxialDistance = interaxialDistance;
  48870. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48871. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48872. return _this;
  48873. }
  48874. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48875. return "StereoscopicGamepadCamera";
  48876. };
  48877. return StereoscopicGamepadCamera;
  48878. }(BABYLON.GamepadCamera));
  48879. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48880. var StereoscopicUniversalCamera = (function (_super) {
  48881. __extends(StereoscopicUniversalCamera, _super);
  48882. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48883. var _this = _super.call(this, name, position, scene) || this;
  48884. _this.interaxialDistance = interaxialDistance;
  48885. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48886. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48887. return _this;
  48888. }
  48889. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48890. return "StereoscopicUniversalCamera";
  48891. };
  48892. return StereoscopicUniversalCamera;
  48893. }(BABYLON.UniversalCamera));
  48894. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48895. })(BABYLON || (BABYLON = {}));
  48896. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48897. var BABYLON;
  48898. (function (BABYLON) {
  48899. var HolographicCamera = (function (_super) {
  48900. __extends(HolographicCamera, _super);
  48901. function HolographicCamera(name, scene) {
  48902. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48903. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48904. _this._holographicViewMatrix = new BABYLON.Matrix();
  48905. _this._identityProjection = BABYLON.Matrix.Identity();
  48906. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48907. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48908. _this.fov = 30;
  48909. _this.minZ = 1.0;
  48910. _this.maxZ = 20;
  48911. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48912. _this.isIntermediate = false;
  48913. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48914. _this.layerMask = 0x0FFFFFFF;
  48915. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48916. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48917. var self = _this;
  48918. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48919. self._holographicViewMatrix.m = window.getViewMatrix();
  48920. self.setViewMatrix(self._holographicViewMatrix);
  48921. var position = window.getCameraPositionVector();
  48922. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48923. });
  48924. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48925. if (scene.frustumPlanes) {
  48926. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48927. }
  48928. });
  48929. scene.addCamera(_this);
  48930. if (!scene.activeCamera) {
  48931. scene.activeCamera = _this;
  48932. }
  48933. return _this;
  48934. }
  48935. HolographicCamera.prototype.getTypeName = function () {
  48936. return "HolographicCamera";
  48937. };
  48938. ;
  48939. HolographicCamera.prototype.getProjectionMatrix = function () {
  48940. return this._identityProjection;
  48941. };
  48942. ;
  48943. HolographicCamera.prototype.getViewMatrix = function () {
  48944. return this._holographicViewMatrix;
  48945. };
  48946. ;
  48947. HolographicCamera.prototype.setViewMatrix = function (view) {
  48948. this._holographicViewMatrix = view;
  48949. view.m[0] = -view.m[0];
  48950. view.m[1] = -view.m[1];
  48951. view.m[2] = -view.m[2];
  48952. view.m[3] = -view.m[3];
  48953. view.m[8] = -view.m[8];
  48954. view.m[9] = -view.m[9];
  48955. view.m[10] = -view.m[10];
  48956. view.m[11] = -view.m[11];
  48957. };
  48958. ;
  48959. HolographicCamera.prototype._initCache = function () { };
  48960. ;
  48961. HolographicCamera.prototype._updateCache = function () { };
  48962. ;
  48963. HolographicCamera.prototype._updateFromScene = function () { };
  48964. ;
  48965. // Synchronized
  48966. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48967. return true;
  48968. };
  48969. ;
  48970. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48971. return true;
  48972. };
  48973. ;
  48974. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48975. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48976. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48977. return result;
  48978. };
  48979. ;
  48980. HolographicCamera.prototype.dispose = function () {
  48981. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48982. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48983. _super.prototype.dispose.call(this);
  48984. };
  48985. return HolographicCamera;
  48986. }(BABYLON.Camera));
  48987. BABYLON.HolographicCamera = HolographicCamera;
  48988. })(BABYLON || (BABYLON = {}));
  48989. //# sourceMappingURL=babylon.holographicCamera.js.map
  48990. var BABYLON;
  48991. (function (BABYLON) {
  48992. var HDRRenderingPipeline = (function (_super) {
  48993. __extends(HDRRenderingPipeline, _super);
  48994. /**
  48995. * @constructor
  48996. * @param {string} name - The rendering pipeline name
  48997. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48998. * @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)
  48999. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49000. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49001. */
  49002. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49003. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49004. var _this = _super.call(this, scene.getEngine(), name) || this;
  49005. /**
  49006. * Public members
  49007. */
  49008. // Gaussian Blur
  49009. /**
  49010. * Gaussian blur coefficient
  49011. * @type {number}
  49012. */
  49013. _this.gaussCoeff = 0.3;
  49014. /**
  49015. * Gaussian blur mean
  49016. * @type {number}
  49017. */
  49018. _this.gaussMean = 1.0;
  49019. /**
  49020. * Gaussian blur standard deviation
  49021. * @type {number}
  49022. */
  49023. _this.gaussStandDev = 0.8;
  49024. /**
  49025. * Gaussian blur multiplier. Multiplies the blur effect
  49026. * @type {number}
  49027. */
  49028. _this.gaussMultiplier = 4.0;
  49029. // HDR
  49030. /**
  49031. * Exposure, controls the overall intensity of the pipeline
  49032. * @type {number}
  49033. */
  49034. _this.exposure = 1.0;
  49035. /**
  49036. * Minimum luminance that the post-process can output. Luminance is >= 0
  49037. * @type {number}
  49038. */
  49039. _this.minimumLuminance = 1.0;
  49040. /**
  49041. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  49042. * @type {number}
  49043. */
  49044. _this.maximumLuminance = 1e20;
  49045. /**
  49046. * Increase rate for luminance: eye adaptation speed to dark
  49047. * @type {number}
  49048. */
  49049. _this.luminanceIncreaserate = 0.5;
  49050. /**
  49051. * Decrease rate for luminance: eye adaptation speed to bright
  49052. * @type {number}
  49053. */
  49054. _this.luminanceDecreaseRate = 0.5;
  49055. // Bright pass
  49056. /**
  49057. * Minimum luminance needed to compute HDR
  49058. * @type {number}
  49059. */
  49060. _this.brightThreshold = 0.8;
  49061. _this._needUpdate = true;
  49062. _this._scene = scene;
  49063. // Bright pass
  49064. _this._createBrightPassPostProcess(scene, ratio);
  49065. // Down sample X4
  49066. _this._createDownSampleX4PostProcess(scene, ratio);
  49067. // Create gaussian blur post-processes
  49068. _this._createGaussianBlurPostProcess(scene, ratio);
  49069. // Texture adder
  49070. _this._createTextureAdderPostProcess(scene, ratio);
  49071. // Luminance generator
  49072. _this._createLuminanceGeneratorPostProcess(scene);
  49073. // HDR
  49074. _this._createHDRPostProcess(scene, ratio);
  49075. // Pass postprocess
  49076. if (originalPostProcess === null) {
  49077. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49078. }
  49079. else {
  49080. _this._originalPostProcess = originalPostProcess;
  49081. }
  49082. // Configure pipeline
  49083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  49084. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  49085. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  49086. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  49087. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  49088. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  49089. var addDownSamplerPostProcess = function (id) {
  49090. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  49091. };
  49092. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  49093. addDownSamplerPostProcess(i);
  49094. }
  49095. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  49096. // Finish
  49097. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49098. if (cameras !== null) {
  49099. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49100. }
  49101. _this.update();
  49102. return _this;
  49103. }
  49104. /**
  49105. * Tells the pipeline to update its post-processes
  49106. */
  49107. HDRRenderingPipeline.prototype.update = function () {
  49108. this._needUpdate = true;
  49109. };
  49110. /**
  49111. * Returns the current calculated luminance
  49112. */
  49113. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  49114. return this._hdrCurrentLuminance;
  49115. };
  49116. /**
  49117. * Returns the currently drawn luminance
  49118. */
  49119. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  49120. return this._hdrOutputLuminance;
  49121. };
  49122. /**
  49123. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  49124. */
  49125. HDRRenderingPipeline.prototype.dispose = function () {
  49126. for (var i = 0; i < this._scene.cameras.length; i++) {
  49127. var camera = this._scene.cameras[i];
  49128. this._originalPostProcess.dispose(camera);
  49129. this._brightPassPostProcess.dispose(camera);
  49130. this._downSampleX4PostProcess.dispose(camera);
  49131. this._guassianBlurHPostProcess.dispose(camera);
  49132. this._guassianBlurVPostProcess.dispose(camera);
  49133. this._textureAdderPostProcess.dispose(camera);
  49134. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  49135. this._downSamplePostProcesses[j].dispose(camera);
  49136. }
  49137. this._hdrPostProcess.dispose(camera);
  49138. }
  49139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49140. _super.prototype.dispose.call(this);
  49141. };
  49142. /**
  49143. * Creates the HDR post-process and computes the luminance adaptation
  49144. */
  49145. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  49146. var _this = this;
  49147. var hdrLastLuminance = 0.0;
  49148. this._hdrOutputLuminance = -1.0;
  49149. this._hdrCurrentLuminance = 1.0;
  49150. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  49151. this._hdrPostProcess.onApply = function (effect) {
  49152. if (_this._hdrOutputLuminance < 0.0) {
  49153. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49154. }
  49155. else {
  49156. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  49157. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  49158. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  49159. }
  49160. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  49161. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  49162. }
  49163. else {
  49164. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49165. }
  49166. }
  49167. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  49168. hdrLastLuminance += scene.getEngine().getDeltaTime();
  49169. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49170. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49171. effect.setFloat("exposure", _this.exposure);
  49172. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  49173. _this._needUpdate = false;
  49174. };
  49175. };
  49176. /**
  49177. * Texture Adder post-process
  49178. */
  49179. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49180. var _this = this;
  49181. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  49182. this._textureAdderPostProcess.onApply = function (effect) {
  49183. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49184. };
  49185. };
  49186. /**
  49187. * Down sample X4 post-process
  49188. */
  49189. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49190. var _this = this;
  49191. var downSampleX4Offsets = new Array(32);
  49192. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  49193. this._downSampleX4PostProcess.onApply = function (effect) {
  49194. if (_this._needUpdate) {
  49195. var id = 0;
  49196. for (var i = -2; i < 2; i++) {
  49197. for (var j = -2; j < 2; j++) {
  49198. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  49199. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  49200. id += 2;
  49201. }
  49202. }
  49203. }
  49204. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49205. };
  49206. };
  49207. /**
  49208. * Bright pass post-process
  49209. */
  49210. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49211. var _this = this;
  49212. var brightOffsets = new Array(8);
  49213. var brightPassCallback = function (effect) {
  49214. if (_this._needUpdate) {
  49215. var sU = (1.0 / _this._brightPassPostProcess.width);
  49216. var sV = (1.0 / _this._brightPassPostProcess.height);
  49217. brightOffsets[0] = -0.5 * sU;
  49218. brightOffsets[1] = 0.5 * sV;
  49219. brightOffsets[2] = 0.5 * sU;
  49220. brightOffsets[3] = 0.5 * sV;
  49221. brightOffsets[4] = -0.5 * sU;
  49222. brightOffsets[5] = -0.5 * sV;
  49223. brightOffsets[6] = 0.5 * sU;
  49224. brightOffsets[7] = -0.5 * sV;
  49225. }
  49226. effect.setArray2("dsOffsets", brightOffsets);
  49227. effect.setFloat("brightThreshold", _this.brightThreshold);
  49228. };
  49229. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  49230. this._brightPassPostProcess.onApply = brightPassCallback;
  49231. };
  49232. /**
  49233. * Luminance generator. Creates the luminance post-process and down sample post-processes
  49234. */
  49235. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  49236. var _this = this;
  49237. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  49238. var luminanceOffsets = new Array(8);
  49239. var downSampleOffsets = new Array(18);
  49240. var halfDestPixelSize;
  49241. this._downSamplePostProcesses = new Array(lumSteps);
  49242. // Utils for luminance
  49243. var luminanceUpdateSourceOffsets = function (width, height) {
  49244. var sU = (1.0 / width);
  49245. var sV = (1.0 / height);
  49246. luminanceOffsets[0] = -0.5 * sU;
  49247. luminanceOffsets[1] = 0.5 * sV;
  49248. luminanceOffsets[2] = 0.5 * sU;
  49249. luminanceOffsets[3] = 0.5 * sV;
  49250. luminanceOffsets[4] = -0.5 * sU;
  49251. luminanceOffsets[5] = -0.5 * sV;
  49252. luminanceOffsets[6] = 0.5 * sU;
  49253. luminanceOffsets[7] = -0.5 * sV;
  49254. };
  49255. var luminanceUpdateDestOffsets = function (width, height) {
  49256. var id = 0;
  49257. for (var x = -1; x < 2; x++) {
  49258. for (var y = -1; y < 2; y++) {
  49259. downSampleOffsets[id] = (x) / width;
  49260. downSampleOffsets[id + 1] = (y) / height;
  49261. id += 2;
  49262. }
  49263. }
  49264. };
  49265. // Luminance callback
  49266. var luminanceCallback = function (effect) {
  49267. if (_this._needUpdate) {
  49268. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  49269. }
  49270. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49271. effect.setArray2("lumOffsets", luminanceOffsets);
  49272. };
  49273. // Down sample callbacks
  49274. var downSampleCallback = function (indice) {
  49275. var i = indice;
  49276. return function (effect) {
  49277. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49278. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49279. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  49280. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  49281. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  49282. effect.setArray2("dsOffsets", downSampleOffsets);
  49283. };
  49284. };
  49285. var downSampleAfterRenderCallback = function (effect) {
  49286. // Unpack result
  49287. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49288. 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);
  49289. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49290. };
  49291. // Create luminance post-process
  49292. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  49293. 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);
  49294. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  49295. // Create down sample post-processes
  49296. for (var i = lumSteps - 2; i >= 0; i--) {
  49297. var length = Math.pow(3, i);
  49298. ratio = { width: length, height: length };
  49299. var defines = "#define DOWN_SAMPLE\n";
  49300. if (i === 0) {
  49301. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  49302. }
  49303. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  49304. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  49305. if (i === 0) {
  49306. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  49307. }
  49308. }
  49309. };
  49310. /**
  49311. * Gaussian blur post-processes. Horizontal and Vertical
  49312. */
  49313. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  49314. var _this = this;
  49315. var blurOffsetsW = new Array(9);
  49316. var blurOffsetsH = new Array(9);
  49317. var blurWeights = new Array(9);
  49318. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  49319. // Utils for gaussian blur
  49320. var calculateBlurOffsets = function (height) {
  49321. var lastOutputDimensions = {
  49322. width: scene.getEngine().getRenderWidth(),
  49323. height: scene.getEngine().getRenderHeight()
  49324. };
  49325. for (var i = 0; i < 9; i++) {
  49326. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49327. if (height) {
  49328. blurOffsetsH[i] = value;
  49329. }
  49330. else {
  49331. blurOffsetsW[i] = value;
  49332. }
  49333. }
  49334. };
  49335. var calculateWeights = function () {
  49336. var x = 0.0;
  49337. for (var i = 0; i < 9; i++) {
  49338. x = (i - 4.0) / 4.0;
  49339. 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));
  49340. }
  49341. };
  49342. // Callback
  49343. var gaussianBlurCallback = function (height) {
  49344. return function (effect) {
  49345. if (_this._needUpdate) {
  49346. calculateWeights();
  49347. calculateBlurOffsets(height);
  49348. }
  49349. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  49350. effect.setArray("blurWeights", blurWeights);
  49351. effect.setFloat("multiplier", _this.gaussMultiplier);
  49352. };
  49353. };
  49354. // Create horizontal gaussian blur post-processes
  49355. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  49356. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  49357. // Create vertical gaussian blur post-process
  49358. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  49359. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  49360. };
  49361. return HDRRenderingPipeline;
  49362. }(BABYLON.PostProcessRenderPipeline));
  49363. // Luminance generator
  49364. HDRRenderingPipeline.LUM_STEPS = 6;
  49365. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  49366. })(BABYLON || (BABYLON = {}));
  49367. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  49368. var BABYLON;
  49369. (function (BABYLON) {
  49370. var FaceAdjacencies = (function () {
  49371. function FaceAdjacencies() {
  49372. this.edges = new Array();
  49373. this.edgesConnectedCount = 0;
  49374. }
  49375. return FaceAdjacencies;
  49376. }());
  49377. var EdgesRenderer = (function () {
  49378. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  49379. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  49380. if (epsilon === void 0) { epsilon = 0.95; }
  49381. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  49382. this.edgesWidthScalerForOrthographic = 1000.0;
  49383. this.edgesWidthScalerForPerspective = 50.0;
  49384. this._linesPositions = new Array();
  49385. this._linesNormals = new Array();
  49386. this._linesIndices = new Array();
  49387. this._buffers = {};
  49388. this._checkVerticesInsteadOfIndices = false;
  49389. this._source = source;
  49390. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  49391. this._epsilon = epsilon;
  49392. this._prepareRessources();
  49393. this._generateEdgesLines();
  49394. }
  49395. EdgesRenderer.prototype._prepareRessources = function () {
  49396. if (this._lineShader) {
  49397. return;
  49398. }
  49399. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  49400. attributes: ["position", "normal"],
  49401. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  49402. });
  49403. this._lineShader.disableDepthWrite = true;
  49404. this._lineShader.backFaceCulling = false;
  49405. };
  49406. EdgesRenderer.prototype.dispose = function () {
  49407. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  49408. if (buffer) {
  49409. buffer.dispose();
  49410. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  49411. }
  49412. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  49413. if (buffer) {
  49414. buffer.dispose();
  49415. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  49416. }
  49417. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  49418. this._lineShader.dispose();
  49419. };
  49420. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  49421. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  49422. return 0;
  49423. }
  49424. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  49425. return 1;
  49426. }
  49427. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  49428. return 2;
  49429. }
  49430. return -1;
  49431. };
  49432. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  49433. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  49434. return 0;
  49435. }
  49436. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  49437. return 1;
  49438. }
  49439. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  49440. return 2;
  49441. }
  49442. return -1;
  49443. };
  49444. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  49445. var needToCreateLine;
  49446. if (edge === undefined) {
  49447. needToCreateLine = true;
  49448. }
  49449. else {
  49450. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  49451. needToCreateLine = dotProduct < this._epsilon;
  49452. }
  49453. if (needToCreateLine) {
  49454. var offset = this._linesPositions.length / 3;
  49455. var normal = p0.subtract(p1);
  49456. normal.normalize();
  49457. // Positions
  49458. this._linesPositions.push(p0.x);
  49459. this._linesPositions.push(p0.y);
  49460. this._linesPositions.push(p0.z);
  49461. this._linesPositions.push(p0.x);
  49462. this._linesPositions.push(p0.y);
  49463. this._linesPositions.push(p0.z);
  49464. this._linesPositions.push(p1.x);
  49465. this._linesPositions.push(p1.y);
  49466. this._linesPositions.push(p1.z);
  49467. this._linesPositions.push(p1.x);
  49468. this._linesPositions.push(p1.y);
  49469. this._linesPositions.push(p1.z);
  49470. // Normals
  49471. this._linesNormals.push(p1.x);
  49472. this._linesNormals.push(p1.y);
  49473. this._linesNormals.push(p1.z);
  49474. this._linesNormals.push(-1);
  49475. this._linesNormals.push(p1.x);
  49476. this._linesNormals.push(p1.y);
  49477. this._linesNormals.push(p1.z);
  49478. this._linesNormals.push(1);
  49479. this._linesNormals.push(p0.x);
  49480. this._linesNormals.push(p0.y);
  49481. this._linesNormals.push(p0.z);
  49482. this._linesNormals.push(-1);
  49483. this._linesNormals.push(p0.x);
  49484. this._linesNormals.push(p0.y);
  49485. this._linesNormals.push(p0.z);
  49486. this._linesNormals.push(1);
  49487. // Indices
  49488. this._linesIndices.push(offset);
  49489. this._linesIndices.push(offset + 1);
  49490. this._linesIndices.push(offset + 2);
  49491. this._linesIndices.push(offset);
  49492. this._linesIndices.push(offset + 2);
  49493. this._linesIndices.push(offset + 3);
  49494. }
  49495. };
  49496. EdgesRenderer.prototype._generateEdgesLines = function () {
  49497. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49498. var indices = this._source.getIndices();
  49499. // First let's find adjacencies
  49500. var adjacencies = new Array();
  49501. var faceNormals = new Array();
  49502. var index;
  49503. var faceAdjacencies;
  49504. // Prepare faces
  49505. for (index = 0; index < indices.length; index += 3) {
  49506. faceAdjacencies = new FaceAdjacencies();
  49507. var p0Index = indices[index];
  49508. var p1Index = indices[index + 1];
  49509. var p2Index = indices[index + 2];
  49510. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49511. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49512. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49513. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49514. faceNormal.normalize();
  49515. faceNormals.push(faceNormal);
  49516. adjacencies.push(faceAdjacencies);
  49517. }
  49518. // Scan
  49519. for (index = 0; index < adjacencies.length; index++) {
  49520. faceAdjacencies = adjacencies[index];
  49521. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49522. var otherFaceAdjacencies = adjacencies[otherIndex];
  49523. if (faceAdjacencies.edgesConnectedCount === 3) {
  49524. break;
  49525. }
  49526. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49527. continue;
  49528. }
  49529. var otherP0 = indices[otherIndex * 3];
  49530. var otherP1 = indices[otherIndex * 3 + 1];
  49531. var otherP2 = indices[otherIndex * 3 + 2];
  49532. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49533. var otherEdgeIndex;
  49534. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49535. continue;
  49536. }
  49537. switch (edgeIndex) {
  49538. case 0:
  49539. if (this._checkVerticesInsteadOfIndices) {
  49540. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49541. }
  49542. else {
  49543. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49544. }
  49545. break;
  49546. case 1:
  49547. if (this._checkVerticesInsteadOfIndices) {
  49548. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49549. }
  49550. else {
  49551. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49552. }
  49553. break;
  49554. case 2:
  49555. if (this._checkVerticesInsteadOfIndices) {
  49556. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49557. }
  49558. else {
  49559. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49560. }
  49561. break;
  49562. }
  49563. if (otherEdgeIndex === -1) {
  49564. continue;
  49565. }
  49566. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49567. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49568. faceAdjacencies.edgesConnectedCount++;
  49569. otherFaceAdjacencies.edgesConnectedCount++;
  49570. if (faceAdjacencies.edgesConnectedCount === 3) {
  49571. break;
  49572. }
  49573. }
  49574. }
  49575. }
  49576. // Create lines
  49577. for (index = 0; index < adjacencies.length; index++) {
  49578. // 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
  49579. var current = adjacencies[index];
  49580. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49581. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49582. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49583. }
  49584. // Merge into a single mesh
  49585. var engine = this._source.getScene().getEngine();
  49586. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49587. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49588. this._ib = engine.createIndexBuffer(this._linesIndices);
  49589. this._indicesCount = this._linesIndices.length;
  49590. };
  49591. EdgesRenderer.prototype.render = function () {
  49592. if (!this._lineShader.isReady()) {
  49593. return;
  49594. }
  49595. var scene = this._source.getScene();
  49596. var engine = scene.getEngine();
  49597. this._lineShader._preBind();
  49598. // VBOs
  49599. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49600. scene.resetCachedMaterial();
  49601. this._lineShader.setColor4("color", this._source.edgesColor);
  49602. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49603. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49604. }
  49605. else {
  49606. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49607. }
  49608. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49609. this._lineShader.bind(this._source.getWorldMatrix());
  49610. // Draw order
  49611. engine.draw(true, 0, this._indicesCount);
  49612. this._lineShader.unbind();
  49613. engine.setDepthWrite(true);
  49614. };
  49615. return EdgesRenderer;
  49616. }());
  49617. BABYLON.EdgesRenderer = EdgesRenderer;
  49618. })(BABYLON || (BABYLON = {}));
  49619. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49620. var BABYLON;
  49621. (function (BABYLON) {
  49622. var TonemappingOperator;
  49623. (function (TonemappingOperator) {
  49624. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49625. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49626. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49627. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49628. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49629. ;
  49630. var TonemapPostProcess = (function (_super) {
  49631. __extends(TonemapPostProcess, _super);
  49632. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49634. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49635. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49636. _this._operator = _operator;
  49637. _this.exposureAdjustment = exposureAdjustment;
  49638. var defines = "#define ";
  49639. if (_this._operator === TonemappingOperator.Hable)
  49640. defines += "HABLE_TONEMAPPING";
  49641. else if (_this._operator === TonemappingOperator.Reinhard)
  49642. defines += "REINHARD_TONEMAPPING";
  49643. else if (_this._operator === TonemappingOperator.HejiDawson)
  49644. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49645. else if (_this._operator === TonemappingOperator.Photographic)
  49646. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49647. //sadly a second call to create the effect.
  49648. _this.updateEffect(defines);
  49649. _this.onApply = function (effect) {
  49650. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49651. };
  49652. return _this;
  49653. }
  49654. return TonemapPostProcess;
  49655. }(BABYLON.PostProcess));
  49656. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49657. })(BABYLON || (BABYLON = {}));
  49658. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49659. var BABYLON;
  49660. (function (BABYLON) {
  49661. var ReflectionProbe = (function () {
  49662. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49664. var _this = this;
  49665. this.name = name;
  49666. this._viewMatrix = BABYLON.Matrix.Identity();
  49667. this._target = BABYLON.Vector3.Zero();
  49668. this._add = BABYLON.Vector3.Zero();
  49669. this.invertYAxis = false;
  49670. this.position = BABYLON.Vector3.Zero();
  49671. this._scene = scene;
  49672. this._scene.reflectionProbes.push(this);
  49673. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49674. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49675. switch (faceIndex) {
  49676. case 0:
  49677. _this._add.copyFromFloats(1, 0, 0);
  49678. break;
  49679. case 1:
  49680. _this._add.copyFromFloats(-1, 0, 0);
  49681. break;
  49682. case 2:
  49683. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49684. break;
  49685. case 3:
  49686. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49687. break;
  49688. case 4:
  49689. _this._add.copyFromFloats(0, 0, 1);
  49690. break;
  49691. case 5:
  49692. _this._add.copyFromFloats(0, 0, -1);
  49693. break;
  49694. }
  49695. if (_this._attachedMesh) {
  49696. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49697. }
  49698. _this.position.addToRef(_this._add, _this._target);
  49699. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49700. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49701. });
  49702. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49703. scene.updateTransformMatrix(true);
  49704. });
  49705. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49706. }
  49707. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49708. get: function () {
  49709. return this._renderTargetTexture.refreshRate;
  49710. },
  49711. set: function (value) {
  49712. this._renderTargetTexture.refreshRate = value;
  49713. },
  49714. enumerable: true,
  49715. configurable: true
  49716. });
  49717. ReflectionProbe.prototype.getScene = function () {
  49718. return this._scene;
  49719. };
  49720. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49721. get: function () {
  49722. return this._renderTargetTexture;
  49723. },
  49724. enumerable: true,
  49725. configurable: true
  49726. });
  49727. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49728. get: function () {
  49729. return this._renderTargetTexture.renderList;
  49730. },
  49731. enumerable: true,
  49732. configurable: true
  49733. });
  49734. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49735. this._attachedMesh = mesh;
  49736. };
  49737. ReflectionProbe.prototype.dispose = function () {
  49738. var index = this._scene.reflectionProbes.indexOf(this);
  49739. if (index !== -1) {
  49740. // Remove from the scene if found
  49741. this._scene.reflectionProbes.splice(index, 1);
  49742. }
  49743. if (this._renderTargetTexture) {
  49744. this._renderTargetTexture.dispose();
  49745. this._renderTargetTexture = null;
  49746. }
  49747. };
  49748. return ReflectionProbe;
  49749. }());
  49750. BABYLON.ReflectionProbe = ReflectionProbe;
  49751. })(BABYLON || (BABYLON = {}));
  49752. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49753. var BABYLON;
  49754. (function (BABYLON) {
  49755. var SolidParticle = (function () {
  49756. /**
  49757. * Creates a Solid Particle object.
  49758. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49759. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49760. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49761. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49762. * `shapeId` (integer) is the model shape identifier in the SPS.
  49763. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49764. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49765. */
  49766. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49767. this.idx = 0; // particle global index
  49768. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49769. this.position = BABYLON.Vector3.Zero(); // position
  49770. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49771. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49772. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49773. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49774. this.alive = true; // alive
  49775. this.isVisible = true; // visibility
  49776. this._pos = 0; // index of this particle in the global "positions" array
  49777. this.shapeId = 0; // model shape id
  49778. this.idxInShape = 0; // index of the particle in its shape id
  49779. this.idx = particleIndex;
  49780. this._pos = positionIndex;
  49781. this._model = model;
  49782. this.shapeId = shapeId;
  49783. this.idxInShape = idxInShape;
  49784. this._sps = sps;
  49785. if (modelBoundingInfo) {
  49786. this._modelBoundingInfo = modelBoundingInfo;
  49787. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49788. }
  49789. }
  49790. Object.defineProperty(SolidParticle.prototype, "scale", {
  49791. /**
  49792. * legacy support, changed scale to scaling
  49793. */
  49794. get: function () {
  49795. return this.scaling;
  49796. },
  49797. set: function (scale) {
  49798. this.scaling = scale;
  49799. },
  49800. enumerable: true,
  49801. configurable: true
  49802. });
  49803. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49804. /**
  49805. * legacy support, changed quaternion to rotationQuaternion
  49806. */
  49807. get: function () {
  49808. return this.rotationQuaternion;
  49809. },
  49810. set: function (q) {
  49811. this.rotationQuaternion = q;
  49812. },
  49813. enumerable: true,
  49814. configurable: true
  49815. });
  49816. /**
  49817. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49818. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49819. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49820. */
  49821. SolidParticle.prototype.intersectsMesh = function (target) {
  49822. if (!this._boundingInfo || !target._boundingInfo) {
  49823. return false;
  49824. }
  49825. if (this._sps._bSphereOnly) {
  49826. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49827. }
  49828. return this._boundingInfo.intersects(target._boundingInfo, false);
  49829. };
  49830. return SolidParticle;
  49831. }());
  49832. BABYLON.SolidParticle = SolidParticle;
  49833. var ModelShape = (function () {
  49834. /**
  49835. * 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.
  49836. * SPS internal tool, don't use it manually.
  49837. */
  49838. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49839. this.shapeID = id;
  49840. this._shape = shape;
  49841. this._shapeUV = shapeUV;
  49842. this._positionFunction = posFunction;
  49843. this._vertexFunction = vtxFunction;
  49844. }
  49845. return ModelShape;
  49846. }());
  49847. BABYLON.ModelShape = ModelShape;
  49848. })(BABYLON || (BABYLON = {}));
  49849. //# sourceMappingURL=babylon.solidParticle.js.map
  49850. var BABYLON;
  49851. (function (BABYLON) {
  49852. /**
  49853. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49854. */
  49855. var SolidParticleSystem = (function () {
  49856. /**
  49857. * Creates a SPS (Solid Particle System) object.
  49858. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49859. * `scene` (Scene) is the scene in which the SPS is added.
  49860. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49861. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49862. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49863. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49864. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49865. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49866. */
  49867. function SolidParticleSystem(name, scene, options) {
  49868. // public members
  49869. /**
  49870. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49871. * Example : var p = SPS.particles[i];
  49872. */
  49873. this.particles = new Array();
  49874. /**
  49875. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49876. */
  49877. this.nbParticles = 0;
  49878. /**
  49879. * If the particles must ever face the camera (default false). Useful for planar particles.
  49880. */
  49881. this.billboard = false;
  49882. /**
  49883. * Recompute normals when adding a shape
  49884. */
  49885. this.recomputeNormals = true;
  49886. /**
  49887. * This a counter ofr your own usage. It's not set by any SPS functions.
  49888. */
  49889. this.counter = 0;
  49890. /**
  49891. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49892. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49893. */
  49894. this.vars = {};
  49895. this._positions = new Array();
  49896. this._indices = new Array();
  49897. this._normals = new Array();
  49898. this._colors = new Array();
  49899. this._uvs = new Array();
  49900. this._index = 0; // indices index
  49901. this._updatable = true;
  49902. this._pickable = false;
  49903. this._isVisibilityBoxLocked = false;
  49904. this._alwaysVisible = false;
  49905. this._shapeCounter = 0;
  49906. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49907. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49908. this._computeParticleColor = true;
  49909. this._computeParticleTexture = true;
  49910. this._computeParticleRotation = true;
  49911. this._computeParticleVertex = false;
  49912. this._computeBoundingBox = false;
  49913. this._cam_axisZ = BABYLON.Vector3.Zero();
  49914. this._cam_axisY = BABYLON.Vector3.Zero();
  49915. this._cam_axisX = BABYLON.Vector3.Zero();
  49916. this._axisX = BABYLON.Axis.X;
  49917. this._axisY = BABYLON.Axis.Y;
  49918. this._axisZ = BABYLON.Axis.Z;
  49919. this._camDir = BABYLON.Vector3.Zero();
  49920. this._rotMatrix = new BABYLON.Matrix();
  49921. this._invertMatrix = new BABYLON.Matrix();
  49922. this._rotated = BABYLON.Vector3.Zero();
  49923. this._quaternion = new BABYLON.Quaternion();
  49924. this._vertex = BABYLON.Vector3.Zero();
  49925. this._normal = BABYLON.Vector3.Zero();
  49926. this._yaw = 0.0;
  49927. this._pitch = 0.0;
  49928. this._roll = 0.0;
  49929. this._halfroll = 0.0;
  49930. this._halfpitch = 0.0;
  49931. this._halfyaw = 0.0;
  49932. this._sinRoll = 0.0;
  49933. this._cosRoll = 0.0;
  49934. this._sinPitch = 0.0;
  49935. this._cosPitch = 0.0;
  49936. this._sinYaw = 0.0;
  49937. this._cosYaw = 0.0;
  49938. this._w = 0.0;
  49939. this._minimum = BABYLON.Tmp.Vector3[0];
  49940. this._maximum = BABYLON.Tmp.Vector3[1];
  49941. this._scale = BABYLON.Tmp.Vector3[2];
  49942. this._translation = BABYLON.Tmp.Vector3[3];
  49943. this._minBbox = BABYLON.Tmp.Vector3[4];
  49944. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49945. this._particlesIntersect = false;
  49946. this._bSphereOnly = false;
  49947. this._bSphereRadiusFactor = 1.0;
  49948. this.name = name;
  49949. this._scene = scene;
  49950. this._camera = scene.activeCamera;
  49951. this._pickable = options ? options.isPickable : false;
  49952. this._particlesIntersect = options ? options.particleIntersection : false;
  49953. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49954. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49955. if (options && options.updatable) {
  49956. this._updatable = options.updatable;
  49957. }
  49958. else {
  49959. this._updatable = true;
  49960. }
  49961. if (this._pickable) {
  49962. this.pickedParticles = [];
  49963. }
  49964. }
  49965. /**
  49966. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49967. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49968. */
  49969. SolidParticleSystem.prototype.buildMesh = function () {
  49970. if (this.nbParticles === 0) {
  49971. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49972. this.addShape(triangle, 1);
  49973. triangle.dispose();
  49974. }
  49975. this._positions32 = new Float32Array(this._positions);
  49976. this._uvs32 = new Float32Array(this._uvs);
  49977. this._colors32 = new Float32Array(this._colors);
  49978. if (this.recomputeNormals) {
  49979. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49980. }
  49981. this._normals32 = new Float32Array(this._normals);
  49982. this._fixedNormal32 = new Float32Array(this._normals);
  49983. var vertexData = new BABYLON.VertexData();
  49984. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49985. vertexData.indices = this._indices;
  49986. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49987. if (this._uvs32) {
  49988. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49989. ;
  49990. }
  49991. if (this._colors32) {
  49992. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49993. }
  49994. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49995. vertexData.applyToMesh(mesh, this._updatable);
  49996. this.mesh = mesh;
  49997. this.mesh.isPickable = this._pickable;
  49998. // free memory
  49999. this._positions = null;
  50000. this._normals = null;
  50001. this._uvs = null;
  50002. this._colors = null;
  50003. if (!this._updatable) {
  50004. this.particles.length = 0;
  50005. }
  50006. return mesh;
  50007. };
  50008. /**
  50009. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  50010. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  50011. * Thus the particles generated from `digest()` have their property `position` set yet.
  50012. * `mesh` ( Mesh ) is the mesh to be digested
  50013. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  50014. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  50015. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  50016. */
  50017. SolidParticleSystem.prototype.digest = function (mesh, options) {
  50018. var size = (options && options.facetNb) || 1;
  50019. var number = (options && options.number);
  50020. var delta = (options && options.delta) || 0;
  50021. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50022. var meshInd = mesh.getIndices();
  50023. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50024. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50025. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50026. var f = 0; // facet counter
  50027. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  50028. // compute size from number
  50029. if (number) {
  50030. number = (number > totalFacets) ? totalFacets : number;
  50031. size = Math.round(totalFacets / number);
  50032. delta = 0;
  50033. }
  50034. else {
  50035. size = (size > totalFacets) ? totalFacets : size;
  50036. }
  50037. var facetPos = []; // submesh positions
  50038. var facetInd = []; // submesh indices
  50039. var facetUV = []; // submesh UV
  50040. var facetCol = []; // submesh colors
  50041. var barycenter = BABYLON.Tmp.Vector3[0];
  50042. var rand;
  50043. var sizeO = size;
  50044. while (f < totalFacets) {
  50045. size = sizeO + Math.floor((1 + delta) * Math.random());
  50046. if (f > totalFacets - size) {
  50047. size = totalFacets - f;
  50048. }
  50049. // reset temp arrays
  50050. facetPos.length = 0;
  50051. facetInd.length = 0;
  50052. facetUV.length = 0;
  50053. facetCol.length = 0;
  50054. // iterate over "size" facets
  50055. var fi = 0;
  50056. for (var j = f * 3; j < (f + size) * 3; j++) {
  50057. facetInd.push(fi);
  50058. var i = meshInd[j];
  50059. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  50060. if (meshUV) {
  50061. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  50062. }
  50063. if (meshCol) {
  50064. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  50065. }
  50066. fi++;
  50067. }
  50068. // create a model shape for each single particle
  50069. var idx = this.nbParticles;
  50070. var shape = this._posToShape(facetPos);
  50071. var shapeUV = this._uvsToShapeUV(facetUV);
  50072. // compute the barycenter of the shape
  50073. var v;
  50074. for (v = 0; v < shape.length; v++) {
  50075. barycenter.addInPlace(shape[v]);
  50076. }
  50077. barycenter.scaleInPlace(1 / shape.length);
  50078. // shift the shape from its barycenter to the origin
  50079. for (v = 0; v < shape.length; v++) {
  50080. shape[v].subtractInPlace(barycenter);
  50081. }
  50082. var bInfo;
  50083. if (this._particlesIntersect) {
  50084. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50085. }
  50086. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  50087. // add the particle in the SPS
  50088. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50089. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  50090. // initialize the particle position
  50091. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50092. this._index += shape.length;
  50093. idx++;
  50094. this.nbParticles++;
  50095. this._shapeCounter++;
  50096. f += size;
  50097. }
  50098. return this;
  50099. };
  50100. //reset copy
  50101. SolidParticleSystem.prototype._resetCopy = function () {
  50102. this._copy.position.x = 0;
  50103. this._copy.position.y = 0;
  50104. this._copy.position.z = 0;
  50105. this._copy.rotation.x = 0;
  50106. this._copy.rotation.y = 0;
  50107. this._copy.rotation.z = 0;
  50108. this._copy.rotationQuaternion = null;
  50109. this._copy.scaling.x = 1;
  50110. this._copy.scaling.y = 1;
  50111. this._copy.scaling.z = 1;
  50112. this._copy.uvs.x = 0;
  50113. this._copy.uvs.y = 0;
  50114. this._copy.uvs.z = 1;
  50115. this._copy.uvs.w = 1;
  50116. this._copy.color = null;
  50117. };
  50118. // _meshBuilder : inserts the shape model in the global SPS mesh
  50119. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50120. var i;
  50121. var u = 0;
  50122. var c = 0;
  50123. var n = 0;
  50124. this._resetCopy();
  50125. if (options && options.positionFunction) {
  50126. options.positionFunction(this._copy, idx, idxInShape);
  50127. }
  50128. if (this._copy.rotationQuaternion) {
  50129. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50130. }
  50131. else {
  50132. this._yaw = this._copy.rotation.y;
  50133. this._pitch = this._copy.rotation.x;
  50134. this._roll = this._copy.rotation.z;
  50135. this._quaternionRotationYPR();
  50136. }
  50137. this._quaternionToRotationMatrix();
  50138. for (i = 0; i < shape.length; i++) {
  50139. this._vertex.x = shape[i].x;
  50140. this._vertex.y = shape[i].y;
  50141. this._vertex.z = shape[i].z;
  50142. if (options && options.vertexFunction) {
  50143. options.vertexFunction(this._copy, this._vertex, i);
  50144. }
  50145. this._vertex.x *= this._copy.scaling.x;
  50146. this._vertex.y *= this._copy.scaling.y;
  50147. this._vertex.z *= this._copy.scaling.z;
  50148. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50149. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50150. if (meshUV) {
  50151. 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);
  50152. u += 2;
  50153. }
  50154. if (this._copy.color) {
  50155. this._color = this._copy.color;
  50156. }
  50157. else if (meshCol && meshCol[c] !== undefined) {
  50158. this._color.r = meshCol[c];
  50159. this._color.g = meshCol[c + 1];
  50160. this._color.b = meshCol[c + 2];
  50161. this._color.a = meshCol[c + 3];
  50162. }
  50163. else {
  50164. this._color.r = 1;
  50165. this._color.g = 1;
  50166. this._color.b = 1;
  50167. this._color.a = 1;
  50168. }
  50169. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50170. c += 4;
  50171. if (!this.recomputeNormals && meshNor) {
  50172. this._normal.x = meshNor[n];
  50173. this._normal.y = meshNor[n + 1];
  50174. this._normal.z = meshNor[n + 2];
  50175. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  50176. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50177. n += 3;
  50178. }
  50179. }
  50180. for (i = 0; i < meshInd.length; i++) {
  50181. indices.push(p + meshInd[i]);
  50182. }
  50183. if (this._pickable) {
  50184. var nbfaces = meshInd.length / 3;
  50185. for (i = 0; i < nbfaces; i++) {
  50186. this.pickedParticles.push({ idx: idx, faceId: i });
  50187. }
  50188. }
  50189. };
  50190. // returns a shape array from positions array
  50191. SolidParticleSystem.prototype._posToShape = function (positions) {
  50192. var shape = [];
  50193. for (var i = 0; i < positions.length; i += 3) {
  50194. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50195. }
  50196. return shape;
  50197. };
  50198. // returns a shapeUV array from a Vector4 uvs
  50199. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50200. var shapeUV = [];
  50201. if (uvs) {
  50202. for (var i = 0; i < uvs.length; i++)
  50203. shapeUV.push(uvs[i]);
  50204. }
  50205. return shapeUV;
  50206. };
  50207. // adds a new particle object in the particles array
  50208. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  50209. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  50210. };
  50211. /**
  50212. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50213. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50214. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  50215. * `nb` (positive integer) the number of particles to be created from this model
  50216. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  50217. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  50218. */
  50219. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50220. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50221. var meshInd = mesh.getIndices();
  50222. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50223. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50224. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50225. var bbInfo;
  50226. if (this._particlesIntersect) {
  50227. bbInfo = mesh.getBoundingInfo();
  50228. }
  50229. var shape = this._posToShape(meshPos);
  50230. var shapeUV = this._uvsToShapeUV(meshUV);
  50231. var posfunc = options ? options.positionFunction : null;
  50232. var vtxfunc = options ? options.vertexFunction : null;
  50233. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  50234. // particles
  50235. var idx = this.nbParticles;
  50236. for (var i = 0; i < nb; i++) {
  50237. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50238. if (this._updatable) {
  50239. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  50240. }
  50241. this._index += shape.length;
  50242. idx++;
  50243. }
  50244. this.nbParticles += nb;
  50245. this._shapeCounter++;
  50246. return this._shapeCounter - 1;
  50247. };
  50248. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50249. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50250. this._resetCopy();
  50251. if (particle._model._positionFunction) {
  50252. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50253. }
  50254. if (this._copy.rotationQuaternion) {
  50255. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50256. }
  50257. else {
  50258. this._yaw = this._copy.rotation.y;
  50259. this._pitch = this._copy.rotation.x;
  50260. this._roll = this._copy.rotation.z;
  50261. this._quaternionRotationYPR();
  50262. }
  50263. this._quaternionToRotationMatrix();
  50264. this._shape = particle._model._shape;
  50265. for (var pt = 0; pt < this._shape.length; pt++) {
  50266. this._vertex.x = this._shape[pt].x;
  50267. this._vertex.y = this._shape[pt].y;
  50268. this._vertex.z = this._shape[pt].z;
  50269. if (particle._model._vertexFunction) {
  50270. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50271. }
  50272. this._vertex.x *= this._copy.scaling.x;
  50273. this._vertex.y *= this._copy.scaling.y;
  50274. this._vertex.z *= this._copy.scaling.z;
  50275. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50276. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50277. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50278. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50279. }
  50280. particle.position.x = 0.0;
  50281. particle.position.y = 0.0;
  50282. particle.position.z = 0.0;
  50283. particle.rotation.x = 0.0;
  50284. particle.rotation.y = 0.0;
  50285. particle.rotation.z = 0.0;
  50286. particle.rotationQuaternion = null;
  50287. particle.scaling.x = 1.0;
  50288. particle.scaling.y = 1.0;
  50289. particle.scaling.z = 1.0;
  50290. };
  50291. /**
  50292. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50293. */
  50294. SolidParticleSystem.prototype.rebuildMesh = function () {
  50295. for (var p = 0; p < this.particles.length; p++) {
  50296. this._rebuildParticle(this.particles[p]);
  50297. }
  50298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50299. };
  50300. /**
  50301. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50302. * This method calls `updateParticle()` for each particle of the SPS.
  50303. * For an animated SPS, it is usually called within the render loop.
  50304. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50305. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50306. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50307. */
  50308. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50309. if (start === void 0) { start = 0; }
  50310. if (end === void 0) { end = this.nbParticles - 1; }
  50311. if (update === void 0) { update = true; }
  50312. if (!this._updatable) {
  50313. return;
  50314. }
  50315. // custom beforeUpdate
  50316. this.beforeUpdateParticles(start, end, update);
  50317. this._cam_axisX.x = 1.0;
  50318. this._cam_axisX.y = 0.0;
  50319. this._cam_axisX.z = 0.0;
  50320. this._cam_axisY.x = 0.0;
  50321. this._cam_axisY.y = 1.0;
  50322. this._cam_axisY.z = 0.0;
  50323. this._cam_axisZ.x = 0.0;
  50324. this._cam_axisZ.y = 0.0;
  50325. this._cam_axisZ.z = 1.0;
  50326. // if the particles will always face the camera
  50327. if (this.billboard) {
  50328. // compute the camera position and un-rotate it by the current mesh rotation
  50329. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  50330. this._quaternionToRotationMatrix();
  50331. this._rotMatrix.invertToRef(this._invertMatrix);
  50332. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  50333. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50334. this._cam_axisZ.normalize();
  50335. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  50336. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  50337. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50338. this._cam_axisY.normalize();
  50339. this._cam_axisX.normalize();
  50340. }
  50341. }
  50342. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50343. var idx = 0; // current position index in the global array positions32
  50344. var index = 0; // position start index in the global array positions32 of the current particle
  50345. var colidx = 0; // current color index in the global array colors32
  50346. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50347. var uvidx = 0; // current uv index in the global array uvs32
  50348. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50349. var pt = 0; // current index in the particle model shape
  50350. if (this.mesh.isFacetDataEnabled) {
  50351. this._computeBoundingBox = true;
  50352. }
  50353. if (this._computeBoundingBox) {
  50354. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50355. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50356. }
  50357. // particle loop
  50358. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  50359. for (var p = start; p <= end; p++) {
  50360. this._particle = this.particles[p];
  50361. this._shape = this._particle._model._shape;
  50362. this._shapeUV = this._particle._model._shapeUV;
  50363. // call to custom user function to update the particle properties
  50364. this.updateParticle(this._particle);
  50365. if (this._particle.isVisible) {
  50366. // particle rotation matrix
  50367. if (this.billboard) {
  50368. this._particle.rotation.x = 0.0;
  50369. this._particle.rotation.y = 0.0;
  50370. }
  50371. if (this._computeParticleRotation || this.billboard) {
  50372. if (this._particle.rotationQuaternion) {
  50373. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50374. }
  50375. else {
  50376. this._yaw = this._particle.rotation.y;
  50377. this._pitch = this._particle.rotation.x;
  50378. this._roll = this._particle.rotation.z;
  50379. this._quaternionRotationYPR();
  50380. }
  50381. this._quaternionToRotationMatrix();
  50382. }
  50383. // particle vertex loop
  50384. for (pt = 0; pt < this._shape.length; pt++) {
  50385. idx = index + pt * 3;
  50386. colidx = colorIndex + pt * 4;
  50387. uvidx = uvIndex + pt * 2;
  50388. this._vertex.x = this._shape[pt].x;
  50389. this._vertex.y = this._shape[pt].y;
  50390. this._vertex.z = this._shape[pt].z;
  50391. if (this._computeParticleVertex) {
  50392. this.updateParticleVertex(this._particle, this._vertex, pt);
  50393. }
  50394. // positions
  50395. this._vertex.x *= this._particle.scaling.x;
  50396. this._vertex.y *= this._particle.scaling.y;
  50397. this._vertex.z *= this._particle.scaling.z;
  50398. 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];
  50399. 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;
  50400. 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;
  50401. 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;
  50402. 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;
  50403. 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;
  50404. 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;
  50405. if (this._computeBoundingBox) {
  50406. if (this._positions32[idx] < this._minimum.x) {
  50407. this._minimum.x = this._positions32[idx];
  50408. }
  50409. if (this._positions32[idx] > this._maximum.x) {
  50410. this._maximum.x = this._positions32[idx];
  50411. }
  50412. if (this._positions32[idx + 1] < this._minimum.y) {
  50413. this._minimum.y = this._positions32[idx + 1];
  50414. }
  50415. if (this._positions32[idx + 1] > this._maximum.y) {
  50416. this._maximum.y = this._positions32[idx + 1];
  50417. }
  50418. if (this._positions32[idx + 2] < this._minimum.z) {
  50419. this._minimum.z = this._positions32[idx + 2];
  50420. }
  50421. if (this._positions32[idx + 2] > this._maximum.z) {
  50422. this._maximum.z = this._positions32[idx + 2];
  50423. }
  50424. }
  50425. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50426. if (!this._computeParticleVertex) {
  50427. this._normal.x = this._fixedNormal32[idx];
  50428. this._normal.y = this._fixedNormal32[idx + 1];
  50429. this._normal.z = this._fixedNormal32[idx + 2];
  50430. 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]);
  50431. 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]);
  50432. 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]);
  50433. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50434. 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;
  50435. 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;
  50436. }
  50437. if (this._computeParticleColor) {
  50438. this._colors32[colidx] = this._particle.color.r;
  50439. this._colors32[colidx + 1] = this._particle.color.g;
  50440. this._colors32[colidx + 2] = this._particle.color.b;
  50441. this._colors32[colidx + 3] = this._particle.color.a;
  50442. }
  50443. if (this._computeParticleTexture) {
  50444. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50445. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50446. }
  50447. }
  50448. }
  50449. else {
  50450. for (pt = 0; pt < this._shape.length; pt++) {
  50451. idx = index + pt * 3;
  50452. colidx = colorIndex + pt * 4;
  50453. uvidx = uvIndex + pt * 2;
  50454. this._positions32[idx] = this._camera.position.x;
  50455. this._positions32[idx + 1] = this._camera.position.y;
  50456. this._positions32[idx + 2] = this._camera.position.z;
  50457. this._normals32[idx] = 0.0;
  50458. this._normals32[idx + 1] = 0.0;
  50459. this._normals32[idx + 2] = 0.0;
  50460. if (this._computeParticleColor) {
  50461. this._colors32[colidx] = this._particle.color.r;
  50462. this._colors32[colidx + 1] = this._particle.color.g;
  50463. this._colors32[colidx + 2] = this._particle.color.b;
  50464. this._colors32[colidx + 3] = this._particle.color.a;
  50465. }
  50466. if (this._computeParticleTexture) {
  50467. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50468. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50469. }
  50470. }
  50471. }
  50472. // if the particle intersections must be computed : update the bbInfo
  50473. if (this._particlesIntersect) {
  50474. var bInfo = this._particle._boundingInfo;
  50475. var bBox = bInfo.boundingBox;
  50476. var bSphere = bInfo.boundingSphere;
  50477. if (!this._bSphereOnly) {
  50478. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50479. for (var b = 0; b < bBox.vectors.length; b++) {
  50480. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50481. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50482. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50483. 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];
  50484. 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;
  50485. 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;
  50486. 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;
  50487. 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;
  50488. 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;
  50489. 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;
  50490. }
  50491. bBox._update(this.mesh._worldMatrix);
  50492. }
  50493. // place and scale the particle bouding sphere in the SPS local system, then update it
  50494. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50495. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50496. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50497. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50498. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50499. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50500. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50501. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50502. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50503. 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));
  50504. bSphere._update(this.mesh._worldMatrix);
  50505. }
  50506. // increment indexes for the next particle
  50507. index = idx + 3;
  50508. colorIndex = colidx + 4;
  50509. uvIndex = uvidx + 2;
  50510. }
  50511. // if the VBO must be updated
  50512. if (update) {
  50513. if (this._computeParticleColor) {
  50514. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50515. }
  50516. if (this._computeParticleTexture) {
  50517. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50518. }
  50519. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50520. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50521. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50522. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50523. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50524. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  50525. for (var i = 0; i < this._normals32.length; i++) {
  50526. this._fixedNormal32[i] = this._normals32[i];
  50527. }
  50528. }
  50529. if (!this.mesh.areNormalsFrozen) {
  50530. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50531. }
  50532. }
  50533. }
  50534. if (this._computeBoundingBox) {
  50535. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50536. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50537. }
  50538. this.afterUpdateParticles(start, end, update);
  50539. };
  50540. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50541. this._halfroll = this._roll * 0.5;
  50542. this._halfpitch = this._pitch * 0.5;
  50543. this._halfyaw = this._yaw * 0.5;
  50544. this._sinRoll = Math.sin(this._halfroll);
  50545. this._cosRoll = Math.cos(this._halfroll);
  50546. this._sinPitch = Math.sin(this._halfpitch);
  50547. this._cosPitch = Math.cos(this._halfpitch);
  50548. this._sinYaw = Math.sin(this._halfyaw);
  50549. this._cosYaw = Math.cos(this._halfyaw);
  50550. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50551. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50552. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50553. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50554. };
  50555. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50556. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50557. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50558. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50559. this._rotMatrix.m[3] = 0;
  50560. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50561. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50562. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50563. this._rotMatrix.m[7] = 0;
  50564. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50565. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50566. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50567. this._rotMatrix.m[11] = 0;
  50568. this._rotMatrix.m[12] = 0;
  50569. this._rotMatrix.m[13] = 0;
  50570. this._rotMatrix.m[14] = 0;
  50571. this._rotMatrix.m[15] = 1.0;
  50572. };
  50573. /**
  50574. * Disposes the SPS
  50575. */
  50576. SolidParticleSystem.prototype.dispose = function () {
  50577. this.mesh.dispose();
  50578. this.vars = null;
  50579. // drop references to internal big arrays for the GC
  50580. this._positions = null;
  50581. this._indices = null;
  50582. this._normals = null;
  50583. this._uvs = null;
  50584. this._colors = null;
  50585. this._positions32 = null;
  50586. this._normals32 = null;
  50587. this._fixedNormal32 = null;
  50588. this._uvs32 = null;
  50589. this._colors32 = null;
  50590. this.pickedParticles = null;
  50591. };
  50592. /**
  50593. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50594. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50595. */
  50596. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50597. if (!this._isVisibilityBoxLocked) {
  50598. this.mesh.refreshBoundingInfo();
  50599. }
  50600. };
  50601. /**
  50602. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50603. * @param size the size (float) of the visibility box
  50604. * note : this doesn't lock the SPS mesh bounding box.
  50605. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50606. */
  50607. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50608. var vis = size / 2;
  50609. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50610. };
  50611. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50612. // getter and setter
  50613. get: function () {
  50614. return this._alwaysVisible;
  50615. },
  50616. /**
  50617. * Sets the SPS as always visible or not
  50618. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50619. */
  50620. set: function (val) {
  50621. this._alwaysVisible = val;
  50622. this.mesh.alwaysSelectAsActiveMesh = val;
  50623. },
  50624. enumerable: true,
  50625. configurable: true
  50626. });
  50627. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50628. get: function () {
  50629. return this._isVisibilityBoxLocked;
  50630. },
  50631. /**
  50632. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50633. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50634. */
  50635. set: function (val) {
  50636. this._isVisibilityBoxLocked = val;
  50637. this.mesh.getBoundingInfo().isLocked = val;
  50638. },
  50639. enumerable: true,
  50640. configurable: true
  50641. });
  50642. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50643. // getters
  50644. get: function () {
  50645. return this._computeParticleRotation;
  50646. },
  50647. // Optimizer setters
  50648. /**
  50649. * Tells to `setParticles()` to compute the particle rotations or not.
  50650. * Default value : true. The SPS is faster when it's set to false.
  50651. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50652. */
  50653. set: function (val) {
  50654. this._computeParticleRotation = val;
  50655. },
  50656. enumerable: true,
  50657. configurable: true
  50658. });
  50659. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50660. get: function () {
  50661. return this._computeParticleColor;
  50662. },
  50663. /**
  50664. * Tells to `setParticles()` to compute the particle colors or not.
  50665. * Default value : true. The SPS is faster when it's set to false.
  50666. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50667. */
  50668. set: function (val) {
  50669. this._computeParticleColor = val;
  50670. },
  50671. enumerable: true,
  50672. configurable: true
  50673. });
  50674. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50675. get: function () {
  50676. return this._computeParticleTexture;
  50677. },
  50678. /**
  50679. * Tells to `setParticles()` to compute the particle textures or not.
  50680. * Default value : true. The SPS is faster when it's set to false.
  50681. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50682. */
  50683. set: function (val) {
  50684. this._computeParticleTexture = val;
  50685. },
  50686. enumerable: true,
  50687. configurable: true
  50688. });
  50689. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50690. get: function () {
  50691. return this._computeParticleVertex;
  50692. },
  50693. /**
  50694. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50695. * Default value : false. The SPS is faster when it's set to false.
  50696. * Note : the particle custom vertex positions aren't stored values.
  50697. */
  50698. set: function (val) {
  50699. this._computeParticleVertex = val;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50705. get: function () {
  50706. return this._computeBoundingBox;
  50707. },
  50708. /**
  50709. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50710. */
  50711. set: function (val) {
  50712. this._computeBoundingBox = val;
  50713. },
  50714. enumerable: true,
  50715. configurable: true
  50716. });
  50717. // =======================================================================
  50718. // Particle behavior logic
  50719. // these following methods may be overwritten by the user to fit his needs
  50720. /**
  50721. * This function does nothing. It may be overwritten to set all the particle first values.
  50722. * The SPS doesn't call this function, you may have to call it by your own.
  50723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50724. */
  50725. SolidParticleSystem.prototype.initParticles = function () {
  50726. };
  50727. /**
  50728. * This function does nothing. It may be overwritten to recycle a particle.
  50729. * The SPS doesn't call this function, you may have to call it by your own.
  50730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50731. */
  50732. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50733. return particle;
  50734. };
  50735. /**
  50736. * Updates a particle : this function should be overwritten by the user.
  50737. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50738. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50739. * ex : just set a particle position or velocity and recycle conditions
  50740. */
  50741. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50742. return particle;
  50743. };
  50744. /**
  50745. * Updates a vertex of a particle : it can be overwritten by the user.
  50746. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50747. * @param particle the current particle
  50748. * @param vertex the current index of the current particle
  50749. * @param pt the index of the current vertex in the particle shape
  50750. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50751. * ex : just set a vertex particle position
  50752. */
  50753. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50754. return vertex;
  50755. };
  50756. /**
  50757. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50758. * This does nothing and may be overwritten by the user.
  50759. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50760. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50761. * @param update the boolean update value actually passed to setParticles()
  50762. */
  50763. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50764. };
  50765. /**
  50766. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50767. * This will be passed three parameters.
  50768. * This does nothing and may be overwritten by the user.
  50769. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50770. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50771. * @param update the boolean update value actually passed to setParticles()
  50772. */
  50773. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50774. };
  50775. return SolidParticleSystem;
  50776. }());
  50777. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50778. })(BABYLON || (BABYLON = {}));
  50779. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50780. var BABYLON;
  50781. (function (BABYLON) {
  50782. var Internals;
  50783. (function (Internals) {
  50784. var FileFaceOrientation = (function () {
  50785. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50786. this.name = name;
  50787. this.worldAxisForNormal = worldAxisForNormal;
  50788. this.worldAxisForFileX = worldAxisForFileX;
  50789. this.worldAxisForFileY = worldAxisForFileY;
  50790. }
  50791. return FileFaceOrientation;
  50792. }());
  50793. ;
  50794. /**
  50795. * Helper class dealing with the extraction of spherical polynomial dataArray
  50796. * from a cube map.
  50797. */
  50798. var CubeMapToSphericalPolynomialTools = (function () {
  50799. function CubeMapToSphericalPolynomialTools() {
  50800. }
  50801. /**
  50802. * Converts a cubemap to the according Spherical Polynomial data.
  50803. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50804. *
  50805. * @param cubeInfo The Cube map to extract the information from.
  50806. * @return The Spherical Polynomial data.
  50807. */
  50808. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50809. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50810. var totalSolidAngle = 0.0;
  50811. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50812. var du = 2.0 / cubeInfo.size;
  50813. var dv = du;
  50814. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50815. var minUV = du * 0.5 - 1.0;
  50816. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50817. var fileFace = this.FileFaces[faceIndex];
  50818. var dataArray = cubeInfo[fileFace.name];
  50819. var v = minUV;
  50820. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50821. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50822. // Because SP is still linear, so summation is fine in that basis.
  50823. for (var y = 0; y < cubeInfo.size; y++) {
  50824. var u = minUV;
  50825. for (var x = 0; x < cubeInfo.size; x++) {
  50826. // World direction (not normalised)
  50827. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50828. worldDirection.normalize();
  50829. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50830. if (1) {
  50831. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50832. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50833. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50834. var color = new BABYLON.Color3(r, g, b);
  50835. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50836. }
  50837. else {
  50838. if (faceIndex == 0) {
  50839. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50840. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50841. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50842. }
  50843. else if (faceIndex == 1) {
  50844. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50845. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50846. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50847. }
  50848. else if (faceIndex == 2) {
  50849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50850. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50851. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50852. }
  50853. else if (faceIndex == 3) {
  50854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50855. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50856. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50857. }
  50858. else if (faceIndex == 4) {
  50859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50861. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50862. }
  50863. else if (faceIndex == 5) {
  50864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50866. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50867. }
  50868. 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]);
  50869. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50870. }
  50871. totalSolidAngle += deltaSolidAngle;
  50872. u += du;
  50873. }
  50874. v += dv;
  50875. }
  50876. }
  50877. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50878. var correction = correctSolidAngle / totalSolidAngle;
  50879. sphericalHarmonics.scale(correction);
  50880. // Additionally scale by pi -- audit needed
  50881. sphericalHarmonics.scale(1.0 / Math.PI);
  50882. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50883. };
  50884. return CubeMapToSphericalPolynomialTools;
  50885. }());
  50886. CubeMapToSphericalPolynomialTools.FileFaces = [
  50887. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50888. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50889. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50890. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50891. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50892. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50893. ];
  50894. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50895. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50896. })(BABYLON || (BABYLON = {}));
  50897. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50898. var BABYLON;
  50899. (function (BABYLON) {
  50900. var Internals;
  50901. (function (Internals) {
  50902. /**
  50903. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50904. */
  50905. var PanoramaToCubeMapTools = (function () {
  50906. function PanoramaToCubeMapTools() {
  50907. }
  50908. /**
  50909. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50910. *
  50911. * @param float32Array The source data.
  50912. * @param inputWidth The width of the input panorama.
  50913. * @param inputhHeight The height of the input panorama.
  50914. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50915. * @return The cubemap data
  50916. */
  50917. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50918. if (!float32Array) {
  50919. throw "ConvertPanoramaToCubemap: input cannot be null";
  50920. }
  50921. if (float32Array.length != inputWidth * inputHeight * 3) {
  50922. throw "ConvertPanoramaToCubemap: input size is wrong";
  50923. }
  50924. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50925. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50926. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50927. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50928. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50929. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50930. return {
  50931. front: textureFront,
  50932. back: textureBack,
  50933. left: textureLeft,
  50934. right: textureRight,
  50935. up: textureUp,
  50936. down: textureDown,
  50937. size: size
  50938. };
  50939. };
  50940. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50941. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50942. var textureArray = new Float32Array(buffer);
  50943. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50944. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50945. var dy = 1 / texSize;
  50946. var fy = 0;
  50947. for (var y = 0; y < texSize; y++) {
  50948. var xv1 = faceData[0];
  50949. var xv2 = faceData[2];
  50950. for (var x = 0; x < texSize; x++) {
  50951. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50952. v.normalize();
  50953. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50954. // 3 channels per pixels
  50955. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50956. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50957. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50958. xv1 = xv1.add(rotDX1);
  50959. xv2 = xv2.add(rotDX2);
  50960. }
  50961. fy += dy;
  50962. }
  50963. return textureArray;
  50964. };
  50965. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50966. var theta = Math.atan2(vDir.z, vDir.x);
  50967. var phi = Math.acos(vDir.y);
  50968. while (theta < -Math.PI)
  50969. theta += 2 * Math.PI;
  50970. while (theta > Math.PI)
  50971. theta -= 2 * Math.PI;
  50972. var dx = theta / Math.PI;
  50973. var dy = phi / Math.PI;
  50974. // recenter.
  50975. dx = dx * 0.5 + 0.5;
  50976. var px = Math.round(dx * inputWidth);
  50977. if (px < 0)
  50978. px = 0;
  50979. else if (px >= inputWidth)
  50980. px = inputWidth - 1;
  50981. var py = Math.round(dy * inputHeight);
  50982. if (py < 0)
  50983. py = 0;
  50984. else if (py >= inputHeight)
  50985. py = inputHeight - 1;
  50986. var inputY = (inputHeight - py - 1);
  50987. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50988. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50989. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50990. return {
  50991. r: r,
  50992. g: g,
  50993. b: b
  50994. };
  50995. };
  50996. return PanoramaToCubeMapTools;
  50997. }());
  50998. PanoramaToCubeMapTools.FACE_FRONT = [
  50999. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51000. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51001. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51002. new BABYLON.Vector3(1.0, 1.0, -1.0)
  51003. ];
  51004. PanoramaToCubeMapTools.FACE_BACK = [
  51005. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51006. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51007. new BABYLON.Vector3(1.0, 1.0, 1.0),
  51008. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  51009. ];
  51010. PanoramaToCubeMapTools.FACE_RIGHT = [
  51011. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51012. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51013. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51014. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51015. ];
  51016. PanoramaToCubeMapTools.FACE_LEFT = [
  51017. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51018. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51019. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51020. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  51021. ];
  51022. PanoramaToCubeMapTools.FACE_DOWN = [
  51023. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51024. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51025. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51026. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51027. ];
  51028. PanoramaToCubeMapTools.FACE_UP = [
  51029. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51030. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51031. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51032. new BABYLON.Vector3(1.0, -1.0, -1.0)
  51033. ];
  51034. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  51035. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51036. })(BABYLON || (BABYLON = {}));
  51037. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  51038. var BABYLON;
  51039. (function (BABYLON) {
  51040. var Internals;
  51041. (function (Internals) {
  51042. ;
  51043. /**
  51044. * This groups tools to convert HDR texture to native colors array.
  51045. */
  51046. var HDRTools = (function () {
  51047. function HDRTools() {
  51048. }
  51049. HDRTools.Ldexp = function (mantissa, exponent) {
  51050. if (exponent > 1023) {
  51051. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  51052. }
  51053. if (exponent < -1074) {
  51054. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  51055. }
  51056. return mantissa * Math.pow(2, exponent);
  51057. };
  51058. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  51059. if (exponent > 0) {
  51060. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  51061. float32array[index + 0] = red * exponent;
  51062. float32array[index + 1] = green * exponent;
  51063. float32array[index + 2] = blue * exponent;
  51064. }
  51065. else {
  51066. float32array[index + 0] = 0;
  51067. float32array[index + 1] = 0;
  51068. float32array[index + 2] = 0;
  51069. }
  51070. };
  51071. HDRTools.readStringLine = function (uint8array, startIndex) {
  51072. var line = "";
  51073. var character = "";
  51074. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  51075. character = String.fromCharCode(uint8array[i]);
  51076. if (character == "\n") {
  51077. break;
  51078. }
  51079. line += character;
  51080. }
  51081. return line;
  51082. };
  51083. /**
  51084. * Reads header information from an RGBE texture stored in a native array.
  51085. * More information on this format are available here:
  51086. * https://en.wikipedia.org/wiki/RGBE_image_format
  51087. *
  51088. * @param uint8array The binary file stored in native array.
  51089. * @return The header information.
  51090. */
  51091. HDRTools.RGBE_ReadHeader = function (uint8array) {
  51092. var height = 0;
  51093. var width = 0;
  51094. var line = this.readStringLine(uint8array, 0);
  51095. if (line[0] != '#' || line[1] != '?') {
  51096. throw "Bad HDR Format.";
  51097. }
  51098. var endOfHeader = false;
  51099. var findFormat = false;
  51100. var lineIndex = 0;
  51101. do {
  51102. lineIndex += (line.length + 1);
  51103. line = this.readStringLine(uint8array, lineIndex);
  51104. if (line == "FORMAT=32-bit_rle_rgbe") {
  51105. findFormat = true;
  51106. }
  51107. else if (line.length == 0) {
  51108. endOfHeader = true;
  51109. }
  51110. } while (!endOfHeader);
  51111. if (!findFormat) {
  51112. throw "HDR Bad header format, unsupported FORMAT";
  51113. }
  51114. lineIndex += (line.length + 1);
  51115. line = this.readStringLine(uint8array, lineIndex);
  51116. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  51117. var match = sizeRegexp.exec(line);
  51118. // TODO. Support +Y and -X if needed.
  51119. if (match.length < 3) {
  51120. throw "HDR Bad header format, no size";
  51121. }
  51122. width = parseInt(match[2]);
  51123. height = parseInt(match[1]);
  51124. if (width < 8 || width > 0x7fff) {
  51125. throw "HDR Bad header format, unsupported size";
  51126. }
  51127. lineIndex += (line.length + 1);
  51128. return {
  51129. height: height,
  51130. width: width,
  51131. dataPosition: lineIndex
  51132. };
  51133. };
  51134. /**
  51135. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  51136. * This RGBE texture needs to store the information as a panorama.
  51137. *
  51138. * More information on this format are available here:
  51139. * https://en.wikipedia.org/wiki/RGBE_image_format
  51140. *
  51141. * @param buffer The binary file stored in an array buffer.
  51142. * @param size The expected size of the extracted cubemap.
  51143. * @return The Cube Map information.
  51144. */
  51145. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51146. var uint8array = new Uint8Array(buffer);
  51147. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51148. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51149. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51150. return cubeMapData;
  51151. };
  51152. /**
  51153. * Returns the pixels data extracted from an RGBE texture.
  51154. * This pixels will be stored left to right up to down in the R G B order in one array.
  51155. *
  51156. * More information on this format are available here:
  51157. * https://en.wikipedia.org/wiki/RGBE_image_format
  51158. *
  51159. * @param uint8array The binary file stored in an array buffer.
  51160. * @param hdrInfo The header information of the file.
  51161. * @return The pixels data in RGB right to left up to down order.
  51162. */
  51163. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51164. // Keep for multi format supports.
  51165. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51166. };
  51167. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51168. var num_scanlines = hdrInfo.height;
  51169. var scanline_width = hdrInfo.width;
  51170. var a, b, c, d, count;
  51171. var dataIndex = hdrInfo.dataPosition;
  51172. var index = 0, endIndex = 0, i = 0;
  51173. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51174. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51175. // 3 channels of 4 bytes per pixel in float.
  51176. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51177. var resultArray = new Float32Array(resultBuffer);
  51178. // read in each successive scanline
  51179. while (num_scanlines > 0) {
  51180. a = uint8array[dataIndex++];
  51181. b = uint8array[dataIndex++];
  51182. c = uint8array[dataIndex++];
  51183. d = uint8array[dataIndex++];
  51184. if (a != 2 || b != 2 || (c & 0x80)) {
  51185. // this file is not run length encoded
  51186. throw "HDR Bad header format, not RLE";
  51187. }
  51188. if (((c << 8) | d) != scanline_width) {
  51189. throw "HDR Bad header format, wrong scan line width";
  51190. }
  51191. index = 0;
  51192. // read each of the four channels for the scanline into the buffer
  51193. for (i = 0; i < 4; i++) {
  51194. endIndex = (i + 1) * scanline_width;
  51195. while (index < endIndex) {
  51196. a = uint8array[dataIndex++];
  51197. b = uint8array[dataIndex++];
  51198. if (a > 128) {
  51199. // a run of the same value
  51200. count = a - 128;
  51201. if ((count == 0) || (count > endIndex - index)) {
  51202. throw "HDR Bad Format, bad scanline data (run)";
  51203. }
  51204. while (count-- > 0) {
  51205. scanLineArray[index++] = b;
  51206. }
  51207. }
  51208. else {
  51209. // a non-run
  51210. count = a;
  51211. if ((count == 0) || (count > endIndex - index)) {
  51212. throw "HDR Bad Format, bad scanline data (non-run)";
  51213. }
  51214. scanLineArray[index++] = b;
  51215. if (--count > 0) {
  51216. for (var j = 0; j < count; j++) {
  51217. scanLineArray[index++] = uint8array[dataIndex++];
  51218. }
  51219. }
  51220. }
  51221. }
  51222. }
  51223. // now convert data from buffer into floats
  51224. for (i = 0; i < scanline_width; i++) {
  51225. a = scanLineArray[i];
  51226. b = scanLineArray[i + scanline_width];
  51227. c = scanLineArray[i + 2 * scanline_width];
  51228. d = scanLineArray[i + 3 * scanline_width];
  51229. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51230. }
  51231. num_scanlines--;
  51232. }
  51233. return resultArray;
  51234. };
  51235. return HDRTools;
  51236. }());
  51237. Internals.HDRTools = HDRTools;
  51238. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51239. })(BABYLON || (BABYLON = {}));
  51240. //# sourceMappingURL=babylon.tools.hdr.js.map
  51241. //_______________________________________________________________
  51242. // Extracted from CubeMapGen:
  51243. // https://code.google.com/archive/p/cubemapgen/
  51244. //
  51245. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51246. //_______________________________________________________________
  51247. var BABYLON;
  51248. (function (BABYLON) {
  51249. var Internals;
  51250. (function (Internals) {
  51251. /**
  51252. * The bounding box information used during the conversion process.
  51253. */
  51254. var CMGBoundinBox = (function () {
  51255. function CMGBoundinBox() {
  51256. this.min = new BABYLON.Vector3(0, 0, 0);
  51257. this.max = new BABYLON.Vector3(0, 0, 0);
  51258. this.clear();
  51259. }
  51260. CMGBoundinBox.prototype.clear = function () {
  51261. this.min.x = CMGBoundinBox.MAX;
  51262. this.min.y = CMGBoundinBox.MAX;
  51263. this.min.z = CMGBoundinBox.MAX;
  51264. this.max.x = CMGBoundinBox.MIN;
  51265. this.max.y = CMGBoundinBox.MIN;
  51266. this.max.z = CMGBoundinBox.MIN;
  51267. };
  51268. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51269. this.min.x = Math.min(this.min.x, x);
  51270. this.min.y = Math.min(this.min.y, y);
  51271. this.min.z = Math.min(this.min.z, z);
  51272. this.max.x = Math.max(this.max.x, x);
  51273. this.max.y = Math.max(this.max.y, y);
  51274. this.max.z = Math.max(this.max.z, z);
  51275. };
  51276. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51277. this.min.x = Math.max(this.min.x, x);
  51278. this.min.y = Math.max(this.min.y, y);
  51279. this.min.z = Math.max(this.min.z, z);
  51280. };
  51281. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51282. this.max.x = Math.min(this.max.x, x);
  51283. this.max.y = Math.min(this.max.y, y);
  51284. this.max.z = Math.min(this.max.z, z);
  51285. };
  51286. CMGBoundinBox.prototype.empty = function () {
  51287. if ((this.min.x > this.max.y) ||
  51288. (this.min.y > this.max.y) ||
  51289. (this.min.z > this.max.y)) {
  51290. return true;
  51291. }
  51292. else {
  51293. return false;
  51294. }
  51295. };
  51296. return CMGBoundinBox;
  51297. }());
  51298. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51299. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51300. /**
  51301. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51302. * required by the glossinees of a material.
  51303. *
  51304. * This only supports the cosine drop power as well as Warp fixup generation method.
  51305. *
  51306. * This is using the process from CubeMapGen described here:
  51307. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51308. */
  51309. var PMREMGenerator = (function () {
  51310. /**
  51311. * Constructor of the generator.
  51312. *
  51313. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51314. * @param inputSize The size of the cubemap faces
  51315. * @param outputSize The size of the output cubemap faces
  51316. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51317. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51318. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51319. * @param specularPower The max specular level of the desired cubemap
  51320. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51321. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51322. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51323. */
  51324. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51325. this.input = input;
  51326. this.inputSize = inputSize;
  51327. this.outputSize = outputSize;
  51328. this.maxNumMipLevels = maxNumMipLevels;
  51329. this.numChannels = numChannels;
  51330. this.isFloat = isFloat;
  51331. this.specularPower = specularPower;
  51332. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51333. this.excludeBase = excludeBase;
  51334. this.fixup = fixup;
  51335. this._outputSurface = [];
  51336. this._numMipLevels = 0;
  51337. }
  51338. /**
  51339. * Launches the filter process and return the result.
  51340. *
  51341. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51342. */
  51343. PMREMGenerator.prototype.filterCubeMap = function () {
  51344. // Init cubemap processor
  51345. this.init();
  51346. // Filters the cubemap
  51347. this.filterCubeMapMipChain();
  51348. // Returns the filtered mips.
  51349. return this._outputSurface;
  51350. };
  51351. PMREMGenerator.prototype.init = function () {
  51352. var i;
  51353. var j;
  51354. var mipLevelSize;
  51355. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51356. if (this.maxNumMipLevels == 0) {
  51357. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51358. }
  51359. //first miplevel size
  51360. mipLevelSize = this.outputSize;
  51361. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51362. for (j = 0; j < this.maxNumMipLevels; j++) {
  51363. this._outputSurface.length++;
  51364. this._outputSurface[j] = [];
  51365. //Iterate over faces for output images
  51366. for (i = 0; i < 6; i++) {
  51367. this._outputSurface[j].length++;
  51368. // Initializes a new array for the output.
  51369. if (this.isFloat) {
  51370. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51371. }
  51372. else {
  51373. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51374. }
  51375. }
  51376. //next mip level is half size
  51377. mipLevelSize >>= 1;
  51378. this._numMipLevels++;
  51379. //terminate if mip chain becomes too small
  51380. if (mipLevelSize == 0) {
  51381. this.maxNumMipLevels = j;
  51382. return;
  51383. }
  51384. }
  51385. };
  51386. //--------------------------------------------------------------------------------------
  51387. //Cube map filtering and mip chain generation.
  51388. // the cube map filtereing is specified using a number of parameters:
  51389. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51390. // indicates the region of the hemisphere to filter over for each tap.
  51391. //
  51392. // Note that the top mip level is also a filtered version of the original input images
  51393. // as well in order to create mip chains for diffuse environment illumination.
  51394. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51395. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51396. //
  51397. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51398. // is a_InitialMipAngle
  51399. //
  51400. // The angle for the subsequent levels of the mip chain are specified by their parents
  51401. // filtering angle and a per-level scale and bias
  51402. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51403. //
  51404. //--------------------------------------------------------------------------------------
  51405. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51406. // First, take count of the lighting model to modify SpecularPower
  51407. // 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;
  51408. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51409. //Cone angle start (for generating subsequent mip levels)
  51410. var currentSpecularPower = this.specularPower;
  51411. //Build filter lookup tables based on the source miplevel size
  51412. this.precomputeFilterLookupTables(this.inputSize);
  51413. // Note that we need to filter the first level before generating mipmap
  51414. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51415. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51416. // TODO : Write a function to copy and scale the base mipmap in output
  51417. // I am just lazy here and just put a high specular power value, and do some if.
  51418. if (this.excludeBase && (levelIndex == 0)) {
  51419. // 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).
  51420. currentSpecularPower = 100000.0;
  51421. }
  51422. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51423. var srcCubeImage = this.input;
  51424. var dstCubeImage = this._outputSurface[levelIndex];
  51425. var dstSize = this.outputSize >> levelIndex;
  51426. // Compute required angle.
  51427. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51428. // filter cube surfaces
  51429. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51430. // fix seams
  51431. if (this.fixup) {
  51432. this.fixupCubeEdges(dstCubeImage, dstSize);
  51433. }
  51434. // Decrease the specular power to generate the mipmap chain
  51435. // TODO : Use another method for Exclude (see first comment at start of the function
  51436. if (this.excludeBase && (levelIndex == 0)) {
  51437. currentSpecularPower = this.specularPower;
  51438. }
  51439. currentSpecularPower *= this.cosinePowerDropPerMip;
  51440. }
  51441. };
  51442. //--------------------------------------------------------------------------------------
  51443. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51444. // It allow to optimize the texel to access base on the specular power.
  51445. //--------------------------------------------------------------------------------------
  51446. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51447. // We want to find the alpha such that:
  51448. // cos(alpha)^cosinePower = epsilon
  51449. // That's: acos(epsilon^(1/cosinePower))
  51450. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51451. var angle = 180.0;
  51452. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51453. angle *= 180.0 / Math.PI; // Convert to degree
  51454. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51455. return angle;
  51456. };
  51457. //--------------------------------------------------------------------------------------
  51458. //Builds the following lookup tables prior to filtering:
  51459. // -normalizer cube map
  51460. // -tap weight lookup table
  51461. //
  51462. //--------------------------------------------------------------------------------------
  51463. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51464. var srcTexelAngle;
  51465. var iCubeFace;
  51466. //clear pre-existing normalizer cube map
  51467. this._normCubeMap = [];
  51468. //Normalized vectors per cubeface and per-texel solid angle
  51469. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51470. };
  51471. //--------------------------------------------------------------------------------------
  51472. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51473. //
  51474. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51475. //
  51476. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51477. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51478. // below
  51479. //--------------------------------------------------------------------------------------
  51480. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51481. var iCubeFace;
  51482. var u;
  51483. var v;
  51484. //iterate over cube faces
  51485. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51486. //First three channels for norm cube, and last channel for solid angle
  51487. this._normCubeMap.push(new Float32Array(size * size * 4));
  51488. //fast texture walk, build normalizer cube map
  51489. var facesData = this.input[iCubeFace];
  51490. for (v = 0; v < size; v++) {
  51491. for (u = 0; u < size; u++) {
  51492. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51493. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51494. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51495. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51496. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51497. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51498. }
  51499. }
  51500. }
  51501. };
  51502. //--------------------------------------------------------------------------------------
  51503. // Convert cubemap face texel coordinates and face idx to 3D vector
  51504. // note the U and V coords are integer coords and range from 0 to size-1
  51505. // this routine can be used to generate a normalizer cube map
  51506. //--------------------------------------------------------------------------------------
  51507. // SL BEGIN
  51508. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51509. var nvcU;
  51510. var nvcV;
  51511. var tempVec;
  51512. // Change from original AMD code
  51513. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51514. // + 0.5f is for texel center addressing
  51515. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51516. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51517. // warp fixup
  51518. if (fixup && size > 1) {
  51519. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51520. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51521. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51522. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51523. }
  51524. // Get current vector
  51525. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51526. // U contribution
  51527. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51528. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51529. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51530. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51531. // V contribution and Sum
  51532. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51533. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51534. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51535. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51536. //add face axis
  51537. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51538. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51539. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51540. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51541. //normalize vector
  51542. PMREMGenerator._vectorTemp.normalize();
  51543. return PMREMGenerator._vectorTemp;
  51544. };
  51545. //--------------------------------------------------------------------------------------
  51546. // Convert 3D vector to cubemap face texel coordinates and face idx
  51547. // note the U and V coords are integer coords and range from 0 to size-1
  51548. // this routine can be used to generate a normalizer cube map
  51549. //
  51550. // returns face IDX and texel coords
  51551. //--------------------------------------------------------------------------------------
  51552. // SL BEGIN
  51553. /*
  51554. Mapping Texture Coordinates to Cube Map Faces
  51555. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51556. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51557. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51558. map arrangement in Pixar's RenderMan package.
  51559. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51560. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51561. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51562. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51563. the major axis direction). The target column in the table below explains how the major axis direction
  51564. maps to the 2D image of a particular cube map target.
  51565. major axis
  51566. direction target sc tc ma
  51567. ---------- --------------------------------- --- --- ---
  51568. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51569. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51570. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51571. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51572. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51573. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51574. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51575. an updated (s,t) is calculated as follows
  51576. s = ( sc/|ma| + 1 ) / 2
  51577. t = ( tc/|ma| + 1 ) / 2
  51578. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51579. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51580. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51581. */
  51582. // Note this method return U and V in range from 0 to size-1
  51583. // SL END
  51584. // Store the information in vector3 for convenience (faceindex, u, v)
  51585. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51586. var maxCoord;
  51587. var faceIdx;
  51588. //absolute value 3
  51589. var absX = Math.abs(x);
  51590. var absY = Math.abs(y);
  51591. var absZ = Math.abs(z);
  51592. if (absX >= absY && absX >= absZ) {
  51593. maxCoord = absX;
  51594. if (x >= 0) {
  51595. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51596. }
  51597. else {
  51598. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51599. }
  51600. }
  51601. else if (absY >= absX && absY >= absZ) {
  51602. maxCoord = absY;
  51603. if (y >= 0) {
  51604. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51605. }
  51606. else {
  51607. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51608. }
  51609. }
  51610. else {
  51611. maxCoord = absZ;
  51612. if (z >= 0) {
  51613. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51614. }
  51615. else {
  51616. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51617. }
  51618. }
  51619. //divide through by max coord so face vector lies on cube face
  51620. var scale = 1 / maxCoord;
  51621. x *= scale;
  51622. y *= scale;
  51623. z *= scale;
  51624. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51625. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51626. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51627. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51628. // Modify original AMD code to return value from 0 to Size - 1
  51629. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51630. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51631. PMREMGenerator._vectorTemp.x = faceIdx;
  51632. PMREMGenerator._vectorTemp.y = u;
  51633. PMREMGenerator._vectorTemp.z = v;
  51634. return PMREMGenerator._vectorTemp;
  51635. };
  51636. //--------------------------------------------------------------------------------------
  51637. //Original code from Ignacio CastaÒo
  51638. // This formula is from Manne ÷hrstrˆm's thesis.
  51639. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51640. // cube face and return the area of the projection of that portion on the
  51641. // surface of the sphere.
  51642. //--------------------------------------------------------------------------------------
  51643. PMREMGenerator.prototype.areaElement = function (x, y) {
  51644. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51645. };
  51646. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51647. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51648. // (+ 0.5f is for texel center addressing)
  51649. u = (2.0 * (u + 0.5) / size) - 1.0;
  51650. v = (2.0 * (v + 0.5) / size) - 1.0;
  51651. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51652. var invResolution = 1.0 / size;
  51653. // U and V are the -1..1 texture coordinate on the current face.
  51654. // Get projected area for this texel
  51655. var x0 = u - invResolution;
  51656. var y0 = v - invResolution;
  51657. var x1 = u + invResolution;
  51658. var y1 = v + invResolution;
  51659. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51660. return solidAngle;
  51661. };
  51662. //--------------------------------------------------------------------------------------
  51663. //The key to the speed of these filtering routines is to quickly define a per-face
  51664. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51665. // Later these pixels are selectively processed based on their dot products to see if
  51666. // they reside within the filtering cone.
  51667. //
  51668. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51669. // of the number of texels needed to be covered in width and height order to filter the
  51670. // region. the bounding box for the center taps face is defined first, and if the
  51671. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51672. // defined next
  51673. //--------------------------------------------------------------------------------------
  51674. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51675. // note that pixels within these regions may be rejected
  51676. // based on the anlge
  51677. var iCubeFace;
  51678. var u;
  51679. var v;
  51680. // bounding box per face to specify region to process
  51681. var filterExtents = [];
  51682. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51683. filterExtents.push(new CMGBoundinBox());
  51684. }
  51685. // min angle a src texel can cover (in degrees)
  51686. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51687. // angle about center tap to define filter cone
  51688. // filter angle is 1/2 the cone angle
  51689. var filterAngle = filterConeAngle / 2.0;
  51690. //ensure filter angle is larger than a texel
  51691. if (filterAngle < srcTexelAngle) {
  51692. filterAngle = srcTexelAngle;
  51693. }
  51694. //ensure filter cone is always smaller than the hemisphere
  51695. if (filterAngle > 90.0) {
  51696. filterAngle = 90.0;
  51697. }
  51698. // the maximum number of texels in 1D the filter cone angle will cover
  51699. // used to determine bounding box size for filter extents
  51700. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51701. // ensure conservative region always covers at least one texel
  51702. if (filterSize < 1) {
  51703. filterSize = 1;
  51704. }
  51705. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51706. // reside within the cone angle
  51707. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51708. // process required faces
  51709. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51710. //iterate over dst cube map face texel
  51711. for (v = 0; v < dstSize; v++) {
  51712. for (u = 0; u < dstSize; u++) {
  51713. //get center tap direction
  51714. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51715. //clear old per-face filter extents
  51716. this.clearFilterExtents(filterExtents);
  51717. //define per-face filter extents
  51718. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51719. //perform filtering of src faces using filter extents
  51720. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51721. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51722. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51723. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51724. }
  51725. }
  51726. }
  51727. };
  51728. //--------------------------------------------------------------------------------------
  51729. //Clear filter extents for the 6 cube map faces
  51730. //--------------------------------------------------------------------------------------
  51731. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51732. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51733. filterExtents[iCubeFaces].clear();
  51734. }
  51735. };
  51736. //--------------------------------------------------------------------------------------
  51737. //Define per-face bounding box filter extents
  51738. //
  51739. // These define conservative texel regions in each of the faces the filter can possibly
  51740. // process. When the pixels in the regions are actually processed, the dot product
  51741. // between the tap vector and the center tap vector is used to determine the weight of
  51742. // the tap and whether or not the tap is within the cone.
  51743. //
  51744. //--------------------------------------------------------------------------------------
  51745. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51746. //neighboring face and bleed over amount, and width of BBOX for
  51747. // left, right, top, and bottom edges of this face
  51748. var bleedOverAmount = [0, 0, 0, 0];
  51749. var bleedOverBBoxMin = [0, 0, 0, 0];
  51750. var bleedOverBBoxMax = [0, 0, 0, 0];
  51751. var neighborFace;
  51752. var neighborEdge;
  51753. var oppositeFaceIdx;
  51754. //get face idx, and u, v info from center tap dir
  51755. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51756. var faceIdx = result.x;
  51757. var u = result.y;
  51758. var v = result.z;
  51759. //define bbox size within face
  51760. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51761. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51762. filterExtents[faceIdx].clampMin(0, 0, 0);
  51763. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51764. //u and v extent in face corresponding to center tap
  51765. var minU = filterExtents[faceIdx].min.x;
  51766. var minV = filterExtents[faceIdx].min.y;
  51767. var maxU = filterExtents[faceIdx].max.x;
  51768. var maxV = filterExtents[faceIdx].max.y;
  51769. //bleed over amounts for face across u=0 edge (left)
  51770. bleedOverAmount[0] = (bboxSize - u);
  51771. bleedOverBBoxMin[0] = minV;
  51772. bleedOverBBoxMax[0] = maxV;
  51773. //bleed over amounts for face across u=1 edge (right)
  51774. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51775. bleedOverBBoxMin[1] = minV;
  51776. bleedOverBBoxMax[1] = maxV;
  51777. //bleed over to face across v=0 edge (up)
  51778. bleedOverAmount[2] = (bboxSize - v);
  51779. bleedOverBBoxMin[2] = minU;
  51780. bleedOverBBoxMax[2] = maxU;
  51781. //bleed over to face across v=1 edge (down)
  51782. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51783. bleedOverBBoxMin[3] = minU;
  51784. bleedOverBBoxMax[3] = maxU;
  51785. //compute bleed over regions in neighboring faces
  51786. for (var i = 0; i < 4; i++) {
  51787. if (bleedOverAmount[i] > 0) {
  51788. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51789. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51790. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51791. // be flipped: the cases are
  51792. // if a left edge mates with a left or bottom edge on the neighbor
  51793. // if a top edge mates with a top or right edge on the neighbor
  51794. // if a right edge mates with a right or top edge on the neighbor
  51795. // if a bottom edge mates with a bottom or left edge on the neighbor
  51796. //Seeing as the edges are enumerated as follows
  51797. // left =0
  51798. // right =1
  51799. // top =2
  51800. // bottom =3
  51801. //
  51802. // so if the edge enums are the same, or the sum of the enums == 3,
  51803. // the bbox needs to be flipped
  51804. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51805. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51806. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51807. }
  51808. //The way the bounding box is extended onto the neighboring face
  51809. // depends on which edge of neighboring face abuts with this one
  51810. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51811. case PMREMGenerator.CP_EDGE_LEFT:
  51812. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51813. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51814. break;
  51815. case PMREMGenerator.CP_EDGE_RIGHT:
  51816. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51817. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51818. break;
  51819. case PMREMGenerator.CP_EDGE_TOP:
  51820. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51821. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51822. break;
  51823. case PMREMGenerator.CP_EDGE_BOTTOM:
  51824. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51825. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51826. break;
  51827. }
  51828. //clamp filter extents in non-center tap faces to remain within surface
  51829. filterExtents[neighborFace].clampMin(0, 0, 0);
  51830. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51831. }
  51832. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51833. // from the center tap face, then process the opposite face entirely for now.
  51834. //Note that the cases in which this happens, what usually happens is that
  51835. // more than one edge bleeds onto the opposite face, and the bounding box
  51836. // encompasses the entire cube map face.
  51837. if (bleedOverAmount[i] > srcSize) {
  51838. //determine opposite face
  51839. switch (faceIdx) {
  51840. case PMREMGenerator.CP_FACE_X_POS:
  51841. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51842. break;
  51843. case PMREMGenerator.CP_FACE_X_NEG:
  51844. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51845. break;
  51846. case PMREMGenerator.CP_FACE_Y_POS:
  51847. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51848. break;
  51849. case PMREMGenerator.CP_FACE_Y_NEG:
  51850. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51851. break;
  51852. case PMREMGenerator.CP_FACE_Z_POS:
  51853. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51854. break;
  51855. case PMREMGenerator.CP_FACE_Z_NEG:
  51856. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51857. break;
  51858. default:
  51859. break;
  51860. }
  51861. //just encompass entire face for now
  51862. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51863. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51864. }
  51865. }
  51866. };
  51867. //--------------------------------------------------------------------------------------
  51868. //ProcessFilterExtents
  51869. // Process bounding box in each cube face
  51870. //
  51871. //--------------------------------------------------------------------------------------
  51872. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51873. //accumulators are 64-bit floats in order to have the precision needed
  51874. // over a summation of a large number of pixels
  51875. var dstAccum = [0, 0, 0, 0];
  51876. var weightAccum = 0;
  51877. var k = 0;
  51878. var nSrcChannels = this.numChannels;
  51879. // norm cube map and srcCubeMap have same face width
  51880. var faceWidth = srcSize;
  51881. //amount to add to pointer to move to next scanline in images
  51882. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51883. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51884. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51885. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51886. // iterate over cubefaces
  51887. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51888. //if bbox is non empty
  51889. if (!filterExtents[iFaceIdx].empty()) {
  51890. var uStart = filterExtents[iFaceIdx].min.x;
  51891. var vStart = filterExtents[iFaceIdx].min.y;
  51892. var uEnd = filterExtents[iFaceIdx].max.x;
  51893. var vEnd = filterExtents[iFaceIdx].max.y;
  51894. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51895. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51896. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51897. for (var v = vStart; v <= vEnd; v++) {
  51898. var normCubeRowWalk = 0;
  51899. var srcCubeRowWalk = 0;
  51900. for (var u = uStart; u <= uEnd; u++) {
  51901. //pointer to direction in cube map associated with texel
  51902. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51903. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51904. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51905. //check dot product to see if texel is within cone
  51906. var tapDotProd = texelVectX * centerTapDir.x +
  51907. texelVectY * centerTapDir.y +
  51908. texelVectZ * centerTapDir.z;
  51909. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51910. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51911. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51912. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51913. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51914. // so just adding one to specularpower do the trick.
  51915. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51916. //iterate over channels
  51917. for (k = 0; k < nSrcChannels; k++) {
  51918. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51919. srcCubeRowWalk++;
  51920. }
  51921. weightAccum += weight; //accumulate weight
  51922. }
  51923. else {
  51924. //step across source pixel
  51925. srcCubeRowWalk += nSrcChannels;
  51926. }
  51927. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51928. }
  51929. startIndexNormCubeMap += normCubePitch;
  51930. startIndexSrcCubeMap += srcCubePitch;
  51931. }
  51932. }
  51933. }
  51934. //divide through by weights if weight is non zero
  51935. if (weightAccum != 0.0) {
  51936. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51937. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51938. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51939. if (this.numChannels > 3) {
  51940. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51941. }
  51942. }
  51943. else {
  51944. // otherwise sample nearest
  51945. // get face idx and u, v texel coordinate in face
  51946. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51947. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51948. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51949. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51950. if (this.numChannels > 3) {
  51951. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51952. }
  51953. }
  51954. return PMREMGenerator._vectorTemp;
  51955. };
  51956. //--------------------------------------------------------------------------------------
  51957. // Fixup cube edges
  51958. //
  51959. // average texels on cube map faces across the edges
  51960. // WARP/BENT Method Only.
  51961. //--------------------------------------------------------------------------------------
  51962. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51963. var k;
  51964. var j;
  51965. var i;
  51966. var iFace;
  51967. var iCorner = 0;
  51968. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51969. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51970. // note that if functionality to filter across the three texels for each corner, then
  51971. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51972. var cornerPtr = [
  51973. [[], [], []],
  51974. [[], [], []],
  51975. [[], [], []],
  51976. [[], [], []],
  51977. [[], [], []],
  51978. [[], [], []],
  51979. [[], [], []],
  51980. [[], [], []]
  51981. ];
  51982. //if there is no fixup, or fixup width = 0, do nothing
  51983. if (cubeMapSize < 1) {
  51984. return;
  51985. }
  51986. //special case 1x1 cubemap, average face colors
  51987. if (cubeMapSize == 1) {
  51988. //iterate over channels
  51989. for (k = 0; k < this.numChannels; k++) {
  51990. var accum = 0.0;
  51991. //iterate over faces to accumulate face colors
  51992. for (iFace = 0; iFace < 6; iFace++) {
  51993. accum += cubeMap[iFace][k];
  51994. }
  51995. //compute average over 6 face colors
  51996. accum /= 6.0;
  51997. //iterate over faces to distribute face colors
  51998. for (iFace = 0; iFace < 6; iFace++) {
  51999. cubeMap[iFace][k] = accum;
  52000. }
  52001. }
  52002. return;
  52003. }
  52004. //iterate over faces to collect list of corner texel pointers
  52005. for (iFace = 0; iFace < 6; iFace++) {
  52006. //the 4 corner pointers for this face
  52007. faceCornerStartIndicies[0] = [iFace, 0];
  52008. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  52009. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  52010. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  52011. //iterate over face corners to collect cube corner pointers
  52012. for (iCorner = 0; iCorner < 4; iCorner++) {
  52013. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  52014. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  52015. cornerNumPtrs[corner]++;
  52016. }
  52017. }
  52018. //iterate over corners to average across corner tap values
  52019. for (iCorner = 0; iCorner < 8; iCorner++) {
  52020. for (k = 0; k < this.numChannels; k++) {
  52021. var cornerTapAccum = 0.0;
  52022. //iterate over corner texels and average results
  52023. for (i = 0; i < 3; i++) {
  52024. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  52025. }
  52026. //divide by 3 to compute average of corner tap values
  52027. cornerTapAccum *= (1.0 / 3.0);
  52028. //iterate over corner texels and average results
  52029. for (i = 0; i < 3; i++) {
  52030. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  52031. }
  52032. }
  52033. }
  52034. //iterate over the twelve edges of the cube to average across edges
  52035. for (i = 0; i < 12; i++) {
  52036. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  52037. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  52038. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  52039. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  52040. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  52041. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  52042. var edgeWalk = 0;
  52043. var neighborEdgeWalk = 0;
  52044. //Determine walking pointers based on edge type
  52045. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  52046. switch (edge) {
  52047. case PMREMGenerator.CP_EDGE_LEFT:
  52048. // no change to faceEdgeStartPtr
  52049. edgeWalk = this.numChannels * cubeMapSize;
  52050. break;
  52051. case PMREMGenerator.CP_EDGE_RIGHT:
  52052. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52053. edgeWalk = this.numChannels * cubeMapSize;
  52054. break;
  52055. case PMREMGenerator.CP_EDGE_TOP:
  52056. // no change to faceEdgeStartPtr
  52057. edgeWalk = this.numChannels;
  52058. break;
  52059. case PMREMGenerator.CP_EDGE_BOTTOM:
  52060. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52061. edgeWalk = this.numChannels;
  52062. break;
  52063. }
  52064. //For certain types of edge abutments, the neighbor edge walk needs to
  52065. // be flipped: the cases are
  52066. // if a left edge mates with a left or bottom edge on the neighbor
  52067. // if a top edge mates with a top or right edge on the neighbor
  52068. // if a right edge mates with a right or top edge on the neighbor
  52069. // if a bottom edge mates with a bottom or left edge on the neighbor
  52070. //Seeing as the edges are enumerated as follows
  52071. // left =0
  52072. // right =1
  52073. // top =2
  52074. // bottom =3
  52075. //
  52076. //If the edge enums are the same, or the sum of the enums == 3,
  52077. // the neighbor edge walk needs to be flipped
  52078. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  52079. switch (neighborEdge) {
  52080. case PMREMGenerator.CP_EDGE_LEFT:
  52081. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  52082. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52083. break;
  52084. case PMREMGenerator.CP_EDGE_RIGHT:
  52085. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52086. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52087. break;
  52088. case PMREMGenerator.CP_EDGE_TOP:
  52089. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52090. neighborEdgeWalk = -this.numChannels;
  52091. break;
  52092. case PMREMGenerator.CP_EDGE_BOTTOM:
  52093. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52094. neighborEdgeWalk = -this.numChannels;
  52095. break;
  52096. }
  52097. }
  52098. else {
  52099. //swapped direction neighbor edge walk
  52100. switch (neighborEdge) {
  52101. case PMREMGenerator.CP_EDGE_LEFT:
  52102. //no change to neighborEdgeStartPtr for this case since it points
  52103. // to the upper left corner already
  52104. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52105. break;
  52106. case PMREMGenerator.CP_EDGE_RIGHT:
  52107. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52108. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52109. break;
  52110. case PMREMGenerator.CP_EDGE_TOP:
  52111. //no change to neighborEdgeStartPtr for this case since it points
  52112. // to the upper left corner already
  52113. neighborEdgeWalk = this.numChannels;
  52114. break;
  52115. case PMREMGenerator.CP_EDGE_BOTTOM:
  52116. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52117. neighborEdgeWalk = this.numChannels;
  52118. break;
  52119. }
  52120. }
  52121. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  52122. //nearby neighborhood
  52123. //step ahead one texel on edge
  52124. edgeStartIndex += edgeWalk;
  52125. neighborEdgeStartIndex += neighborEdgeWalk;
  52126. // note that this loop does not process the corner texels, since they have already been
  52127. // averaged across faces across earlier
  52128. for (j = 1; j < (cubeMapSize - 1); j++) {
  52129. //for each set of taps along edge, average them
  52130. // and rewrite the results into the edges
  52131. for (k = 0; k < this.numChannels; k++) {
  52132. var edgeTap = cubeMap[face][edgeStartIndex + k];
  52133. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  52134. //compute average of tap intensity values
  52135. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  52136. //propagate average of taps to edge taps
  52137. cubeMap[face][edgeStartIndex + k] = avgTap;
  52138. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  52139. }
  52140. edgeStartIndex += edgeWalk;
  52141. neighborEdgeStartIndex += neighborEdgeWalk;
  52142. }
  52143. }
  52144. };
  52145. return PMREMGenerator;
  52146. }());
  52147. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52148. PMREMGenerator.CP_UDIR = 0;
  52149. PMREMGenerator.CP_VDIR = 1;
  52150. PMREMGenerator.CP_FACEAXIS = 2;
  52151. //used to index cube faces
  52152. PMREMGenerator.CP_FACE_X_POS = 0;
  52153. PMREMGenerator.CP_FACE_X_NEG = 1;
  52154. PMREMGenerator.CP_FACE_Y_POS = 2;
  52155. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52156. PMREMGenerator.CP_FACE_Z_POS = 4;
  52157. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52158. //used to index image edges
  52159. // NOTE.. the actual number corresponding to the edge is important
  52160. // do not change these, or the code will break
  52161. //
  52162. // CP_EDGE_LEFT is u = 0
  52163. // CP_EDGE_RIGHT is u = width-1
  52164. // CP_EDGE_TOP is v = 0
  52165. // CP_EDGE_BOTTOM is v = height-1
  52166. PMREMGenerator.CP_EDGE_LEFT = 0;
  52167. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52168. PMREMGenerator.CP_EDGE_TOP = 2;
  52169. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52170. //corners of CUBE map (P or N specifys if it corresponds to the
  52171. // positive or negative direction each of X, Y, and Z
  52172. PMREMGenerator.CP_CORNER_NNN = 0;
  52173. PMREMGenerator.CP_CORNER_NNP = 1;
  52174. PMREMGenerator.CP_CORNER_NPN = 2;
  52175. PMREMGenerator.CP_CORNER_NPP = 3;
  52176. PMREMGenerator.CP_CORNER_PNN = 4;
  52177. PMREMGenerator.CP_CORNER_PNP = 5;
  52178. PMREMGenerator.CP_CORNER_PPN = 6;
  52179. PMREMGenerator.CP_CORNER_PPP = 7;
  52180. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52181. //3x2 matrices that map cube map indexing vectors in 3d
  52182. // (after face selection and divide through by the
  52183. // _ABSOLUTE VALUE_ of the max coord)
  52184. // into NVC space
  52185. //Note this currently assumes the D3D cube face ordering and orientation
  52186. PMREMGenerator._sgFace2DMapping = [
  52187. //XPOS face
  52188. [[0, 0, -1],
  52189. [0, -1, 0],
  52190. [1, 0, 0]],
  52191. //XNEG face
  52192. [[0, 0, 1],
  52193. [0, -1, 0],
  52194. [-1, 0, 0]],
  52195. //YPOS face
  52196. [[1, 0, 0],
  52197. [0, 0, 1],
  52198. [0, 1, 0]],
  52199. //YNEG face
  52200. [[1, 0, 0],
  52201. [0, 0, -1],
  52202. [0, -1, 0]],
  52203. //ZPOS face
  52204. [[1, 0, 0],
  52205. [0, -1, 0],
  52206. [0, 0, 1]],
  52207. //ZNEG face
  52208. [[-1, 0, 0],
  52209. [0, -1, 0],
  52210. [0, 0, -1]],
  52211. ];
  52212. //------------------------------------------------------------------------------
  52213. // D3D cube map face specification
  52214. // mapping from 3D x,y,z cube map lookup coordinates
  52215. // to 2D within face u,v coordinates
  52216. //
  52217. // --------------------> U direction
  52218. // | (within-face texture space)
  52219. // | _____
  52220. // | | |
  52221. // | | +Y |
  52222. // | _____|_____|_____ _____
  52223. // | | | | | |
  52224. // | | -X | +Z | +X | -Z |
  52225. // | |_____|_____|_____|_____|
  52226. // | | |
  52227. // | | -Y |
  52228. // | |_____|
  52229. // |
  52230. // v V direction
  52231. // (within-face texture space)
  52232. //------------------------------------------------------------------------------
  52233. //Information about neighbors and how texture coorrdinates change across faces
  52234. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52235. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52236. //Note this currently assumes the D3D cube face ordering and orientation
  52237. PMREMGenerator._sgCubeNgh = [
  52238. //XPOS face
  52239. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52240. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52241. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52242. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52243. //XNEG face
  52244. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52245. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52246. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52247. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52248. //YPOS face
  52249. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52250. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52251. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52252. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52253. //YNEG face
  52254. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52255. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52256. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52257. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52258. //ZPOS face
  52259. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52260. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52261. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52262. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52263. //ZNEG face
  52264. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52265. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52266. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52267. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52268. ];
  52269. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52270. // this table is used to average over the edges.
  52271. PMREMGenerator._sgCubeEdgeList = [
  52272. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52273. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52274. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52275. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52276. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52277. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52278. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52279. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52280. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52281. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52282. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52283. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52284. ];
  52285. //Information about which of the 8 cube corners are correspond to the
  52286. // the 4 corners in each cube face
  52287. // the order is upper left, upper right, lower left, lower right
  52288. PMREMGenerator._sgCubeCornerList = [
  52289. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52290. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52291. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52292. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52293. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52294. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52295. ];
  52296. Internals.PMREMGenerator = PMREMGenerator;
  52297. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52298. })(BABYLON || (BABYLON = {}));
  52299. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  52300. var BABYLON;
  52301. (function (BABYLON) {
  52302. /**
  52303. * This represents a texture coming from an HDR input.
  52304. *
  52305. * The only supported format is currently panorama picture stored in RGBE format.
  52306. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52307. */
  52308. var HDRCubeTexture = (function (_super) {
  52309. __extends(HDRCubeTexture, _super);
  52310. /**
  52311. * Instantiates an HDRTexture from the following parameters.
  52312. *
  52313. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52314. * @param scene The scene the texture will be used in
  52315. * @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.
  52316. * @param noMipmap Forces to not generate the mipmap if true
  52317. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52318. * @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)
  52319. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52320. */
  52321. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  52322. if (noMipmap === void 0) { noMipmap = false; }
  52323. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52324. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52325. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52326. var _this = _super.call(this, scene) || this;
  52327. _this._useInGammaSpace = false;
  52328. _this._generateHarmonics = true;
  52329. _this._isBABYLONPreprocessed = false;
  52330. /**
  52331. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52332. */
  52333. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52334. /**
  52335. * The spherical polynomial data extracted from the texture.
  52336. */
  52337. _this.sphericalPolynomial = null;
  52338. /**
  52339. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52340. * This is usefull at run time to apply the good shader.
  52341. */
  52342. _this.isPMREM = false;
  52343. if (!url) {
  52344. return _this;
  52345. }
  52346. _this.name = url;
  52347. _this.url = url;
  52348. _this.hasAlpha = false;
  52349. _this.isCube = true;
  52350. _this._textureMatrix = BABYLON.Matrix.Identity();
  52351. if (size) {
  52352. _this._isBABYLONPreprocessed = false;
  52353. _this._noMipmap = noMipmap;
  52354. _this._size = size;
  52355. _this._useInGammaSpace = useInGammaSpace;
  52356. _this._usePMREMGenerator = usePMREMGenerator &&
  52357. scene.getEngine().getCaps().textureLOD &&
  52358. _this.getScene().getEngine().getCaps().textureFloat &&
  52359. !_this._useInGammaSpace;
  52360. }
  52361. else {
  52362. _this._isBABYLONPreprocessed = true;
  52363. _this._noMipmap = false;
  52364. _this._useInGammaSpace = false;
  52365. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52366. _this.getScene().getEngine().getCaps().textureFloat &&
  52367. !_this._useInGammaSpace;
  52368. }
  52369. _this.isPMREM = _this._usePMREMGenerator;
  52370. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52371. if (!_this._texture) {
  52372. if (!scene.useDelayedTextureLoading) {
  52373. _this.loadTexture();
  52374. }
  52375. else {
  52376. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52377. }
  52378. }
  52379. return _this;
  52380. }
  52381. /**
  52382. * Occurs when the file is a preprocessed .babylon.hdr file.
  52383. */
  52384. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52385. var _this = this;
  52386. var mipLevels = 0;
  52387. var floatArrayView = null;
  52388. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52389. var mips = [];
  52390. var startIndex = 30;
  52391. for (var level = 0; level < mipLevels; level++) {
  52392. mips.push([]);
  52393. // Fill each pixel of the mip level.
  52394. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52395. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52396. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52397. mips[level].push(faceData);
  52398. startIndex += faceSize;
  52399. }
  52400. }
  52401. return mips;
  52402. } : null;
  52403. var callback = function (buffer) {
  52404. // Create Native Array Views
  52405. var intArrayView = new Int32Array(buffer);
  52406. floatArrayView = new Float32Array(buffer);
  52407. // Fill header.
  52408. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52409. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52410. // Update Texture Information.
  52411. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52412. // Fill polynomial information.
  52413. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52414. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52415. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52416. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52417. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52418. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52419. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52420. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52421. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52422. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52423. // Fill pixel data.
  52424. mipLevels = intArrayView[29]; // Number of mip levels.
  52425. var startIndex = 30;
  52426. var data = [];
  52427. var faceSize = Math.pow(_this._size, 2) * 3;
  52428. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52429. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52430. startIndex += faceSize;
  52431. }
  52432. var results = [];
  52433. var byteArray = null;
  52434. // Push each faces.
  52435. for (var k = 0; k < 6; k++) {
  52436. var dataFace = null;
  52437. // If special cases.
  52438. if (!mipmapGenerator) {
  52439. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52440. dataFace = data[j];
  52441. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52442. // 3 channels of 1 bytes per pixel in bytes.
  52443. var byteBuffer = new ArrayBuffer(faceSize);
  52444. byteArray = new Uint8Array(byteBuffer);
  52445. }
  52446. for (var i = 0; i < _this._size * _this._size; i++) {
  52447. // Put in gamma space if requested.
  52448. if (_this._useInGammaSpace) {
  52449. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52450. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52451. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52452. }
  52453. // Convert to int texture for fallback.
  52454. if (byteArray) {
  52455. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52456. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52457. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52458. // May use luminance instead if the result is not accurate.
  52459. var max = Math.max(Math.max(r, g), b);
  52460. if (max > 255) {
  52461. var scale = 255 / max;
  52462. r *= scale;
  52463. g *= scale;
  52464. b *= scale;
  52465. }
  52466. byteArray[(i * 3) + 0] = r;
  52467. byteArray[(i * 3) + 1] = g;
  52468. byteArray[(i * 3) + 2] = b;
  52469. }
  52470. }
  52471. }
  52472. else {
  52473. dataFace = data[k];
  52474. }
  52475. // Fill the array accordingly.
  52476. if (byteArray) {
  52477. results.push(byteArray);
  52478. }
  52479. else {
  52480. results.push(dataFace);
  52481. }
  52482. }
  52483. return results;
  52484. };
  52485. 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);
  52486. };
  52487. /**
  52488. * Occurs when the file is raw .hdr file.
  52489. */
  52490. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52491. var _this = this;
  52492. var callback = function (buffer) {
  52493. // Extract the raw linear data.
  52494. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52495. // Generate harmonics if needed.
  52496. if (_this._generateHarmonics) {
  52497. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52498. }
  52499. var results = [];
  52500. var byteArray = null;
  52501. // Push each faces.
  52502. for (var j = 0; j < 6; j++) {
  52503. // Create uintarray fallback.
  52504. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52505. // 3 channels of 1 bytes per pixel in bytes.
  52506. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52507. byteArray = new Uint8Array(byteBuffer);
  52508. }
  52509. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52510. // If special cases.
  52511. if (_this._useInGammaSpace || byteArray) {
  52512. for (var i = 0; i < _this._size * _this._size; i++) {
  52513. // Put in gamma space if requested.
  52514. if (_this._useInGammaSpace) {
  52515. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52516. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52517. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52518. }
  52519. // Convert to int texture for fallback.
  52520. if (byteArray) {
  52521. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52522. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52523. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52524. // May use luminance instead if the result is not accurate.
  52525. var max = Math.max(Math.max(r, g), b);
  52526. if (max > 255) {
  52527. var scale = 255 / max;
  52528. r *= scale;
  52529. g *= scale;
  52530. b *= scale;
  52531. }
  52532. byteArray[(i * 3) + 0] = r;
  52533. byteArray[(i * 3) + 1] = g;
  52534. byteArray[(i * 3) + 2] = b;
  52535. }
  52536. }
  52537. }
  52538. if (byteArray) {
  52539. results.push(byteArray);
  52540. }
  52541. else {
  52542. results.push(dataFace);
  52543. }
  52544. }
  52545. return results;
  52546. };
  52547. var mipmapGenerator = null;
  52548. if (!this._noMipmap &&
  52549. this._usePMREMGenerator) {
  52550. mipmapGenerator = function (data) {
  52551. // Custom setup of the generator matching with the PBR shader values.
  52552. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52553. return generator.filterCubeMap();
  52554. };
  52555. }
  52556. 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);
  52557. };
  52558. /**
  52559. * Starts the loading process of the texture.
  52560. */
  52561. HDRCubeTexture.prototype.loadTexture = function () {
  52562. if (this._isBABYLONPreprocessed) {
  52563. this.loadBabylonTexture();
  52564. }
  52565. else {
  52566. this.loadHDRTexture();
  52567. }
  52568. };
  52569. HDRCubeTexture.prototype.clone = function () {
  52570. var size = this._isBABYLONPreprocessed ? null : this._size;
  52571. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52572. // Base texture
  52573. newTexture.level = this.level;
  52574. newTexture.wrapU = this.wrapU;
  52575. newTexture.wrapV = this.wrapV;
  52576. newTexture.coordinatesIndex = this.coordinatesIndex;
  52577. newTexture.coordinatesMode = this.coordinatesMode;
  52578. return newTexture;
  52579. };
  52580. // Methods
  52581. HDRCubeTexture.prototype.delayLoad = function () {
  52582. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52583. return;
  52584. }
  52585. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52586. this._texture = this._getFromCache(this.url, this._noMipmap);
  52587. if (!this._texture) {
  52588. this.loadTexture();
  52589. }
  52590. };
  52591. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52592. return this._textureMatrix;
  52593. };
  52594. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52595. var texture = null;
  52596. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52597. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52598. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52599. texture.name = parsedTexture.name;
  52600. texture.hasAlpha = parsedTexture.hasAlpha;
  52601. texture.level = parsedTexture.level;
  52602. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52603. }
  52604. return texture;
  52605. };
  52606. HDRCubeTexture.prototype.serialize = function () {
  52607. if (!this.name) {
  52608. return null;
  52609. }
  52610. var serializationObject = {};
  52611. serializationObject.name = this.name;
  52612. serializationObject.hasAlpha = this.hasAlpha;
  52613. serializationObject.isCube = true;
  52614. serializationObject.level = this.level;
  52615. serializationObject.size = this._size;
  52616. serializationObject.coordinatesMode = this.coordinatesMode;
  52617. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52618. serializationObject.generateHarmonics = this._generateHarmonics;
  52619. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52620. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52621. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52622. serializationObject.noMipmap = this._noMipmap;
  52623. return serializationObject;
  52624. };
  52625. /**
  52626. * Saves as a file the data contained in the texture in a binary format.
  52627. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52628. * as the spherical used in the lighting.
  52629. * @param url The HDR file url.
  52630. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52631. * @param onError Method called if any error happens during download.
  52632. * @return The packed binary data.
  52633. */
  52634. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52635. if (onError === void 0) { onError = null; }
  52636. var callback = function (buffer) {
  52637. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52638. // Returns a URL you can use as a href.
  52639. var objUrl = window.URL.createObjectURL(data);
  52640. // Simulates a link to it and click to dowload.
  52641. var a = document.createElement("a");
  52642. document.body.appendChild(a);
  52643. a.style.display = "none";
  52644. a.href = objUrl;
  52645. a.download = "envmap.babylon.hdr";
  52646. a.click();
  52647. };
  52648. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52649. };
  52650. /**
  52651. * Serializes the data contained in the texture in a binary format.
  52652. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52653. * as the spherical used in the lighting.
  52654. * @param url The HDR file url.
  52655. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52656. * @param onError Method called if any error happens during download.
  52657. * @return The packed binary data.
  52658. */
  52659. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52660. if (onError === void 0) { onError = null; }
  52661. // Needs the url tho create the texture.
  52662. if (!url) {
  52663. return null;
  52664. }
  52665. // Check Power of two size.
  52666. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52667. return null;
  52668. }
  52669. var getDataCallback = function (dataBuffer) {
  52670. // Extract the raw linear data.
  52671. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52672. // Generate harmonics if needed.
  52673. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52674. // Generate seamless faces
  52675. var mipGeneratorArray = [];
  52676. // Data are known to be in +X +Y +Z -X -Y -Z
  52677. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52678. mipGeneratorArray.push(cubeData.right); // +X
  52679. mipGeneratorArray.push(cubeData.left); // -X
  52680. mipGeneratorArray.push(cubeData.up); // +Y
  52681. mipGeneratorArray.push(cubeData.down); // -Y
  52682. mipGeneratorArray.push(cubeData.front); // +Z
  52683. mipGeneratorArray.push(cubeData.back); // -Z
  52684. // Custom setup of the generator matching with the PBR shader values.
  52685. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52686. var mippedData = generator.filterCubeMap();
  52687. // Compute required byte length.
  52688. var byteLength = 1 * 4; // Raw Data Version int32.
  52689. byteLength += 4; // CubeMap max mip face size int32.
  52690. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52691. // Add data size.
  52692. byteLength += 4; // Number of mip levels int32.
  52693. for (var level = 0; level < mippedData.length; level++) {
  52694. var mipSize = size >> level;
  52695. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52696. }
  52697. // Prepare binary structure.
  52698. var buffer = new ArrayBuffer(byteLength);
  52699. var intArrayView = new Int32Array(buffer);
  52700. var floatArrayView = new Float32Array(buffer);
  52701. // Fill header.
  52702. intArrayView[0] = 1; // Version 1.
  52703. intArrayView[1] = size; // CubeMap max mip face size.
  52704. // Fill polynomial information.
  52705. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52706. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52707. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52708. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52709. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52710. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52711. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52712. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52713. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52714. // Fill pixel data.
  52715. intArrayView[29] = mippedData.length; // Number of mip levels.
  52716. var startIndex = 30;
  52717. for (var level = 0; level < mippedData.length; level++) {
  52718. // Fill each pixel of the mip level.
  52719. var faceSize = Math.pow(size >> level, 2) * 3;
  52720. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52721. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52722. startIndex += faceSize;
  52723. }
  52724. }
  52725. // Callback.
  52726. callback(buffer);
  52727. };
  52728. // Download and process.
  52729. BABYLON.Tools.LoadFile(url, function (data) {
  52730. getDataCallback(data);
  52731. }, null, null, true, onError);
  52732. };
  52733. return HDRCubeTexture;
  52734. }(BABYLON.BaseTexture));
  52735. HDRCubeTexture._facesMapping = [
  52736. "right",
  52737. "up",
  52738. "front",
  52739. "left",
  52740. "down",
  52741. "back"
  52742. ];
  52743. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52744. })(BABYLON || (BABYLON = {}));
  52745. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52746. var BABYLON;
  52747. (function (BABYLON) {
  52748. var Debug;
  52749. (function (Debug) {
  52750. /**
  52751. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52752. */
  52753. var SkeletonViewer = (function () {
  52754. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52755. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52756. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52757. this.skeleton = skeleton;
  52758. this.mesh = mesh;
  52759. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52760. this.renderingGroupId = renderingGroupId;
  52761. this.color = BABYLON.Color3.White();
  52762. this._debugLines = [];
  52763. this._isEnabled = false;
  52764. this._scene = scene;
  52765. this.update();
  52766. this._renderFunction = this.update.bind(this);
  52767. }
  52768. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52769. get: function () {
  52770. return this._isEnabled;
  52771. },
  52772. set: function (value) {
  52773. if (this._isEnabled === value) {
  52774. return;
  52775. }
  52776. this._isEnabled = value;
  52777. if (value) {
  52778. this._scene.registerBeforeRender(this._renderFunction);
  52779. }
  52780. else {
  52781. this._scene.unregisterBeforeRender(this._renderFunction);
  52782. }
  52783. },
  52784. enumerable: true,
  52785. configurable: true
  52786. });
  52787. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52788. if (x === void 0) { x = 0; }
  52789. if (y === void 0) { y = 0; }
  52790. if (z === void 0) { z = 0; }
  52791. var tmat = BABYLON.Tmp.Matrix[0];
  52792. var parentBone = bone.getParent();
  52793. tmat.copyFrom(bone.getLocalMatrix());
  52794. if (x !== 0 || y !== 0 || z !== 0) {
  52795. var tmat2 = BABYLON.Tmp.Matrix[1];
  52796. BABYLON.Matrix.IdentityToRef(tmat2);
  52797. tmat2.m[12] = x;
  52798. tmat2.m[13] = y;
  52799. tmat2.m[14] = z;
  52800. tmat2.multiplyToRef(tmat, tmat);
  52801. }
  52802. if (parentBone) {
  52803. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52804. }
  52805. tmat.multiplyToRef(meshMat, tmat);
  52806. position.x = tmat.m[12];
  52807. position.y = tmat.m[13];
  52808. position.z = tmat.m[14];
  52809. };
  52810. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52811. var len = bones.length;
  52812. for (var i = 0; i < len; i++) {
  52813. var bone = bones[i];
  52814. var points = this._debugLines[i];
  52815. if (!points) {
  52816. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52817. this._debugLines[i] = points;
  52818. }
  52819. this._getBonePosition(points[0], bone, meshMat);
  52820. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52821. }
  52822. };
  52823. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52824. var len = bones.length;
  52825. var boneNum = 0;
  52826. for (var i = len - 1; i >= 0; i--) {
  52827. var childBone = bones[i];
  52828. var parentBone = childBone.getParent();
  52829. if (!parentBone) {
  52830. continue;
  52831. }
  52832. var points = this._debugLines[boneNum];
  52833. if (!points) {
  52834. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52835. this._debugLines[boneNum] = points;
  52836. }
  52837. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52838. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52839. boneNum++;
  52840. }
  52841. };
  52842. SkeletonViewer.prototype.update = function () {
  52843. if (this.autoUpdateBonesMatrices) {
  52844. this.skeleton.computeAbsoluteTransforms();
  52845. }
  52846. if (this.skeleton.bones[0].length === undefined) {
  52847. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52848. }
  52849. else {
  52850. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52851. }
  52852. if (!this._debugMesh) {
  52853. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52854. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52855. }
  52856. else {
  52857. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52858. }
  52859. this._debugMesh.color = this.color;
  52860. };
  52861. SkeletonViewer.prototype.dispose = function () {
  52862. if (this._debugMesh) {
  52863. this.isEnabled = false;
  52864. this._debugMesh.dispose();
  52865. this._debugMesh = null;
  52866. }
  52867. };
  52868. return SkeletonViewer;
  52869. }());
  52870. Debug.SkeletonViewer = SkeletonViewer;
  52871. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52872. })(BABYLON || (BABYLON = {}));
  52873. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52874. var BABYLON;
  52875. (function (BABYLON) {
  52876. var Debug;
  52877. (function (Debug) {
  52878. var AxesViewer = (function () {
  52879. function AxesViewer(scene, scaleLines) {
  52880. if (scaleLines === void 0) { scaleLines = 1; }
  52881. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52882. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52883. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52884. this.scaleLines = 1;
  52885. this.scaleLines = scaleLines;
  52886. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52887. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52888. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52889. this._xmesh.renderingGroupId = 2;
  52890. this._ymesh.renderingGroupId = 2;
  52891. this._zmesh.renderingGroupId = 2;
  52892. this._xmesh.material.checkReadyOnlyOnce = true;
  52893. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52894. this._ymesh.material.checkReadyOnlyOnce = true;
  52895. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52896. this._zmesh.material.checkReadyOnlyOnce = true;
  52897. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52898. this.scene = scene;
  52899. }
  52900. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52901. var scaleLines = this.scaleLines;
  52902. var point1 = this._xline[0];
  52903. var point2 = this._xline[1];
  52904. point1.x = position.x;
  52905. point1.y = position.y;
  52906. point1.z = position.z;
  52907. point2.x = point1.x + xaxis.x * scaleLines;
  52908. point2.y = point1.y + xaxis.y * scaleLines;
  52909. point2.z = point1.z + xaxis.z * scaleLines;
  52910. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52911. point1 = this._yline[0];
  52912. point2 = this._yline[1];
  52913. point1.x = position.x;
  52914. point1.y = position.y;
  52915. point1.z = position.z;
  52916. point2.x = point1.x + yaxis.x * scaleLines;
  52917. point2.y = point1.y + yaxis.y * scaleLines;
  52918. point2.z = point1.z + yaxis.z * scaleLines;
  52919. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52920. point1 = this._zline[0];
  52921. point2 = this._zline[1];
  52922. point1.x = position.x;
  52923. point1.y = position.y;
  52924. point1.z = position.z;
  52925. point2.x = point1.x + zaxis.x * scaleLines;
  52926. point2.y = point1.y + zaxis.y * scaleLines;
  52927. point2.z = point1.z + zaxis.z * scaleLines;
  52928. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52929. };
  52930. AxesViewer.prototype.dispose = function () {
  52931. if (this._xmesh) {
  52932. this._xmesh.dispose();
  52933. this._ymesh.dispose();
  52934. this._zmesh.dispose();
  52935. this._xmesh = null;
  52936. this._ymesh = null;
  52937. this._zmesh = null;
  52938. this._xline = null;
  52939. this._yline = null;
  52940. this._zline = null;
  52941. this.scene = null;
  52942. }
  52943. };
  52944. return AxesViewer;
  52945. }());
  52946. Debug.AxesViewer = AxesViewer;
  52947. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52948. })(BABYLON || (BABYLON = {}));
  52949. //# sourceMappingURL=babylon.axesViewer.js.map
  52950. var BABYLON;
  52951. (function (BABYLON) {
  52952. var Debug;
  52953. (function (Debug) {
  52954. var BoneAxesViewer = (function (_super) {
  52955. __extends(BoneAxesViewer, _super);
  52956. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52957. if (scaleLines === void 0) { scaleLines = 1; }
  52958. var _this = _super.call(this, scene, scaleLines) || this;
  52959. _this.pos = BABYLON.Vector3.Zero();
  52960. _this.xaxis = BABYLON.Vector3.Zero();
  52961. _this.yaxis = BABYLON.Vector3.Zero();
  52962. _this.zaxis = BABYLON.Vector3.Zero();
  52963. _this.mesh = mesh;
  52964. _this.bone = bone;
  52965. return _this;
  52966. }
  52967. BoneAxesViewer.prototype.update = function () {
  52968. var bone = this.bone;
  52969. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52970. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52971. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52972. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52973. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52974. };
  52975. BoneAxesViewer.prototype.dispose = function () {
  52976. if (this.pos) {
  52977. this.pos = null;
  52978. this.xaxis = null;
  52979. this.yaxis = null;
  52980. this.zaxis = null;
  52981. this.mesh = null;
  52982. this.bone = null;
  52983. _super.prototype.dispose.call(this);
  52984. }
  52985. };
  52986. return BoneAxesViewer;
  52987. }(Debug.AxesViewer));
  52988. Debug.BoneAxesViewer = BoneAxesViewer;
  52989. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52990. })(BABYLON || (BABYLON = {}));
  52991. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52992. var BABYLON;
  52993. (function (BABYLON) {
  52994. /**
  52995. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52996. * It can help converting any input color in a desired output one. This can then be used to create effects
  52997. * from sepia, black and white to sixties or futuristic rendering...
  52998. *
  52999. * The only supported format is currently 3dl.
  53000. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  53001. */
  53002. var ColorGradingTexture = (function (_super) {
  53003. __extends(ColorGradingTexture, _super);
  53004. /**
  53005. * Instantiates a ColorGradingTexture from the following parameters.
  53006. *
  53007. * @param url The location of the color gradind data (currently only supporting 3dl)
  53008. * @param scene The scene the texture will be used in
  53009. */
  53010. function ColorGradingTexture(url, scene) {
  53011. var _this = _super.call(this, scene) || this;
  53012. if (!url) {
  53013. return _this;
  53014. }
  53015. _this._textureMatrix = BABYLON.Matrix.Identity();
  53016. _this.name = url;
  53017. _this.url = url;
  53018. _this.hasAlpha = false;
  53019. _this.isCube = false;
  53020. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53021. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53022. _this.anisotropicFilteringLevel = 1;
  53023. _this._texture = _this._getFromCache(url, true);
  53024. if (!_this._texture) {
  53025. if (!scene.useDelayedTextureLoading) {
  53026. _this.loadTexture();
  53027. }
  53028. else {
  53029. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53030. }
  53031. }
  53032. return _this;
  53033. }
  53034. /**
  53035. * Returns the texture matrix used in most of the material.
  53036. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  53037. */
  53038. ColorGradingTexture.prototype.getTextureMatrix = function () {
  53039. return this._textureMatrix;
  53040. };
  53041. /**
  53042. * Occurs when the file being loaded is a .3dl LUT file.
  53043. */
  53044. ColorGradingTexture.prototype.load3dlTexture = function () {
  53045. var _this = this;
  53046. var mipLevels = 0;
  53047. var floatArrayView = null;
  53048. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53049. this._texture = texture;
  53050. var callback = function (text) {
  53051. var data;
  53052. var tempData;
  53053. var line;
  53054. var lines = text.split('\n');
  53055. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  53056. var maxColor = 0;
  53057. for (var i = 0; i < lines.length; i++) {
  53058. line = lines[i];
  53059. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  53060. continue;
  53061. if (line.indexOf('#') === 0)
  53062. continue;
  53063. var words = line.split(" ");
  53064. if (size === 0) {
  53065. // Number of space + one
  53066. size = words.length;
  53067. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  53068. tempData = new Float32Array(size * size * size * 4);
  53069. continue;
  53070. }
  53071. if (size != 0) {
  53072. var r = Math.max(parseInt(words[0]), 0);
  53073. var g = Math.max(parseInt(words[1]), 0);
  53074. var b = Math.max(parseInt(words[2]), 0);
  53075. maxColor = Math.max(r, maxColor);
  53076. maxColor = Math.max(g, maxColor);
  53077. maxColor = Math.max(b, maxColor);
  53078. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  53079. tempData[pixelStorageIndex + 0] = r;
  53080. tempData[pixelStorageIndex + 1] = g;
  53081. tempData[pixelStorageIndex + 2] = b;
  53082. tempData[pixelStorageIndex + 3] = 0;
  53083. pixelIndexSlice++;
  53084. if (pixelIndexSlice % size == 0) {
  53085. pixelIndexH++;
  53086. pixelIndexSlice = 0;
  53087. if (pixelIndexH % size == 0) {
  53088. pixelIndexW++;
  53089. pixelIndexH = 0;
  53090. }
  53091. }
  53092. }
  53093. }
  53094. for (var i = 0; i < tempData.length; i++) {
  53095. var value = tempData[i];
  53096. data[i] = (value / maxColor * 255);
  53097. }
  53098. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  53099. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  53100. };
  53101. BABYLON.Tools.LoadFile(this.url, callback);
  53102. return this._texture;
  53103. };
  53104. /**
  53105. * Starts the loading process of the texture.
  53106. */
  53107. ColorGradingTexture.prototype.loadTexture = function () {
  53108. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  53109. this.load3dlTexture();
  53110. }
  53111. };
  53112. /**
  53113. * Clones the color gradind texture.
  53114. */
  53115. ColorGradingTexture.prototype.clone = function () {
  53116. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  53117. // Base texture
  53118. newTexture.level = this.level;
  53119. return newTexture;
  53120. };
  53121. /**
  53122. * Called during delayed load for textures.
  53123. */
  53124. ColorGradingTexture.prototype.delayLoad = function () {
  53125. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53126. return;
  53127. }
  53128. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53129. this._texture = this._getFromCache(this.url, true);
  53130. if (!this._texture) {
  53131. this.loadTexture();
  53132. }
  53133. };
  53134. /**
  53135. * Binds the color grading to the shader.
  53136. * @param colorGrading The texture to bind
  53137. * @param effect The effect to bind to
  53138. */
  53139. ColorGradingTexture.Bind = function (colorGrading, effect) {
  53140. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  53141. var x = colorGrading.level; // Texture Level
  53142. var y = colorGrading.getSize().height; // Texture Size example with 8
  53143. var z = y - 1.0; // SizeMinusOne 8 - 1
  53144. var w = 1 / y; // Space of 1 slice 1 / 8
  53145. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  53146. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  53147. 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
  53148. 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
  53149. 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
  53150. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  53151. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  53152. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  53153. };
  53154. /**
  53155. * Prepare the list of uniforms associated with the ColorGrading effects.
  53156. * @param uniformsList The list of uniforms used in the effect
  53157. * @param samplersList The list of samplers used in the effect
  53158. */
  53159. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  53160. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  53161. samplersList.push("cameraColorGrading2DSampler");
  53162. };
  53163. /**
  53164. * Parses a color grading texture serialized by Babylon.
  53165. * @param parsedTexture The texture information being parsedTexture
  53166. * @param scene The scene to load the texture in
  53167. * @param rootUrl The root url of the data assets to load
  53168. * @return A color gradind texture
  53169. */
  53170. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53171. var texture = null;
  53172. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  53173. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  53174. texture.name = parsedTexture.name;
  53175. texture.level = parsedTexture.level;
  53176. }
  53177. return texture;
  53178. };
  53179. /**
  53180. * Serializes the LUT texture to json format.
  53181. */
  53182. ColorGradingTexture.prototype.serialize = function () {
  53183. if (!this.name) {
  53184. return null;
  53185. }
  53186. var serializationObject = {};
  53187. serializationObject.name = this.name;
  53188. serializationObject.level = this.level;
  53189. serializationObject.customType = "BABYLON.ColorGradingTexture";
  53190. return serializationObject;
  53191. };
  53192. return ColorGradingTexture;
  53193. }(BABYLON.BaseTexture));
  53194. /**
  53195. * Empty line regex stored for GC.
  53196. */
  53197. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  53198. BABYLON.ColorGradingTexture = ColorGradingTexture;
  53199. })(BABYLON || (BABYLON = {}));
  53200. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  53201. var BABYLON;
  53202. (function (BABYLON) {
  53203. /**
  53204. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53205. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53206. * 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;
  53207. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53208. */
  53209. var ColorCurves = (function () {
  53210. function ColorCurves() {
  53211. this._dirty = true;
  53212. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  53213. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  53214. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53215. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  53216. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53217. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  53218. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  53219. this._globalHue = 30;
  53220. this._globalDensity = 0;
  53221. this._globalSaturation = 0;
  53222. this._globalExposure = 0;
  53223. this._highlightsHue = 30;
  53224. this._highlightsDensity = 0;
  53225. this._highlightsSaturation = 0;
  53226. this._highlightsExposure = 0;
  53227. this._midtonesHue = 30;
  53228. this._midtonesDensity = 0;
  53229. this._midtonesSaturation = 0;
  53230. this._midtonesExposure = 0;
  53231. this._shadowsHue = 30;
  53232. this._shadowsDensity = 0;
  53233. this._shadowsSaturation = 0;
  53234. this._shadowsExposure = 0;
  53235. }
  53236. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  53237. /**
  53238. * Gets the global Hue value.
  53239. * 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).
  53240. */
  53241. get: function () {
  53242. return this._globalHue;
  53243. },
  53244. /**
  53245. * Sets the global Hue value.
  53246. * 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).
  53247. */
  53248. set: function (value) {
  53249. this._globalHue = value;
  53250. this._dirty = true;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  53256. /**
  53257. * Gets the global Density value.
  53258. * 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.
  53259. * Values less than zero provide a filter of opposite hue.
  53260. */
  53261. get: function () {
  53262. return this._globalDensity;
  53263. },
  53264. /**
  53265. * Sets the global Density value.
  53266. * 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.
  53267. * Values less than zero provide a filter of opposite hue.
  53268. */
  53269. set: function (value) {
  53270. this._globalDensity = value;
  53271. this._dirty = true;
  53272. },
  53273. enumerable: true,
  53274. configurable: true
  53275. });
  53276. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  53277. /**
  53278. * Gets the global Saturation value.
  53279. * 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.
  53280. */
  53281. get: function () {
  53282. return this._globalSaturation;
  53283. },
  53284. /**
  53285. * Sets the global Saturation value.
  53286. * 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.
  53287. */
  53288. set: function (value) {
  53289. this._globalSaturation = value;
  53290. this._dirty = true;
  53291. },
  53292. enumerable: true,
  53293. configurable: true
  53294. });
  53295. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  53296. /**
  53297. * Gets the highlights Hue value.
  53298. * 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).
  53299. */
  53300. get: function () {
  53301. return this._highlightsHue;
  53302. },
  53303. /**
  53304. * Sets the highlights Hue value.
  53305. * 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).
  53306. */
  53307. set: function (value) {
  53308. this._highlightsHue = value;
  53309. this._dirty = true;
  53310. },
  53311. enumerable: true,
  53312. configurable: true
  53313. });
  53314. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  53315. /**
  53316. * Gets the highlights Density value.
  53317. * 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.
  53318. * Values less than zero provide a filter of opposite hue.
  53319. */
  53320. get: function () {
  53321. return this._highlightsDensity;
  53322. },
  53323. /**
  53324. * Sets the highlights Density value.
  53325. * 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.
  53326. * Values less than zero provide a filter of opposite hue.
  53327. */
  53328. set: function (value) {
  53329. this._highlightsDensity = value;
  53330. this._dirty = true;
  53331. },
  53332. enumerable: true,
  53333. configurable: true
  53334. });
  53335. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  53336. /**
  53337. * Gets the highlights Saturation value.
  53338. * 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.
  53339. */
  53340. get: function () {
  53341. return this._highlightsSaturation;
  53342. },
  53343. /**
  53344. * Sets the highlights Saturation value.
  53345. * 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.
  53346. */
  53347. set: function (value) {
  53348. this._highlightsSaturation = value;
  53349. this._dirty = true;
  53350. },
  53351. enumerable: true,
  53352. configurable: true
  53353. });
  53354. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  53355. /**
  53356. * Gets the highlights Exposure value.
  53357. * 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.
  53358. */
  53359. get: function () {
  53360. return this._highlightsExposure;
  53361. },
  53362. /**
  53363. * Sets the highlights Exposure value.
  53364. * 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.
  53365. */
  53366. set: function (value) {
  53367. this._highlightsExposure = value;
  53368. this._dirty = true;
  53369. },
  53370. enumerable: true,
  53371. configurable: true
  53372. });
  53373. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  53374. /**
  53375. * Gets the midtones Hue value.
  53376. * 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).
  53377. */
  53378. get: function () {
  53379. return this._midtonesHue;
  53380. },
  53381. /**
  53382. * Sets the midtones Hue value.
  53383. * 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).
  53384. */
  53385. set: function (value) {
  53386. this._midtonesHue = value;
  53387. this._dirty = true;
  53388. },
  53389. enumerable: true,
  53390. configurable: true
  53391. });
  53392. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  53393. /**
  53394. * Gets the midtones Density value.
  53395. * 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.
  53396. * Values less than zero provide a filter of opposite hue.
  53397. */
  53398. get: function () {
  53399. return this._midtonesDensity;
  53400. },
  53401. /**
  53402. * Sets the midtones Density value.
  53403. * 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.
  53404. * Values less than zero provide a filter of opposite hue.
  53405. */
  53406. set: function (value) {
  53407. this._midtonesDensity = value;
  53408. this._dirty = true;
  53409. },
  53410. enumerable: true,
  53411. configurable: true
  53412. });
  53413. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  53414. /**
  53415. * Gets the midtones Saturation value.
  53416. * 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.
  53417. */
  53418. get: function () {
  53419. return this._midtonesSaturation;
  53420. },
  53421. /**
  53422. * Sets the midtones Saturation value.
  53423. * 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.
  53424. */
  53425. set: function (value) {
  53426. this._midtonesSaturation = value;
  53427. this._dirty = true;
  53428. },
  53429. enumerable: true,
  53430. configurable: true
  53431. });
  53432. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  53433. /**
  53434. * Gets the midtones Exposure value.
  53435. * 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.
  53436. */
  53437. get: function () {
  53438. return this._midtonesExposure;
  53439. },
  53440. /**
  53441. * Sets the midtones Exposure value.
  53442. * 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.
  53443. */
  53444. set: function (value) {
  53445. this._midtonesExposure = value;
  53446. this._dirty = true;
  53447. },
  53448. enumerable: true,
  53449. configurable: true
  53450. });
  53451. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  53452. /**
  53453. * Gets the shadows Hue value.
  53454. * 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).
  53455. */
  53456. get: function () {
  53457. return this._shadowsHue;
  53458. },
  53459. /**
  53460. * Sets the shadows Hue value.
  53461. * 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).
  53462. */
  53463. set: function (value) {
  53464. this._shadowsHue = value;
  53465. this._dirty = true;
  53466. },
  53467. enumerable: true,
  53468. configurable: true
  53469. });
  53470. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  53471. /**
  53472. * Gets the shadows Density value.
  53473. * 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.
  53474. * Values less than zero provide a filter of opposite hue.
  53475. */
  53476. get: function () {
  53477. return this._shadowsDensity;
  53478. },
  53479. /**
  53480. * Sets the shadows Density value.
  53481. * 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.
  53482. * Values less than zero provide a filter of opposite hue.
  53483. */
  53484. set: function (value) {
  53485. this._shadowsDensity = value;
  53486. this._dirty = true;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53492. /**
  53493. * Gets the shadows Saturation value.
  53494. * 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.
  53495. */
  53496. get: function () {
  53497. return this._shadowsSaturation;
  53498. },
  53499. /**
  53500. * Sets the shadows Saturation value.
  53501. * 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.
  53502. */
  53503. set: function (value) {
  53504. this._shadowsSaturation = value;
  53505. this._dirty = true;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53511. /**
  53512. * Gets the shadows Exposure value.
  53513. * 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.
  53514. */
  53515. get: function () {
  53516. return this._shadowsExposure;
  53517. },
  53518. /**
  53519. * Sets the shadows Exposure value.
  53520. * 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.
  53521. */
  53522. set: function (value) {
  53523. this._shadowsExposure = value;
  53524. this._dirty = true;
  53525. },
  53526. enumerable: true,
  53527. configurable: true
  53528. });
  53529. /**
  53530. * Binds the color curves to the shader.
  53531. * @param colorCurves The color curve to bind
  53532. * @param effect The effect to bind to
  53533. */
  53534. ColorCurves.Bind = function (colorCurves, effect) {
  53535. if (colorCurves._dirty) {
  53536. colorCurves._dirty = false;
  53537. // Fill in global info.
  53538. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53539. // Compute highlights info.
  53540. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53541. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53542. // Compute midtones info.
  53543. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53544. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53545. // Compute shadows info.
  53546. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53547. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53548. // Compute deltas (neutral is midtones).
  53549. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53550. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53551. }
  53552. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53553. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53554. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53555. };
  53556. /**
  53557. * Prepare the list of uniforms associated with the ColorCurves effects.
  53558. * @param uniformsList The list of uniforms used in the effect
  53559. */
  53560. ColorCurves.PrepareUniforms = function (uniformsList) {
  53561. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53562. };
  53563. /**
  53564. * Returns color grading data based on a hue, density, saturation and exposure value.
  53565. * @param filterHue The hue of the color filter.
  53566. * @param filterDensity The density of the color filter.
  53567. * @param saturation The saturation.
  53568. * @param exposure The exposure.
  53569. * @param result The result data container.
  53570. */
  53571. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53572. if (hue == null) {
  53573. return;
  53574. }
  53575. hue = ColorCurves.clamp(hue, 0, 360);
  53576. density = ColorCurves.clamp(density, -100, 100);
  53577. saturation = ColorCurves.clamp(saturation, -100, 100);
  53578. exposure = ColorCurves.clamp(exposure, -100, 100);
  53579. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53580. // so that the maximum filter density is only 50% control. This provides fine control
  53581. // for small values and reasonable range.
  53582. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53583. density *= 0.5;
  53584. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53585. if (density < 0) {
  53586. density *= -1;
  53587. hue = (hue + 180) % 360;
  53588. }
  53589. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53590. result.scaleToRef(2, result);
  53591. result.a = 1 + 0.01 * saturation;
  53592. };
  53593. /**
  53594. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53595. * @param value The input slider value in range [-100,100].
  53596. * @returns Adjusted value.
  53597. */
  53598. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53599. value /= 100;
  53600. var x = Math.abs(value);
  53601. x = Math.pow(x, 2);
  53602. if (value < 0) {
  53603. x *= -1;
  53604. }
  53605. x *= 100;
  53606. return x;
  53607. };
  53608. /**
  53609. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53610. * @param hue The hue (H) input.
  53611. * @param saturation The saturation (S) input.
  53612. * @param brightness The brightness (B) input.
  53613. * @result An RGBA color represented as Vector4.
  53614. */
  53615. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53616. var h = ColorCurves.clamp(hue, 0, 360);
  53617. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53618. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53619. if (s === 0) {
  53620. result.r = v;
  53621. result.g = v;
  53622. result.b = v;
  53623. }
  53624. else {
  53625. // sector 0 to 5
  53626. h /= 60;
  53627. var i = Math.floor(h);
  53628. // fractional part of h
  53629. var f = h - i;
  53630. var p = v * (1 - s);
  53631. var q = v * (1 - s * f);
  53632. var t = v * (1 - s * (1 - f));
  53633. switch (i) {
  53634. case 0:
  53635. result.r = v;
  53636. result.g = t;
  53637. result.b = p;
  53638. break;
  53639. case 1:
  53640. result.r = q;
  53641. result.g = v;
  53642. result.b = p;
  53643. break;
  53644. case 2:
  53645. result.r = p;
  53646. result.g = v;
  53647. result.b = t;
  53648. break;
  53649. case 3:
  53650. result.r = p;
  53651. result.g = q;
  53652. result.b = v;
  53653. break;
  53654. case 4:
  53655. result.r = t;
  53656. result.g = p;
  53657. result.b = v;
  53658. break;
  53659. default:
  53660. result.r = v;
  53661. result.g = p;
  53662. result.b = q;
  53663. break;
  53664. }
  53665. }
  53666. result.a = 1;
  53667. };
  53668. /**
  53669. * Returns a value clamped between min and max
  53670. * @param value The value to clamp
  53671. * @param min The minimum of value
  53672. * @param max The maximum of value
  53673. * @returns The clamped value.
  53674. */
  53675. ColorCurves.clamp = function (value, min, max) {
  53676. return Math.min(Math.max(value, min), max);
  53677. };
  53678. /**
  53679. * Clones the current color curve instance.
  53680. * @return The cloned curves
  53681. */
  53682. ColorCurves.prototype.clone = function () {
  53683. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53684. };
  53685. /**
  53686. * Serializes the current color curve instance to a json representation.
  53687. * @return a JSON representation
  53688. */
  53689. ColorCurves.prototype.serialize = function () {
  53690. return BABYLON.SerializationHelper.Serialize(this);
  53691. };
  53692. /**
  53693. * Parses the color curve from a json representation.
  53694. * @param source the JSON source to parse
  53695. * @return The parsed curves
  53696. */
  53697. ColorCurves.Parse = function (source) {
  53698. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53699. };
  53700. return ColorCurves;
  53701. }());
  53702. __decorate([
  53703. BABYLON.serialize()
  53704. ], ColorCurves.prototype, "_globalHue", void 0);
  53705. __decorate([
  53706. BABYLON.serialize()
  53707. ], ColorCurves.prototype, "_globalDensity", void 0);
  53708. __decorate([
  53709. BABYLON.serialize()
  53710. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53711. __decorate([
  53712. BABYLON.serialize()
  53713. ], ColorCurves.prototype, "_globalExposure", void 0);
  53714. __decorate([
  53715. BABYLON.serialize()
  53716. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53717. __decorate([
  53718. BABYLON.serialize()
  53719. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53720. __decorate([
  53721. BABYLON.serialize()
  53722. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53723. __decorate([
  53724. BABYLON.serialize()
  53725. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53726. __decorate([
  53727. BABYLON.serialize()
  53728. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53729. __decorate([
  53730. BABYLON.serialize()
  53731. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53732. __decorate([
  53733. BABYLON.serialize()
  53734. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53735. __decorate([
  53736. BABYLON.serialize()
  53737. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53738. BABYLON.ColorCurves = ColorCurves;
  53739. })(BABYLON || (BABYLON = {}));
  53740. //# sourceMappingURL=babylon.colorCurves.js.map
  53741. var BABYLON;
  53742. (function (BABYLON) {
  53743. var PBRMaterialDefines = (function (_super) {
  53744. __extends(PBRMaterialDefines, _super);
  53745. function PBRMaterialDefines() {
  53746. var _this = _super.call(this) || this;
  53747. _this.ALBEDO = false;
  53748. _this.AMBIENT = false;
  53749. _this.OPACITY = false;
  53750. _this.OPACITYRGB = false;
  53751. _this.REFLECTION = false;
  53752. _this.EMISSIVE = false;
  53753. _this.REFLECTIVITY = false;
  53754. _this.BUMP = false;
  53755. _this.PARALLAX = false;
  53756. _this.PARALLAXOCCLUSION = false;
  53757. _this.SPECULAROVERALPHA = false;
  53758. _this.CLIPPLANE = false;
  53759. _this.ALPHATEST = false;
  53760. _this.ALPHAFROMALBEDO = false;
  53761. _this.POINTSIZE = false;
  53762. _this.FOG = false;
  53763. _this.SPECULARTERM = false;
  53764. _this.OPACITYFRESNEL = false;
  53765. _this.EMISSIVEFRESNEL = false;
  53766. _this.FRESNEL = false;
  53767. _this.NORMAL = false;
  53768. _this.UV1 = false;
  53769. _this.UV2 = false;
  53770. _this.VERTEXCOLOR = false;
  53771. _this.VERTEXALPHA = false;
  53772. _this.NUM_BONE_INFLUENCERS = 0;
  53773. _this.BonesPerMesh = 0;
  53774. _this.INSTANCES = false;
  53775. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53776. _this.MICROSURFACEAUTOMATIC = false;
  53777. _this.EMISSIVEASILLUMINATION = false;
  53778. _this.LINKEMISSIVEWITHALBEDO = false;
  53779. _this.LIGHTMAP = false;
  53780. _this.USELIGHTMAPASSHADOWMAP = false;
  53781. _this.REFLECTIONMAP_3D = false;
  53782. _this.REFLECTIONMAP_SPHERICAL = false;
  53783. _this.REFLECTIONMAP_PLANAR = false;
  53784. _this.REFLECTIONMAP_CUBIC = false;
  53785. _this.REFLECTIONMAP_PROJECTION = false;
  53786. _this.REFLECTIONMAP_SKYBOX = false;
  53787. _this.REFLECTIONMAP_EXPLICIT = false;
  53788. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53789. _this.INVERTCUBICMAP = false;
  53790. _this.LOGARITHMICDEPTH = false;
  53791. _this.CAMERATONEMAP = false;
  53792. _this.CAMERACONTRAST = false;
  53793. _this.CAMERACOLORGRADING = false;
  53794. _this.CAMERACOLORCURVES = false;
  53795. _this.OVERLOADEDVALUES = false;
  53796. _this.OVERLOADEDSHADOWVALUES = false;
  53797. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53798. _this.REFRACTION = false;
  53799. _this.REFRACTIONMAP_3D = false;
  53800. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53801. _this.REFRACTIONMAPINLINEARSPACE = false;
  53802. _this.LODBASEDMICROSFURACE = false;
  53803. _this.USEPHYSICALLIGHTFALLOFF = false;
  53804. _this.RADIANCEOVERALPHA = false;
  53805. _this.USEPMREMREFLECTION = false;
  53806. _this.USEPMREMREFRACTION = false;
  53807. _this.OPENGLNORMALMAP = false;
  53808. _this.INVERTNORMALMAPX = false;
  53809. _this.INVERTNORMALMAPY = false;
  53810. _this.SHADOWFULLFLOAT = false;
  53811. _this.METALLICWORKFLOW = false;
  53812. _this.METALLICROUGHNESSMAP = false;
  53813. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53814. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53815. _this.rebuild();
  53816. return _this;
  53817. }
  53818. return PBRMaterialDefines;
  53819. }(BABYLON.MaterialDefines));
  53820. /**
  53821. * The Physically based material of BJS.
  53822. *
  53823. * This offers the main features of a standard PBR material.
  53824. * For more information, please refer to the documentation :
  53825. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53826. */
  53827. var PBRMaterial = (function (_super) {
  53828. __extends(PBRMaterial, _super);
  53829. /**
  53830. * Instantiates a new PBRMaterial instance.
  53831. *
  53832. * @param name The material name
  53833. * @param scene The scene the material will be use in.
  53834. */
  53835. function PBRMaterial(name, scene) {
  53836. var _this = _super.call(this, name, scene) || this;
  53837. /**
  53838. * Intensity of the direct lights e.g. the four lights available in your scene.
  53839. * This impacts both the direct diffuse and specular highlights.
  53840. */
  53841. _this.directIntensity = 1.0;
  53842. /**
  53843. * Intensity of the emissive part of the material.
  53844. * This helps controlling the emissive effect without modifying the emissive color.
  53845. */
  53846. _this.emissiveIntensity = 1.0;
  53847. /**
  53848. * Intensity of the environment e.g. how much the environment will light the object
  53849. * either through harmonics for rough material or through the refelction for shiny ones.
  53850. */
  53851. _this.environmentIntensity = 1.0;
  53852. /**
  53853. * This is a special control allowing the reduction of the specular highlights coming from the
  53854. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53855. */
  53856. _this.specularIntensity = 1.0;
  53857. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53858. /**
  53859. * Debug Control allowing disabling the bump map on this material.
  53860. */
  53861. _this.disableBumpMap = false;
  53862. /**
  53863. * Debug Control helping enforcing or dropping the darkness of shadows.
  53864. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53865. */
  53866. _this.overloadedShadowIntensity = 1.0;
  53867. /**
  53868. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53869. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53870. */
  53871. _this.overloadedShadeIntensity = 1.0;
  53872. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53873. /**
  53874. * The camera exposure used on this material.
  53875. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53876. * This corresponds to a photographic exposure.
  53877. */
  53878. _this.cameraExposure = 1.0;
  53879. /**
  53880. * The camera contrast used on this material.
  53881. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53882. */
  53883. _this.cameraContrast = 1.0;
  53884. /**
  53885. * Color Grading 2D Lookup Texture.
  53886. * This allows special effects like sepia, black and white to sixties rendering style.
  53887. */
  53888. _this.cameraColorGradingTexture = null;
  53889. /**
  53890. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53891. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53892. * 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;
  53893. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53894. */
  53895. _this.cameraColorCurves = null;
  53896. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53897. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53898. /**
  53899. * Debug Control allowing to overload the ambient color.
  53900. * This as to be use with the overloadedAmbientIntensity parameter.
  53901. */
  53902. _this.overloadedAmbient = BABYLON.Color3.White();
  53903. /**
  53904. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53905. */
  53906. _this.overloadedAmbientIntensity = 0.0;
  53907. /**
  53908. * Debug Control allowing to overload the albedo color.
  53909. * This as to be use with the overloadedAlbedoIntensity parameter.
  53910. */
  53911. _this.overloadedAlbedo = BABYLON.Color3.White();
  53912. /**
  53913. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53914. */
  53915. _this.overloadedAlbedoIntensity = 0.0;
  53916. /**
  53917. * Debug Control allowing to overload the reflectivity color.
  53918. * This as to be use with the overloadedReflectivityIntensity parameter.
  53919. */
  53920. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53921. /**
  53922. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53923. */
  53924. _this.overloadedReflectivityIntensity = 0.0;
  53925. /**
  53926. * Debug Control allowing to overload the emissive color.
  53927. * This as to be use with the overloadedEmissiveIntensity parameter.
  53928. */
  53929. _this.overloadedEmissive = BABYLON.Color3.White();
  53930. /**
  53931. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53932. */
  53933. _this.overloadedEmissiveIntensity = 0.0;
  53934. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53935. /**
  53936. * Debug Control allowing to overload the reflection color.
  53937. * This as to be use with the overloadedReflectionIntensity parameter.
  53938. */
  53939. _this.overloadedReflection = BABYLON.Color3.White();
  53940. /**
  53941. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53942. */
  53943. _this.overloadedReflectionIntensity = 0.0;
  53944. /**
  53945. * Debug Control allowing to overload the microsurface.
  53946. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53947. */
  53948. _this.overloadedMicroSurface = 0.0;
  53949. /**
  53950. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53951. */
  53952. _this.overloadedMicroSurfaceIntensity = 0.0;
  53953. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53954. /**
  53955. * AKA Occlusion Texture Intensity in other nomenclature.
  53956. */
  53957. _this.ambientTextureStrength = 1.0;
  53958. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53959. /**
  53960. * AKA Diffuse Color in other nomenclature.
  53961. */
  53962. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53963. /**
  53964. * AKA Specular Color in other nomenclature.
  53965. */
  53966. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53967. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53968. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53969. /**
  53970. * AKA Glossiness in other nomenclature.
  53971. */
  53972. _this.microSurface = 0.9;
  53973. /**
  53974. * source material index of refraction (IOR)' / 'destination material IOR.
  53975. */
  53976. _this.indexOfRefraction = 0.66;
  53977. /**
  53978. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53979. */
  53980. _this.invertRefractionY = false;
  53981. /**
  53982. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53983. * Materials half opaque for instance using refraction could benefit from this control.
  53984. */
  53985. _this.linkRefractionWithTransparency = false;
  53986. /**
  53987. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53988. */
  53989. _this.linkEmissiveWithAlbedo = false;
  53990. _this.useLightmapAsShadowmap = false;
  53991. /**
  53992. * In this mode, the emissive informtaion will always be added to the lighting once.
  53993. * A light for instance can be thought as emissive.
  53994. */
  53995. _this.useEmissiveAsIllumination = false;
  53996. /**
  53997. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53998. */
  53999. _this.useAlphaFromAlbedoTexture = false;
  54000. /**
  54001. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  54002. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  54003. */
  54004. _this.useSpecularOverAlpha = true;
  54005. /**
  54006. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  54007. */
  54008. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  54009. /**
  54010. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  54011. */
  54012. _this.useRoughnessFromMetallicTextureAlpha = true;
  54013. /**
  54014. * Specifies if the metallic texture contains the roughness information in its green channel.
  54015. */
  54016. _this.useRoughnessFromMetallicTextureGreen = false;
  54017. /**
  54018. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  54019. * The material will try to infer what glossiness each pixel should be.
  54020. */
  54021. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  54022. /**
  54023. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  54024. * the creation of the material.
  54025. */
  54026. _this.useScalarInLinearSpace = false;
  54027. /**
  54028. * BJS is using an harcoded light falloff based on a manually sets up range.
  54029. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  54030. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  54031. */
  54032. _this.usePhysicalLightFalloff = true;
  54033. /**
  54034. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  54035. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  54036. */
  54037. _this.useRadianceOverAlpha = true;
  54038. /**
  54039. * Allows using the bump map in parallax mode.
  54040. */
  54041. _this.useParallax = false;
  54042. /**
  54043. * Allows using the bump map in parallax occlusion mode.
  54044. */
  54045. _this.useParallaxOcclusion = false;
  54046. /**
  54047. * Controls the scale bias of the parallax mode.
  54048. */
  54049. _this.parallaxScaleBias = 0.05;
  54050. /**
  54051. * If sets to true, disables all the lights affecting the material.
  54052. */
  54053. _this.disableLighting = false;
  54054. /**
  54055. * Number of Simultaneous lights allowed on the material.
  54056. */
  54057. _this.maxSimultaneousLights = 4;
  54058. /**
  54059. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  54060. */
  54061. _this.invertNormalMapX = false;
  54062. /**
  54063. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  54064. */
  54065. _this.invertNormalMapY = false;
  54066. _this._renderTargets = new BABYLON.SmartArray(16);
  54067. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  54068. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  54069. _this._tempColor = new BABYLON.Color3();
  54070. _this._defines = new PBRMaterialDefines();
  54071. _this._cachedDefines = new PBRMaterialDefines();
  54072. _this._myScene = null;
  54073. _this._myShadowGenerator = null;
  54074. _this._cachedDefines.BonesPerMesh = -1;
  54075. _this.getRenderTargetTextures = function () {
  54076. _this._renderTargets.reset();
  54077. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  54078. _this._renderTargets.push(_this.reflectionTexture);
  54079. }
  54080. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  54081. _this._renderTargets.push(_this.refractionTexture);
  54082. }
  54083. return _this._renderTargets;
  54084. };
  54085. return _this;
  54086. }
  54087. PBRMaterial.prototype.getClassName = function () {
  54088. return "PBRMaterial";
  54089. };
  54090. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  54091. get: function () {
  54092. return this._useLogarithmicDepth;
  54093. },
  54094. set: function (value) {
  54095. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  54096. },
  54097. enumerable: true,
  54098. configurable: true
  54099. });
  54100. PBRMaterial.prototype.needAlphaBlending = function () {
  54101. if (this.linkRefractionWithTransparency) {
  54102. return false;
  54103. }
  54104. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  54105. };
  54106. PBRMaterial.prototype.needAlphaTesting = function () {
  54107. if (this.linkRefractionWithTransparency) {
  54108. return false;
  54109. }
  54110. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  54111. };
  54112. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  54113. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  54114. };
  54115. PBRMaterial.prototype.getAlphaTestTexture = function () {
  54116. return this.albedoTexture;
  54117. };
  54118. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54119. if (!mesh) {
  54120. return true;
  54121. }
  54122. if (this._defines.INSTANCES !== useInstances) {
  54123. return false;
  54124. }
  54125. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  54126. return true;
  54127. }
  54128. return false;
  54129. };
  54130. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  54131. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  54132. };
  54133. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  54134. if (!useScalarInLinear) {
  54135. color.toLinearSpaceToRef(ref);
  54136. }
  54137. else {
  54138. ref.r = color.r;
  54139. ref.g = color.g;
  54140. ref.b = color.b;
  54141. }
  54142. };
  54143. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  54144. var lightIndex = 0;
  54145. var depthValuesAlreadySet = false;
  54146. for (var index = 0; index < scene.lights.length; index++) {
  54147. var light = scene.lights[index];
  54148. if (!light.isEnabled()) {
  54149. continue;
  54150. }
  54151. if (!light.canAffectMesh(mesh)) {
  54152. continue;
  54153. }
  54154. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  54155. // GAMMA CORRECTION.
  54156. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  54157. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  54158. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  54159. if (defines["SPECULARTERM"]) {
  54160. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  54161. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  54162. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  54163. }
  54164. // Shadows
  54165. if (scene.shadowsEnabled) {
  54166. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  54167. }
  54168. lightIndex++;
  54169. if (lightIndex === maxSimultaneousLights)
  54170. break;
  54171. }
  54172. };
  54173. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  54174. if (this.isFrozen) {
  54175. if (this._wasPreviouslyReady) {
  54176. return true;
  54177. }
  54178. }
  54179. var scene = this.getScene();
  54180. var engine = scene.getEngine();
  54181. var needNormals = false;
  54182. var needUVs = false;
  54183. this._defines.reset();
  54184. if (scene.lightsEnabled && !this.disableLighting) {
  54185. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  54186. }
  54187. if (!this.checkReadyOnEveryCall) {
  54188. if (this._renderId === scene.getRenderId()) {
  54189. if (this._checkCache(scene, mesh, useInstances)) {
  54190. return true;
  54191. }
  54192. }
  54193. }
  54194. if (scene.texturesEnabled) {
  54195. if (scene.getEngine().getCaps().textureLOD) {
  54196. this._defines.LODBASEDMICROSFURACE = true;
  54197. }
  54198. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54199. if (!this.albedoTexture.isReady()) {
  54200. return false;
  54201. }
  54202. else {
  54203. needUVs = true;
  54204. this._defines.ALBEDO = true;
  54205. }
  54206. }
  54207. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54208. if (!this.ambientTexture.isReady()) {
  54209. return false;
  54210. }
  54211. else {
  54212. needUVs = true;
  54213. this._defines.AMBIENT = true;
  54214. }
  54215. }
  54216. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54217. if (!this.opacityTexture.isReady()) {
  54218. return false;
  54219. }
  54220. else {
  54221. needUVs = true;
  54222. this._defines.OPACITY = true;
  54223. if (this.opacityTexture.getAlphaFromRGB) {
  54224. this._defines.OPACITYRGB = true;
  54225. }
  54226. }
  54227. }
  54228. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54229. if (!this.reflectionTexture.isReady()) {
  54230. return false;
  54231. }
  54232. else {
  54233. needNormals = true;
  54234. this._defines.REFLECTION = true;
  54235. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  54236. this._defines.INVERTCUBICMAP = true;
  54237. }
  54238. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  54239. switch (this.reflectionTexture.coordinatesMode) {
  54240. case BABYLON.Texture.CUBIC_MODE:
  54241. case BABYLON.Texture.INVCUBIC_MODE:
  54242. this._defines.REFLECTIONMAP_CUBIC = true;
  54243. break;
  54244. case BABYLON.Texture.EXPLICIT_MODE:
  54245. this._defines.REFLECTIONMAP_EXPLICIT = true;
  54246. break;
  54247. case BABYLON.Texture.PLANAR_MODE:
  54248. this._defines.REFLECTIONMAP_PLANAR = true;
  54249. break;
  54250. case BABYLON.Texture.PROJECTION_MODE:
  54251. this._defines.REFLECTIONMAP_PROJECTION = true;
  54252. break;
  54253. case BABYLON.Texture.SKYBOX_MODE:
  54254. this._defines.REFLECTIONMAP_SKYBOX = true;
  54255. break;
  54256. case BABYLON.Texture.SPHERICAL_MODE:
  54257. this._defines.REFLECTIONMAP_SPHERICAL = true;
  54258. break;
  54259. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  54260. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  54261. break;
  54262. }
  54263. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  54264. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  54265. needNormals = true;
  54266. if (this.reflectionTexture.isPMREM) {
  54267. this._defines.USEPMREMREFLECTION = true;
  54268. }
  54269. }
  54270. }
  54271. }
  54272. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54273. if (!this.lightmapTexture.isReady()) {
  54274. return false;
  54275. }
  54276. else {
  54277. needUVs = true;
  54278. this._defines.LIGHTMAP = true;
  54279. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  54280. }
  54281. }
  54282. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54283. if (!this.emissiveTexture.isReady()) {
  54284. return false;
  54285. }
  54286. else {
  54287. needUVs = true;
  54288. this._defines.EMISSIVE = true;
  54289. }
  54290. }
  54291. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54292. if (this.metallicTexture) {
  54293. if (!this.metallicTexture.isReady()) {
  54294. return false;
  54295. }
  54296. else {
  54297. needUVs = true;
  54298. this._defines.METALLICWORKFLOW = true;
  54299. this._defines.METALLICROUGHNESSMAP = true;
  54300. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  54301. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  54302. }
  54303. }
  54304. else if (this.reflectivityTexture) {
  54305. if (!this.reflectivityTexture.isReady()) {
  54306. return false;
  54307. }
  54308. else {
  54309. needUVs = true;
  54310. this._defines.REFLECTIVITY = true;
  54311. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  54312. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  54313. }
  54314. }
  54315. }
  54316. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54317. if (!this.bumpTexture.isReady()) {
  54318. return false;
  54319. }
  54320. else {
  54321. needUVs = true;
  54322. this._defines.BUMP = true;
  54323. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54324. this._defines.PARALLAX = true;
  54325. if (this.useParallaxOcclusion) {
  54326. this._defines.PARALLAXOCCLUSION = true;
  54327. }
  54328. }
  54329. if (this.invertNormalMapX) {
  54330. this._defines.INVERTNORMALMAPX = true;
  54331. }
  54332. if (this.invertNormalMapY) {
  54333. this._defines.INVERTNORMALMAPY = true;
  54334. }
  54335. if (scene._mirroredCameraPosition) {
  54336. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  54337. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  54338. }
  54339. }
  54340. }
  54341. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54342. if (!this.refractionTexture.isReady()) {
  54343. return false;
  54344. }
  54345. else {
  54346. needUVs = true;
  54347. this._defines.REFRACTION = true;
  54348. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  54349. if (this.linkRefractionWithTransparency) {
  54350. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  54351. }
  54352. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  54353. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  54354. if (this.refractionTexture.isPMREM) {
  54355. this._defines.USEPMREMREFRACTION = true;
  54356. }
  54357. }
  54358. }
  54359. }
  54360. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54361. if (!this.cameraColorGradingTexture.isReady()) {
  54362. return false;
  54363. }
  54364. else {
  54365. this._defines.CAMERACOLORGRADING = true;
  54366. }
  54367. }
  54368. }
  54369. // Effect
  54370. if (scene.clipPlane) {
  54371. this._defines.CLIPPLANE = true;
  54372. }
  54373. if (engine.getAlphaTesting()) {
  54374. this._defines.ALPHATEST = true;
  54375. }
  54376. if (this._shouldUseAlphaFromAlbedoTexture()) {
  54377. this._defines.ALPHAFROMALBEDO = true;
  54378. }
  54379. if (this.useEmissiveAsIllumination) {
  54380. this._defines.EMISSIVEASILLUMINATION = true;
  54381. }
  54382. if (this.linkEmissiveWithAlbedo) {
  54383. this._defines.LINKEMISSIVEWITHALBEDO = true;
  54384. }
  54385. if (this.useLogarithmicDepth) {
  54386. this._defines.LOGARITHMICDEPTH = true;
  54387. }
  54388. if (this.cameraContrast != 1) {
  54389. this._defines.CAMERACONTRAST = true;
  54390. }
  54391. if (this.cameraExposure != 1) {
  54392. this._defines.CAMERATONEMAP = true;
  54393. }
  54394. if (this.cameraColorCurves) {
  54395. this._defines.CAMERACOLORCURVES = true;
  54396. }
  54397. if (this.overloadedShadeIntensity != 1 ||
  54398. this.overloadedShadowIntensity != 1) {
  54399. this._defines.OVERLOADEDSHADOWVALUES = true;
  54400. }
  54401. if (this.overloadedMicroSurfaceIntensity > 0 ||
  54402. this.overloadedEmissiveIntensity > 0 ||
  54403. this.overloadedReflectivityIntensity > 0 ||
  54404. this.overloadedAlbedoIntensity > 0 ||
  54405. this.overloadedAmbientIntensity > 0 ||
  54406. this.overloadedReflectionIntensity > 0) {
  54407. this._defines.OVERLOADEDVALUES = true;
  54408. }
  54409. // Point size
  54410. if (this.pointsCloud || scene.forcePointsCloud) {
  54411. this._defines.POINTSIZE = true;
  54412. }
  54413. // Fog
  54414. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54415. this._defines.FOG = true;
  54416. }
  54417. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54418. // Fresnel
  54419. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  54420. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54421. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54422. this._defines.OPACITYFRESNEL = true;
  54423. }
  54424. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54425. this._defines.EMISSIVEFRESNEL = true;
  54426. }
  54427. needNormals = true;
  54428. this._defines.FRESNEL = true;
  54429. }
  54430. }
  54431. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  54432. this._defines.SPECULAROVERALPHA = true;
  54433. }
  54434. if (this.usePhysicalLightFalloff) {
  54435. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  54436. }
  54437. if (this.useRadianceOverAlpha) {
  54438. this._defines.RADIANCEOVERALPHA = true;
  54439. }
  54440. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  54441. this._defines.METALLICWORKFLOW = true;
  54442. }
  54443. // Attribs
  54444. if (mesh) {
  54445. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54446. this._defines.NORMAL = true;
  54447. }
  54448. if (needUVs) {
  54449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54450. this._defines.UV1 = true;
  54451. }
  54452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54453. this._defines.UV2 = true;
  54454. }
  54455. }
  54456. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54457. this._defines.VERTEXCOLOR = true;
  54458. if (mesh.hasVertexAlpha) {
  54459. this._defines.VERTEXALPHA = true;
  54460. }
  54461. }
  54462. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54463. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  54464. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  54465. }
  54466. // Instances
  54467. if (useInstances) {
  54468. this._defines.INSTANCES = true;
  54469. }
  54470. }
  54471. // Get correct effect
  54472. if (!this._defines.isEqual(this._cachedDefines)) {
  54473. this._defines.cloneTo(this._cachedDefines);
  54474. scene.resetCachedMaterial();
  54475. // Fallbacks
  54476. var fallbacks = new BABYLON.EffectFallbacks();
  54477. if (this._defines.REFLECTION) {
  54478. fallbacks.addFallback(0, "REFLECTION");
  54479. }
  54480. if (this._defines.REFRACTION) {
  54481. fallbacks.addFallback(0, "REFRACTION");
  54482. }
  54483. if (this._defines.REFLECTIVITY) {
  54484. fallbacks.addFallback(0, "REFLECTIVITY");
  54485. }
  54486. if (this._defines.BUMP) {
  54487. fallbacks.addFallback(0, "BUMP");
  54488. }
  54489. if (this._defines.PARALLAX) {
  54490. fallbacks.addFallback(1, "PARALLAX");
  54491. }
  54492. if (this._defines.PARALLAXOCCLUSION) {
  54493. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54494. }
  54495. if (this._defines.SPECULAROVERALPHA) {
  54496. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54497. }
  54498. if (this._defines.FOG) {
  54499. fallbacks.addFallback(1, "FOG");
  54500. }
  54501. if (this._defines.POINTSIZE) {
  54502. fallbacks.addFallback(0, "POINTSIZE");
  54503. }
  54504. if (this._defines.LOGARITHMICDEPTH) {
  54505. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54506. }
  54507. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54508. if (this._defines.SPECULARTERM) {
  54509. fallbacks.addFallback(0, "SPECULARTERM");
  54510. }
  54511. if (this._defines.OPACITYFRESNEL) {
  54512. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54513. }
  54514. if (this._defines.EMISSIVEFRESNEL) {
  54515. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54516. }
  54517. if (this._defines.FRESNEL) {
  54518. fallbacks.addFallback(3, "FRESNEL");
  54519. }
  54520. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54521. fallbacks.addCPUSkinningFallback(0, mesh);
  54522. }
  54523. //Attributes
  54524. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54525. if (this._defines.NORMAL) {
  54526. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54527. }
  54528. if (this._defines.UV1) {
  54529. attribs.push(BABYLON.VertexBuffer.UVKind);
  54530. }
  54531. if (this._defines.UV2) {
  54532. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54533. }
  54534. if (this._defines.VERTEXCOLOR) {
  54535. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54536. }
  54537. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54538. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54539. // Legacy browser patch
  54540. var join = this._defines.toString();
  54541. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54542. "vFogInfos", "vFogColor", "pointSize",
  54543. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54544. "mBones",
  54545. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54546. "depthValues",
  54547. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54548. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54549. "logarithmicDepthConstant",
  54550. "vSphericalX", "vSphericalY", "vSphericalZ",
  54551. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54552. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54553. "vMicrosurfaceTextureLods",
  54554. "vCameraInfos"
  54555. ];
  54556. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54557. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54558. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54559. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54560. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54561. }
  54562. if (!this._effect.isReady()) {
  54563. return false;
  54564. }
  54565. this._renderId = scene.getRenderId();
  54566. this._wasPreviouslyReady = true;
  54567. if (mesh) {
  54568. if (!mesh._materialDefines) {
  54569. mesh._materialDefines = new PBRMaterialDefines();
  54570. }
  54571. this._defines.cloneTo(mesh._materialDefines);
  54572. }
  54573. return true;
  54574. };
  54575. PBRMaterial.prototype.unbind = function () {
  54576. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54577. this._effect.setTexture("reflection2DSampler", null);
  54578. }
  54579. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54580. this._effect.setTexture("refraction2DSampler", null);
  54581. }
  54582. _super.prototype.unbind.call(this);
  54583. };
  54584. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54585. this._effect.setMatrix("world", world);
  54586. };
  54587. PBRMaterial.prototype.bind = function (world, mesh) {
  54588. this._myScene = this.getScene();
  54589. // Matrices
  54590. this.bindOnlyWorldMatrix(world);
  54591. // Bones
  54592. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54593. if (this._myScene.getCachedMaterial() !== this) {
  54594. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54595. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54596. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54597. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54598. }
  54599. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54600. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54601. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54602. }
  54603. }
  54604. // Textures
  54605. if (this._myScene.texturesEnabled) {
  54606. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54607. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54608. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54609. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54610. }
  54611. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54612. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54613. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54614. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54615. }
  54616. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54617. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54618. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54619. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54620. }
  54621. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54622. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54623. if (this.reflectionTexture.isCube) {
  54624. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54625. }
  54626. else {
  54627. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54628. }
  54629. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54630. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54631. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54632. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54633. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54634. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54635. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54636. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54637. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54638. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54639. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54640. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54641. }
  54642. }
  54643. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54644. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54645. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54646. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54647. }
  54648. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54649. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54650. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54651. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54652. }
  54653. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54654. if (this.metallicTexture) {
  54655. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54656. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54657. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54658. }
  54659. else if (this.reflectivityTexture) {
  54660. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54661. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54662. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54663. }
  54664. }
  54665. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54666. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54667. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54668. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54669. }
  54670. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54671. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54672. var depth = 1.0;
  54673. if (this.refractionTexture.isCube) {
  54674. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54675. }
  54676. else {
  54677. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54678. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54679. if (this.refractionTexture.depth) {
  54680. depth = this.refractionTexture.depth;
  54681. }
  54682. }
  54683. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54684. }
  54685. if ((this.reflectionTexture || this.refractionTexture)) {
  54686. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54687. }
  54688. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54689. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54690. }
  54691. }
  54692. // Clip plane
  54693. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54694. // Point size
  54695. if (this.pointsCloud) {
  54696. this._effect.setFloat("pointSize", this.pointSize);
  54697. }
  54698. // Colors
  54699. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54700. if (this._defines.METALLICWORKFLOW) {
  54701. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54702. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54703. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54704. }
  54705. else {
  54706. // GAMMA CORRECTION.
  54707. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54708. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54709. }
  54710. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54711. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54712. // GAMMA CORRECTION.
  54713. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54714. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54715. // GAMMA CORRECTION.
  54716. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54717. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54718. }
  54719. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54720. // GAMMA CORRECTION.
  54721. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54722. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54723. // Lights
  54724. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54725. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54726. }
  54727. // View
  54728. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54729. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54730. }
  54731. // Fog
  54732. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54733. this._lightingInfos.x = this.directIntensity;
  54734. this._lightingInfos.y = this.emissiveIntensity;
  54735. this._lightingInfos.z = this.environmentIntensity;
  54736. this._lightingInfos.w = this.specularIntensity;
  54737. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54738. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54739. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54740. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54741. this._cameraInfos.x = this.cameraExposure;
  54742. this._cameraInfos.y = this.cameraContrast;
  54743. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54744. if (this.cameraColorCurves) {
  54745. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54746. }
  54747. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54748. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54749. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54750. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54751. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54752. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54753. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54754. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54755. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54756. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54757. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54758. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54759. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54760. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54761. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54762. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54763. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54764. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54765. // Log. depth
  54766. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54767. }
  54768. _super.prototype.bind.call(this, world, mesh);
  54769. this._myScene = null;
  54770. };
  54771. PBRMaterial.prototype.getAnimatables = function () {
  54772. var results = [];
  54773. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54774. results.push(this.albedoTexture);
  54775. }
  54776. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54777. results.push(this.ambientTexture);
  54778. }
  54779. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54780. results.push(this.opacityTexture);
  54781. }
  54782. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54783. results.push(this.reflectionTexture);
  54784. }
  54785. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54786. results.push(this.emissiveTexture);
  54787. }
  54788. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54789. results.push(this.metallicTexture);
  54790. }
  54791. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54792. results.push(this.reflectivityTexture);
  54793. }
  54794. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54795. results.push(this.bumpTexture);
  54796. }
  54797. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54798. results.push(this.lightmapTexture);
  54799. }
  54800. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54801. results.push(this.refractionTexture);
  54802. }
  54803. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54804. results.push(this.cameraColorGradingTexture);
  54805. }
  54806. return results;
  54807. };
  54808. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54809. if (forceDisposeTextures) {
  54810. if (this.albedoTexture) {
  54811. this.albedoTexture.dispose();
  54812. }
  54813. if (this.ambientTexture) {
  54814. this.ambientTexture.dispose();
  54815. }
  54816. if (this.opacityTexture) {
  54817. this.opacityTexture.dispose();
  54818. }
  54819. if (this.reflectionTexture) {
  54820. this.reflectionTexture.dispose();
  54821. }
  54822. if (this.emissiveTexture) {
  54823. this.emissiveTexture.dispose();
  54824. }
  54825. if (this.metallicTexture) {
  54826. this.metallicTexture.dispose();
  54827. }
  54828. if (this.reflectivityTexture) {
  54829. this.reflectivityTexture.dispose();
  54830. }
  54831. if (this.bumpTexture) {
  54832. this.bumpTexture.dispose();
  54833. }
  54834. if (this.lightmapTexture) {
  54835. this.lightmapTexture.dispose();
  54836. }
  54837. if (this.refractionTexture) {
  54838. this.refractionTexture.dispose();
  54839. }
  54840. if (this.cameraColorGradingTexture) {
  54841. this.cameraColorGradingTexture.dispose();
  54842. }
  54843. }
  54844. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54845. };
  54846. PBRMaterial.prototype.clone = function (name) {
  54847. var _this = this;
  54848. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54849. };
  54850. PBRMaterial.prototype.serialize = function () {
  54851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54852. serializationObject.customType = "BABYLON.PBRMaterial";
  54853. return serializationObject;
  54854. };
  54855. // Statics
  54856. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54857. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54858. };
  54859. return PBRMaterial;
  54860. }(BABYLON.Material));
  54861. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54862. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54863. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54864. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54865. __decorate([
  54866. BABYLON.serialize()
  54867. ], PBRMaterial.prototype, "directIntensity", void 0);
  54868. __decorate([
  54869. BABYLON.serialize()
  54870. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54871. __decorate([
  54872. BABYLON.serialize()
  54873. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54874. __decorate([
  54875. BABYLON.serialize()
  54876. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54877. __decorate([
  54878. BABYLON.serialize()
  54879. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54880. __decorate([
  54881. BABYLON.serialize()
  54882. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54883. __decorate([
  54884. BABYLON.serialize()
  54885. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54886. __decorate([
  54887. BABYLON.serialize()
  54888. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54889. __decorate([
  54890. BABYLON.serialize()
  54891. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54892. __decorate([
  54893. BABYLON.serializeAsTexture()
  54894. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54895. __decorate([
  54896. BABYLON.serializeAsColorCurves()
  54897. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54898. __decorate([
  54899. BABYLON.serializeAsColor3()
  54900. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54901. __decorate([
  54902. BABYLON.serialize()
  54903. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54904. __decorate([
  54905. BABYLON.serializeAsColor3()
  54906. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54907. __decorate([
  54908. BABYLON.serialize()
  54909. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54910. __decorate([
  54911. BABYLON.serializeAsColor3()
  54912. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54913. __decorate([
  54914. BABYLON.serialize()
  54915. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54916. __decorate([
  54917. BABYLON.serializeAsColor3()
  54918. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54919. __decorate([
  54920. BABYLON.serialize()
  54921. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54922. __decorate([
  54923. BABYLON.serializeAsColor3()
  54924. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54925. __decorate([
  54926. BABYLON.serialize()
  54927. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54928. __decorate([
  54929. BABYLON.serialize()
  54930. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54931. __decorate([
  54932. BABYLON.serialize()
  54933. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54934. __decorate([
  54935. BABYLON.serializeAsTexture()
  54936. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54937. __decorate([
  54938. BABYLON.serializeAsTexture()
  54939. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54940. __decorate([
  54941. BABYLON.serialize()
  54942. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54943. __decorate([
  54944. BABYLON.serializeAsTexture()
  54945. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54946. __decorate([
  54947. BABYLON.serializeAsTexture()
  54948. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54949. __decorate([
  54950. BABYLON.serializeAsTexture()
  54951. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54952. __decorate([
  54953. BABYLON.serializeAsTexture()
  54954. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54955. __decorate([
  54956. BABYLON.serializeAsTexture()
  54957. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54958. __decorate([
  54959. BABYLON.serialize()
  54960. ], PBRMaterial.prototype, "metallic", void 0);
  54961. __decorate([
  54962. BABYLON.serialize()
  54963. ], PBRMaterial.prototype, "roughness", void 0);
  54964. __decorate([
  54965. BABYLON.serializeAsTexture()
  54966. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54967. __decorate([
  54968. BABYLON.serializeAsTexture()
  54969. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54970. __decorate([
  54971. BABYLON.serializeAsTexture()
  54972. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54973. __decorate([
  54974. BABYLON.serializeAsColor3("ambient")
  54975. ], PBRMaterial.prototype, "ambientColor", void 0);
  54976. __decorate([
  54977. BABYLON.serializeAsColor3("albedo")
  54978. ], PBRMaterial.prototype, "albedoColor", void 0);
  54979. __decorate([
  54980. BABYLON.serializeAsColor3("reflectivity")
  54981. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54982. __decorate([
  54983. BABYLON.serializeAsColor3("reflection")
  54984. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54985. __decorate([
  54986. BABYLON.serializeAsColor3("emissive")
  54987. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54988. __decorate([
  54989. BABYLON.serialize()
  54990. ], PBRMaterial.prototype, "microSurface", void 0);
  54991. __decorate([
  54992. BABYLON.serialize()
  54993. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54994. __decorate([
  54995. BABYLON.serialize()
  54996. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54997. __decorate([
  54998. BABYLON.serializeAsFresnelParameters()
  54999. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  55000. __decorate([
  55001. BABYLON.serializeAsFresnelParameters()
  55002. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  55003. __decorate([
  55004. BABYLON.serialize()
  55005. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  55006. __decorate([
  55007. BABYLON.serialize()
  55008. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  55009. __decorate([
  55010. BABYLON.serialize()
  55011. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  55012. __decorate([
  55013. BABYLON.serialize()
  55014. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  55015. __decorate([
  55016. BABYLON.serialize()
  55017. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  55018. __decorate([
  55019. BABYLON.serialize()
  55020. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  55021. __decorate([
  55022. BABYLON.serialize()
  55023. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  55024. __decorate([
  55025. BABYLON.serialize()
  55026. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  55027. __decorate([
  55028. BABYLON.serialize()
  55029. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  55030. __decorate([
  55031. BABYLON.serialize()
  55032. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  55033. __decorate([
  55034. BABYLON.serialize()
  55035. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  55036. __decorate([
  55037. BABYLON.serialize()
  55038. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  55039. __decorate([
  55040. BABYLON.serialize()
  55041. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  55042. __decorate([
  55043. BABYLON.serialize()
  55044. ], PBRMaterial.prototype, "useParallax", void 0);
  55045. __decorate([
  55046. BABYLON.serialize()
  55047. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  55048. __decorate([
  55049. BABYLON.serialize()
  55050. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  55051. __decorate([
  55052. BABYLON.serialize()
  55053. ], PBRMaterial.prototype, "disableLighting", void 0);
  55054. __decorate([
  55055. BABYLON.serialize()
  55056. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  55057. __decorate([
  55058. BABYLON.serialize()
  55059. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  55060. __decorate([
  55061. BABYLON.serialize()
  55062. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  55063. __decorate([
  55064. BABYLON.serialize()
  55065. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  55066. BABYLON.PBRMaterial = PBRMaterial;
  55067. })(BABYLON || (BABYLON = {}));
  55068. //# sourceMappingURL=babylon.pbrMaterial.js.map
  55069. var BABYLON;
  55070. (function (BABYLON) {
  55071. var DebugLayer = (function () {
  55072. function DebugLayer(scene) {
  55073. this._scene = scene;
  55074. }
  55075. /** Creates the inspector window. */
  55076. DebugLayer.prototype._createInspector = function (popup) {
  55077. if (!this._inspector) {
  55078. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  55079. } // else nothing to do,; instance is already existing
  55080. };
  55081. DebugLayer.prototype.isVisible = function () {
  55082. return false;
  55083. };
  55084. DebugLayer.prototype.hide = function () {
  55085. if (this._inspector) {
  55086. this._inspector.dispose();
  55087. this._inspector = null;
  55088. }
  55089. };
  55090. DebugLayer.prototype.show = function (popup) {
  55091. if (typeof INSPECTOR == 'undefined') {
  55092. // Load inspector and add it to the DOM
  55093. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  55094. }
  55095. else {
  55096. // Otherwise creates the inspector
  55097. this._createInspector(popup);
  55098. }
  55099. };
  55100. return DebugLayer;
  55101. }());
  55102. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  55103. BABYLON.DebugLayer = DebugLayer;
  55104. })(BABYLON || (BABYLON = {}));
  55105. //# sourceMappingURL=babylon.debugLayer.js.map
  55106. var BABYLON;
  55107. (function (BABYLON) {
  55108. var StandardRenderingPipeline = (function (_super) {
  55109. __extends(StandardRenderingPipeline, _super);
  55110. /**
  55111. * @constructor
  55112. * @param {string} name - The rendering pipeline name
  55113. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55114. * @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)
  55115. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55116. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55117. */
  55118. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55119. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55120. var _this = _super.call(this, scene.getEngine(), name) || this;
  55121. _this.downSampleX4PostProcess = null;
  55122. _this.brightPassPostProcess = null;
  55123. _this.gaussianBlurHPostProcesses = [];
  55124. _this.gaussianBlurVPostProcesses = [];
  55125. _this.textureAdderPostProcess = null;
  55126. _this.textureAdderFinalPostProcess = null;
  55127. _this.lensFlarePostProcess = null;
  55128. _this.lensFlareComposePostProcess = null;
  55129. _this.depthOfFieldPostProcess = null;
  55130. // Values
  55131. _this.brightThreshold = 1.0;
  55132. _this.blurWidth = 2.0;
  55133. _this.gaussianCoefficient = 0.25;
  55134. _this.gaussianMean = 1.0;
  55135. _this.gaussianStandardDeviation = 1.0;
  55136. _this.exposure = 1.0;
  55137. _this.lensTexture = null;
  55138. _this.lensColorTexture = null;
  55139. _this.lensFlareStrength = 20.0;
  55140. _this.lensFlareGhostDispersal = 1.4;
  55141. _this.lensFlareHaloWidth = 0.7;
  55142. _this.lensFlareDistortionStrength = 16.0;
  55143. _this.lensStarTexture = null;
  55144. _this.lensFlareDirtTexture = null;
  55145. _this.depthOfFieldDistance = 10.0;
  55146. // IAnimatable
  55147. _this.animations = [];
  55148. _this._depthRenderer = null;
  55149. // Getters and setters
  55150. _this._depthOfFieldEnabled = true;
  55151. _this._lensFlareEnabled = true;
  55152. // Initialize
  55153. _this._scene = scene;
  55154. // Create pass post-processe
  55155. if (!originalPostProcess) {
  55156. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  55157. }
  55158. else {
  55159. _this.originalPostProcess = originalPostProcess;
  55160. }
  55161. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  55162. // Create down sample X4 post-process
  55163. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  55164. // Create bright pass post-process
  55165. _this._createBrightPassPostProcess(scene, ratio / 2);
  55166. // Create gaussian blur post-processes (down sampling blurs)
  55167. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  55168. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  55169. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  55170. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  55171. // Create texture adder post-process
  55172. _this._createTextureAdderPostProcess(scene, ratio);
  55173. // Create depth-of-field source post-process
  55174. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  55176. // Create lens flare post-process
  55177. _this._createLensFlarePostProcess(scene, ratio);
  55178. // Create gaussian blur used by depth-of-field
  55179. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  55180. // Create depth-of-field post-process
  55181. _this._createDepthOfFieldPostProcess(scene, ratio);
  55182. // Finish
  55183. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55184. if (cameras !== null) {
  55185. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55186. }
  55187. // Deactivate
  55188. _this.LensFlareEnabled = false;
  55189. _this.DepthOfFieldEnabled = false;
  55190. return _this;
  55191. }
  55192. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  55193. get: function () {
  55194. return this._depthOfFieldEnabled;
  55195. },
  55196. set: function (enabled) {
  55197. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  55198. if (enabled && !this._depthOfFieldEnabled) {
  55199. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55200. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55201. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55202. this._depthRenderer = this._scene.enableDepthRenderer();
  55203. }
  55204. else if (!enabled && this._depthOfFieldEnabled) {
  55205. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55206. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55207. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55208. }
  55209. this._depthOfFieldEnabled = enabled;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  55215. get: function () {
  55216. return this._lensFlareEnabled;
  55217. },
  55218. set: function (enabled) {
  55219. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  55220. if (enabled && !this._lensFlareEnabled) {
  55221. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55222. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55223. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55224. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55225. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55226. }
  55227. else if (!enabled && this._lensFlareEnabled) {
  55228. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55229. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55230. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55231. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55232. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55233. }
  55234. this._lensFlareEnabled = enabled;
  55235. },
  55236. enumerable: true,
  55237. configurable: true
  55238. });
  55239. // Down Sample X4 Post-Processs
  55240. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55241. var _this = this;
  55242. var downSampleX4Offsets = new Array(32);
  55243. 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);
  55244. this.downSampleX4PostProcess.onApply = function (effect) {
  55245. var id = 0;
  55246. for (var i = -2; i < 2; i++) {
  55247. for (var j = -2; j < 2; j++) {
  55248. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  55249. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  55250. id += 2;
  55251. }
  55252. }
  55253. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55254. };
  55255. // Add to pipeline
  55256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  55257. };
  55258. // Brightpass Post-Process
  55259. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55260. var _this = this;
  55261. var brightOffsets = new Array(8);
  55262. 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);
  55263. this.brightPassPostProcess.onApply = function (effect) {
  55264. var sU = (1.0 / _this.brightPassPostProcess.width);
  55265. var sV = (1.0 / _this.brightPassPostProcess.height);
  55266. brightOffsets[0] = -0.5 * sU;
  55267. brightOffsets[1] = 0.5 * sV;
  55268. brightOffsets[2] = 0.5 * sU;
  55269. brightOffsets[3] = 0.5 * sV;
  55270. brightOffsets[4] = -0.5 * sU;
  55271. brightOffsets[5] = -0.5 * sV;
  55272. brightOffsets[6] = 0.5 * sU;
  55273. brightOffsets[7] = -0.5 * sV;
  55274. effect.setArray2("dsOffsets", brightOffsets);
  55275. effect.setFloat("brightThreshold", _this.brightThreshold);
  55276. };
  55277. // Add to pipeline
  55278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  55279. };
  55280. // Create gaussian blur H&V post-processes
  55281. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  55282. var _this = this;
  55283. var blurOffsets = new Array(9);
  55284. var blurWeights = new Array(9);
  55285. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  55286. var callback = function (height) {
  55287. return function (effect) {
  55288. // Weights
  55289. var x = 0.0;
  55290. for (var i = 0; i < 9; i++) {
  55291. x = (i - 4.0) / 4.0;
  55292. blurWeights[i] =
  55293. _this.gaussianCoefficient
  55294. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  55295. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  55296. }
  55297. var lastOutputDimensions = {
  55298. width: scene.getEngine().getRenderWidth(),
  55299. height: scene.getEngine().getRenderHeight()
  55300. };
  55301. for (var i = 0; i < 9; i++) {
  55302. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55303. blurOffsets[i] = value;
  55304. }
  55305. effect.setArray("blurOffsets", blurOffsets);
  55306. effect.setArray("blurWeights", blurWeights);
  55307. effect.setFloat("blurWidth", _this.blurWidth);
  55308. };
  55309. };
  55310. // Create horizontal gaussian blur post-processes
  55311. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55312. gaussianBlurHPostProcess.onApply = callback(false);
  55313. // Create vertical gaussian blur post-process
  55314. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55315. gaussianBlurVPostProcess.onApply = callback(true);
  55316. // Add to pipeline
  55317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  55318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  55319. // Finish
  55320. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  55321. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  55322. };
  55323. // Create texture adder post-process
  55324. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55325. var _this = this;
  55326. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  55327. 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);
  55328. this.textureAdderPostProcess.onApply = function (effect) {
  55329. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  55330. effect.setTexture("lensSampler", _this.lensTexture);
  55331. effect.setFloat("exposure", _this.exposure);
  55332. };
  55333. // Add to pipeline
  55334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  55335. };
  55336. // Create lens flare post-process
  55337. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55338. var _this = this;
  55339. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  55341. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  55342. 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);
  55343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  55344. var resolution = new BABYLON.Vector2(0, 0);
  55345. // Lens flare
  55346. this.lensFlarePostProcess.onApply = function (effect) {
  55347. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  55348. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55349. effect.setFloat("strength", _this.lensFlareStrength);
  55350. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55351. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55352. // Shift
  55353. resolution.x = _this.lensFlarePostProcess.width;
  55354. resolution.y = _this.lensFlarePostProcess.height;
  55355. effect.setVector2("resolution", resolution);
  55356. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55357. };
  55358. // Compose
  55359. 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);
  55360. 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);
  55361. this.lensFlareComposePostProcess.onApply = function (effect) {
  55362. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55363. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55364. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55365. // Lens start rotation matrix
  55366. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55367. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55368. 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));
  55369. camRot *= 4.0;
  55370. 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);
  55371. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55372. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55373. };
  55374. };
  55375. // Create depth-of-field post-process
  55376. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55377. var _this = this;
  55378. 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);
  55379. this.depthOfFieldPostProcess.onApply = function (effect) {
  55380. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55381. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  55382. effect.setFloat("distance", _this.depthOfFieldDistance);
  55383. };
  55384. // Add to pipeline
  55385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55386. };
  55387. // Dispose
  55388. StandardRenderingPipeline.prototype.dispose = function () {
  55389. for (var i = 0; i < this._scene.cameras.length; i++) {
  55390. var camera = this._scene.cameras[i];
  55391. this.originalPostProcess.dispose(camera);
  55392. this.downSampleX4PostProcess.dispose(camera);
  55393. this.brightPassPostProcess.dispose(camera);
  55394. this.textureAdderPostProcess.dispose(camera);
  55395. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  55396. this.gaussianBlurHPostProcesses[j].dispose(camera);
  55397. }
  55398. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  55399. this.gaussianBlurVPostProcesses[j].dispose(camera);
  55400. }
  55401. this.textureAdderFinalPostProcess.dispose(camera);
  55402. this.lensFlarePostProcess.dispose(camera);
  55403. this.lensFlareComposePostProcess.dispose(camera);
  55404. this.depthOfFieldPostProcess.dispose(camera);
  55405. }
  55406. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55407. _super.prototype.dispose.call(this);
  55408. };
  55409. return StandardRenderingPipeline;
  55410. }(BABYLON.PostProcessRenderPipeline));
  55411. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55412. })(BABYLON || (BABYLON = {}));
  55413. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55414. 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\nfFogDistance=abs(viewPos.z);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 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}"};
  55415. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=abs((view*worldPos).z);\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  55416. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";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);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){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(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},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){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=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 t(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 t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.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},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var 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},t.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},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.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)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.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},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.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},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.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)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.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},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.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.multiply=function(t){\nvar 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],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,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]);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)},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.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.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0),new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  55417. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55418. module.exports = BABYLON;
  55419. };