babylon.2.0-alpha.debug.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  311. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  594. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. 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]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. 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);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. 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);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var screenshotCanvas;
  1711. var fpsRange = 60;
  1712. var previousFramesDuration = [];
  1713. var fps = 60;
  1714. var deltaTime = 0;
  1715. var cloneValue = function (source, destinationObject) {
  1716. if (!source)
  1717. return null;
  1718. if (source instanceof BABYLON.Mesh) {
  1719. return null;
  1720. }
  1721. if (source instanceof BABYLON.SubMesh) {
  1722. return source.clone(destinationObject);
  1723. } else if (source.clone) {
  1724. return source.clone();
  1725. }
  1726. return null;
  1727. };
  1728. var Tools = (function () {
  1729. function Tools() {
  1730. }
  1731. Tools.GetFilename = function (path) {
  1732. var index = path.lastIndexOf("/");
  1733. if (index < 0)
  1734. return path;
  1735. return path.substring(index + 1);
  1736. };
  1737. Tools.GetDOMTextContent = function (element) {
  1738. var result = "";
  1739. var child = element.firstChild;
  1740. while (child) {
  1741. if (child.nodeType == 3) {
  1742. result += child.textContent;
  1743. }
  1744. child = child.nextSibling;
  1745. }
  1746. return result;
  1747. };
  1748. Tools.ToDegrees = function (angle) {
  1749. return angle * 180 / Math.PI;
  1750. };
  1751. Tools.ToRadians = function (angle) {
  1752. return angle * Math.PI / 180;
  1753. };
  1754. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1761. }
  1762. return {
  1763. minimum: minimum,
  1764. maximum: maximum
  1765. };
  1766. };
  1767. Tools.ExtractMinAndMax = function (positions, start, count) {
  1768. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1769. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1770. for (var index = start; index < start + count; index++) {
  1771. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1772. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1773. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1774. }
  1775. return {
  1776. minimum: minimum,
  1777. maximum: maximum
  1778. };
  1779. };
  1780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1782. return undefined;
  1783. return Array.isArray(obj) ? obj : [obj];
  1784. };
  1785. Tools.GetPointerPrefix = function () {
  1786. var eventPrefix = "pointer";
  1787. if (!navigator.pointerEnabled) {
  1788. eventPrefix = "mouse";
  1789. }
  1790. return eventPrefix;
  1791. };
  1792. Tools.QueueNewFrame = function (func) {
  1793. if (window.requestAnimationFrame)
  1794. window.requestAnimationFrame(func);
  1795. else if (window.msRequestAnimationFrame)
  1796. window.msRequestAnimationFrame(func);
  1797. else if (window.webkitRequestAnimationFrame)
  1798. window.webkitRequestAnimationFrame(func);
  1799. else if (window.mozRequestAnimationFrame)
  1800. window.mozRequestAnimationFrame(func);
  1801. else if (window.oRequestAnimationFrame)
  1802. window.oRequestAnimationFrame(func);
  1803. else {
  1804. window.setTimeout(func, 16);
  1805. }
  1806. };
  1807. Tools.RequestFullscreen = function (element) {
  1808. if (element.requestFullscreen)
  1809. element.requestFullscreen();
  1810. else if (element.msRequestFullscreen)
  1811. element.msRequestFullscreen();
  1812. else if (element.webkitRequestFullscreen)
  1813. element.webkitRequestFullscreen();
  1814. else if (element.mozRequestFullScreen)
  1815. element.mozRequestFullScreen();
  1816. };
  1817. Tools.ExitFullscreen = function () {
  1818. if (document.exitFullscreen) {
  1819. document.exitFullscreen();
  1820. } else if (document.mozCancelFullScreen) {
  1821. document.mozCancelFullScreen();
  1822. } else if (document.webkitCancelFullScreen) {
  1823. document.webkitCancelFullScreen();
  1824. } else if (document.msCancelFullScreen) {
  1825. document.msCancelFullScreen();
  1826. }
  1827. };
  1828. Tools.CleanUrl = function (url) {
  1829. url = url.replace(/#/mg, "%23");
  1830. return url;
  1831. };
  1832. Tools.LoadImage = function (url, onload, onerror, database) {
  1833. url = Tools.CleanUrl(url);
  1834. var img = new Image();
  1835. if (url.substr(0, 5) != "data:")
  1836. img.crossOrigin = 'anonymous';
  1837. img.onload = function () {
  1838. onload(img);
  1839. };
  1840. img.onerror = function (err) {
  1841. onerror(img, err);
  1842. };
  1843. var noIndexedDB = function () {
  1844. img.src = url;
  1845. };
  1846. var loadFromIndexedDB = function () {
  1847. database.loadImageFromDB(url, img);
  1848. };
  1849. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1850. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1851. } else {
  1852. if (url.indexOf("file:") === -1) {
  1853. noIndexedDB();
  1854. } else {
  1855. try {
  1856. var textureName = url.substring(5);
  1857. var blobURL;
  1858. try {
  1859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1860. } catch (ex) {
  1861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1862. }
  1863. img.src = blobURL;
  1864. } catch (e) {
  1865. Tools.Log("Error while trying to load texture: " + textureName);
  1866. img.src = null;
  1867. }
  1868. }
  1869. }
  1870. return img;
  1871. };
  1872. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1873. url = Tools.CleanUrl(url);
  1874. var noIndexedDB = function () {
  1875. var request = new XMLHttpRequest();
  1876. var loadUrl = Tools.BaseUrl + url;
  1877. request.open('GET', loadUrl, true);
  1878. if (useArrayBuffer) {
  1879. request.responseType = "arraybuffer";
  1880. }
  1881. request.onprogress = progressCallBack;
  1882. request.onreadystatechange = function () {
  1883. if (request.readyState == 4) {
  1884. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1885. callback(!useArrayBuffer ? request.responseText : request.response);
  1886. } else {
  1887. if (onError) {
  1888. onError();
  1889. } else {
  1890. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1891. }
  1892. }
  1893. }
  1894. };
  1895. request.send(null);
  1896. };
  1897. var loadFromIndexedDB = function () {
  1898. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1899. };
  1900. if (url.indexOf("file:") !== -1) {
  1901. var fileName = url.substring(5);
  1902. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1903. } else {
  1904. if (database && database.enableSceneOffline) {
  1905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1906. } else {
  1907. noIndexedDB();
  1908. }
  1909. }
  1910. };
  1911. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1912. var reader = new FileReader();
  1913. reader.onload = function (e) {
  1914. callback(e.target.result);
  1915. };
  1916. reader.onprogress = progressCallback;
  1917. reader.readAsDataURL(fileToLoad);
  1918. };
  1919. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1920. var reader = new FileReader();
  1921. reader.onload = function (e) {
  1922. callback(e.target.result);
  1923. };
  1924. reader.onprogress = progressCallBack;
  1925. if (!useArrayBuffer) {
  1926. reader.readAsText(fileToLoad);
  1927. } else {
  1928. reader.readAsArrayBuffer(fileToLoad);
  1929. }
  1930. };
  1931. Tools.CheckExtends = function (v, min, max) {
  1932. if (v.x < min.x)
  1933. min.x = v.x;
  1934. if (v.y < min.y)
  1935. min.y = v.y;
  1936. if (v.z < min.z)
  1937. min.z = v.z;
  1938. if (v.x > max.x)
  1939. max.x = v.x;
  1940. if (v.y > max.y)
  1941. max.y = v.y;
  1942. if (v.z > max.z)
  1943. max.z = v.z;
  1944. };
  1945. Tools.WithinEpsilon = function (a, b) {
  1946. var num = a - b;
  1947. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1948. };
  1949. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1950. for (var prop in source) {
  1951. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1952. continue;
  1953. }
  1954. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1955. continue;
  1956. }
  1957. var sourceValue = source[prop];
  1958. var typeOfSourceValue = typeof sourceValue;
  1959. if (typeOfSourceValue == "function") {
  1960. continue;
  1961. }
  1962. if (typeOfSourceValue == "object") {
  1963. if (sourceValue instanceof Array) {
  1964. destination[prop] = [];
  1965. if (sourceValue.length > 0) {
  1966. if (typeof sourceValue[0] == "object") {
  1967. for (var index = 0; index < sourceValue.length; index++) {
  1968. var clonedValue = cloneValue(sourceValue[index], destination);
  1969. if (destination[prop].indexOf(clonedValue) === -1) {
  1970. destination[prop].push(clonedValue);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = sourceValue.slice(0);
  1975. }
  1976. }
  1977. } else {
  1978. destination[prop] = cloneValue(sourceValue, destination);
  1979. }
  1980. } else {
  1981. destination[prop] = sourceValue;
  1982. }
  1983. }
  1984. };
  1985. Tools.IsEmpty = function (obj) {
  1986. for (var i in obj) {
  1987. return false;
  1988. }
  1989. return true;
  1990. };
  1991. Tools.RegisterTopRootEvents = function (events) {
  1992. for (var index = 0; index < events.length; index++) {
  1993. var event = events[index];
  1994. window.addEventListener(event.name, event.handler, false);
  1995. try {
  1996. if (window.parent) {
  1997. window.parent.addEventListener(event.name, event.handler, false);
  1998. }
  1999. } catch (e) {
  2000. }
  2001. }
  2002. };
  2003. Tools.UnregisterTopRootEvents = function (events) {
  2004. for (var index = 0; index < events.length; index++) {
  2005. var event = events[index];
  2006. window.removeEventListener(event.name, event.handler);
  2007. try {
  2008. if (window.parent) {
  2009. window.parent.removeEventListener(event.name, event.handler);
  2010. }
  2011. } catch (e) {
  2012. }
  2013. }
  2014. };
  2015. Tools.GetFps = function () {
  2016. return fps;
  2017. };
  2018. Tools.GetDeltaTime = function () {
  2019. return deltaTime;
  2020. };
  2021. Tools._MeasureFps = function () {
  2022. previousFramesDuration.push(Tools.Now);
  2023. var length = previousFramesDuration.length;
  2024. if (length >= 2) {
  2025. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2026. }
  2027. if (length >= fpsRange) {
  2028. if (length > fpsRange) {
  2029. previousFramesDuration.splice(0, 1);
  2030. length = previousFramesDuration.length;
  2031. }
  2032. var sum = 0;
  2033. for (var id = 0; id < length - 1; id++) {
  2034. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2035. }
  2036. fps = 1000.0 / (sum / (length - 1));
  2037. }
  2038. };
  2039. Tools.CreateScreenshot = function (engine, camera, size) {
  2040. var width;
  2041. var height;
  2042. var scene = camera.getScene();
  2043. var previousCamera = null;
  2044. if (scene.activeCamera !== camera) {
  2045. previousCamera = scene.activeCamera;
  2046. scene.activeCamera = camera;
  2047. }
  2048. if (size.precision) {
  2049. width = Math.round(engine.getRenderWidth() * size.precision);
  2050. height = Math.round(width / engine.getAspectRatio(camera));
  2051. size = { width: width, height: height };
  2052. } else if (size.width && size.height) {
  2053. width = size.width;
  2054. height = size.height;
  2055. } else if (size.width && !size.height) {
  2056. width = size.width;
  2057. height = Math.round(width / engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (size.height && !size.width) {
  2060. height = size.height;
  2061. width = Math.round(height * engine.getAspectRatio(camera));
  2062. size = { width: width, height: height };
  2063. } else if (!isNaN(size)) {
  2064. height = size;
  2065. width = size;
  2066. } else {
  2067. Tools.Error("Invalid 'size' parameter !");
  2068. return;
  2069. }
  2070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2071. texture.renderList = engine.scenes[0].meshes;
  2072. texture.onAfterRender = function () {
  2073. var numberOfChannelsByLine = width * 4;
  2074. var halfHeight = height / 2;
  2075. var data = engine.readPixels(0, 0, width, height);
  2076. for (var i = 0; i < halfHeight; i++) {
  2077. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2078. var currentCell = j + i * numberOfChannelsByLine;
  2079. var targetLine = height - i - 1;
  2080. var targetCell = j + targetLine * numberOfChannelsByLine;
  2081. var temp = data[currentCell];
  2082. data[currentCell] = data[targetCell];
  2083. data[targetCell] = temp;
  2084. }
  2085. }
  2086. if (!screenshotCanvas) {
  2087. screenshotCanvas = document.createElement('canvas');
  2088. }
  2089. screenshotCanvas.width = width;
  2090. screenshotCanvas.height = height;
  2091. var context = screenshotCanvas.getContext('2d');
  2092. var imageData = context.createImageData(width, height);
  2093. imageData.data.set(data);
  2094. context.putImageData(imageData, 0, 0);
  2095. var base64Image = screenshotCanvas.toDataURL();
  2096. if (("download" in document.createElement("a"))) {
  2097. var a = window.document.createElement("a");
  2098. a.href = base64Image;
  2099. var date = new Date();
  2100. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2101. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2102. window.document.body.appendChild(a);
  2103. a.addEventListener("click", function () {
  2104. a.parentElement.removeChild(a);
  2105. });
  2106. a.click();
  2107. } else {
  2108. var newWindow = window.open("");
  2109. var img = newWindow.document.createElement("img");
  2110. img.src = base64Image;
  2111. newWindow.document.body.appendChild(img);
  2112. }
  2113. };
  2114. texture.render(true);
  2115. texture.dispose();
  2116. if (previousCamera) {
  2117. scene.activeCamera = previousCamera;
  2118. }
  2119. };
  2120. Tools.ValidateXHRData = function (xhr, dataType) {
  2121. if (typeof dataType === "undefined") { dataType = 7; }
  2122. try {
  2123. if (dataType & 1) {
  2124. if (xhr.responseText && xhr.responseText.length > 0) {
  2125. return true;
  2126. } else if (dataType === 1) {
  2127. return false;
  2128. }
  2129. }
  2130. if (dataType & 2) {
  2131. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2132. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2133. return true;
  2134. } else if (dataType === 2) {
  2135. return false;
  2136. }
  2137. }
  2138. if (dataType & 4) {
  2139. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2140. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2141. return true;
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. } catch (e) {
  2147. }
  2148. return false;
  2149. };
  2150. Object.defineProperty(Tools, "NoneLogLevel", {
  2151. get: function () {
  2152. return Tools._NoneLogLevel;
  2153. },
  2154. enumerable: true,
  2155. configurable: true
  2156. });
  2157. Object.defineProperty(Tools, "MessageLogLevel", {
  2158. get: function () {
  2159. return Tools._MessageLogLevel;
  2160. },
  2161. enumerable: true,
  2162. configurable: true
  2163. });
  2164. Object.defineProperty(Tools, "WarningLogLevel", {
  2165. get: function () {
  2166. return Tools._WarningLogLevel;
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Object.defineProperty(Tools, "ErrorLogLevel", {
  2172. get: function () {
  2173. return Tools._ErrorLogLevel;
  2174. },
  2175. enumerable: true,
  2176. configurable: true
  2177. });
  2178. Object.defineProperty(Tools, "AllLogLevel", {
  2179. get: function () {
  2180. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2181. },
  2182. enumerable: true,
  2183. configurable: true
  2184. });
  2185. Tools._FormatMessage = function (message) {
  2186. var padStr = function (i) {
  2187. return (i < 10) ? "0" + i : "" + i;
  2188. };
  2189. var date = new Date();
  2190. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2191. };
  2192. Tools._LogDisabled = function (message) {
  2193. };
  2194. Tools._LogEnabled = function (message) {
  2195. console.log(Tools._FormatMessage(message));
  2196. };
  2197. Tools._WarnDisabled = function (message) {
  2198. };
  2199. Tools._WarnEnabled = function (message) {
  2200. console.warn(Tools._FormatMessage(message));
  2201. };
  2202. Tools._ErrorDisabled = function (message) {
  2203. };
  2204. Tools._ErrorEnabled = function (message) {
  2205. console.error(Tools._FormatMessage(message));
  2206. };
  2207. Object.defineProperty(Tools, "LogLevels", {
  2208. set: function (level) {
  2209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2210. Tools.Log = Tools._LogEnabled;
  2211. } else {
  2212. Tools.Log = Tools._LogDisabled;
  2213. }
  2214. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2215. Tools.Warn = Tools._WarnEnabled;
  2216. } else {
  2217. Tools.Warn = Tools._WarnDisabled;
  2218. }
  2219. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2220. Tools.Error = Tools._ErrorEnabled;
  2221. } else {
  2222. Tools.Error = Tools._ErrorDisabled;
  2223. }
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2229. get: function () {
  2230. return Tools._PerformanceNoneLogLevel;
  2231. },
  2232. enumerable: true,
  2233. configurable: true
  2234. });
  2235. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2236. get: function () {
  2237. return Tools._PerformanceUserMarkLogLevel;
  2238. },
  2239. enumerable: true,
  2240. configurable: true
  2241. });
  2242. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2243. get: function () {
  2244. return Tools._PerformanceConsoleLogLevel;
  2245. },
  2246. enumerable: true,
  2247. configurable: true
  2248. });
  2249. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2250. set: function (level) {
  2251. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2252. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2253. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2254. return;
  2255. }
  2256. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2257. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2258. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2259. return;
  2260. }
  2261. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2262. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2263. },
  2264. enumerable: true,
  2265. configurable: true
  2266. });
  2267. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2268. };
  2269. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2270. };
  2271. Tools._StartUserMark = function (counterName, condition) {
  2272. if (typeof condition === "undefined") { condition = true; }
  2273. if (!condition || !Tools._performance.mark) {
  2274. return;
  2275. }
  2276. Tools._performance.mark(counterName + "-Begin");
  2277. };
  2278. Tools._EndUserMark = function (counterName, condition) {
  2279. if (typeof condition === "undefined") { condition = true; }
  2280. if (!condition || !Tools._performance.mark) {
  2281. return;
  2282. }
  2283. Tools._performance.mark(counterName + "-End");
  2284. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2285. };
  2286. Tools._StartPerformanceConsole = function (counterName, condition) {
  2287. if (typeof condition === "undefined") { condition = true; }
  2288. if (!condition) {
  2289. return;
  2290. }
  2291. Tools._StartUserMark(counterName, condition);
  2292. if (console.time) {
  2293. console.time(counterName);
  2294. }
  2295. };
  2296. Tools._EndPerformanceConsole = function (counterName, condition) {
  2297. if (typeof condition === "undefined") { condition = true; }
  2298. if (!condition) {
  2299. return;
  2300. }
  2301. Tools._EndUserMark(counterName, condition);
  2302. if (console.time) {
  2303. console.timeEnd(counterName);
  2304. }
  2305. };
  2306. Object.defineProperty(Tools, "Now", {
  2307. get: function () {
  2308. if (window.performance.now) {
  2309. return window.performance.now();
  2310. }
  2311. return new Date().getTime();
  2312. },
  2313. enumerable: true,
  2314. configurable: true
  2315. });
  2316. Tools.BaseUrl = "";
  2317. Tools.GetExponantOfTwo = function (value, max) {
  2318. var count = 1;
  2319. do {
  2320. count *= 2;
  2321. } while(count < value);
  2322. if (count > max)
  2323. count = max;
  2324. return count;
  2325. };
  2326. Tools._NoneLogLevel = 0;
  2327. Tools._MessageLogLevel = 1;
  2328. Tools._WarningLogLevel = 2;
  2329. Tools._ErrorLogLevel = 4;
  2330. Tools.Log = Tools._LogEnabled;
  2331. Tools.Warn = Tools._WarnEnabled;
  2332. Tools.Error = Tools._ErrorEnabled;
  2333. Tools._PerformanceNoneLogLevel = 0;
  2334. Tools._PerformanceUserMarkLogLevel = 1;
  2335. Tools._PerformanceConsoleLogLevel = 2;
  2336. Tools._performance = window.performance;
  2337. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2338. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2339. return Tools;
  2340. })();
  2341. BABYLON.Tools = Tools;
  2342. })(BABYLON || (BABYLON = {}));
  2343. var BABYLON;
  2344. (function (BABYLON) {
  2345. var _DepthCullingState = (function () {
  2346. function _DepthCullingState() {
  2347. this._isDepthTestDirty = false;
  2348. this._isDepthMaskDirty = false;
  2349. this._isDepthFuncDirty = false;
  2350. this._isCullFaceDirty = false;
  2351. this._isCullDirty = false;
  2352. }
  2353. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2354. get: function () {
  2355. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2356. },
  2357. enumerable: true,
  2358. configurable: true
  2359. });
  2360. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2361. get: function () {
  2362. return this._cullFace;
  2363. },
  2364. set: function (value) {
  2365. if (this._cullFace === value) {
  2366. return;
  2367. }
  2368. this._cullFace = value;
  2369. this._isCullFaceDirty = true;
  2370. },
  2371. enumerable: true,
  2372. configurable: true
  2373. });
  2374. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2375. get: function () {
  2376. return this._cull;
  2377. },
  2378. set: function (value) {
  2379. if (this._cull === value) {
  2380. return;
  2381. }
  2382. this._cull = value;
  2383. this._isCullDirty = true;
  2384. },
  2385. enumerable: true,
  2386. configurable: true
  2387. });
  2388. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2389. get: function () {
  2390. return this._depthFunc;
  2391. },
  2392. set: function (value) {
  2393. if (this._depthFunc === value) {
  2394. return;
  2395. }
  2396. this._depthFunc = value;
  2397. this._isDepthFuncDirty = true;
  2398. },
  2399. enumerable: true,
  2400. configurable: true
  2401. });
  2402. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2403. get: function () {
  2404. return this._depthMask;
  2405. },
  2406. set: function (value) {
  2407. if (this._depthMask === value) {
  2408. return;
  2409. }
  2410. this._depthMask = value;
  2411. this._isDepthMaskDirty = true;
  2412. },
  2413. enumerable: true,
  2414. configurable: true
  2415. });
  2416. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2417. get: function () {
  2418. return this._depthTest;
  2419. },
  2420. set: function (value) {
  2421. if (this._depthTest === value) {
  2422. return;
  2423. }
  2424. this._depthTest = value;
  2425. this._isDepthTestDirty = true;
  2426. },
  2427. enumerable: true,
  2428. configurable: true
  2429. });
  2430. _DepthCullingState.prototype.reset = function () {
  2431. this._depthMask = true;
  2432. this._depthTest = true;
  2433. this._depthFunc = null;
  2434. this._cull = null;
  2435. this._cullFace = null;
  2436. this._isDepthTestDirty = true;
  2437. this._isDepthMaskDirty = true;
  2438. this._isDepthFuncDirty = false;
  2439. this._isCullFaceDirty = false;
  2440. this._isCullDirty = false;
  2441. };
  2442. _DepthCullingState.prototype.apply = function (gl) {
  2443. if (!this.isDirty) {
  2444. return;
  2445. }
  2446. if (this._isCullDirty) {
  2447. if (this.cull === true) {
  2448. gl.enable(gl.CULL_FACE);
  2449. } else if (this.cull === false) {
  2450. gl.disable(gl.CULL_FACE);
  2451. }
  2452. this._isCullDirty = false;
  2453. }
  2454. if (this._isCullFaceDirty) {
  2455. gl.cullFace(this.cullFace);
  2456. this._isCullFaceDirty = false;
  2457. }
  2458. if (this._isDepthMaskDirty) {
  2459. gl.depthMask(this.depthMask);
  2460. this._isDepthMaskDirty = false;
  2461. }
  2462. if (this._isDepthTestDirty) {
  2463. if (this.depthTest === true) {
  2464. gl.enable(gl.DEPTH_TEST);
  2465. } else if (this.depthTest === false) {
  2466. gl.disable(gl.DEPTH_TEST);
  2467. }
  2468. this._isDepthTestDirty = false;
  2469. }
  2470. if (this._isDepthFuncDirty) {
  2471. gl.depthFunc(this.depthFunc);
  2472. this._isDepthFuncDirty = false;
  2473. }
  2474. };
  2475. return _DepthCullingState;
  2476. })();
  2477. BABYLON._DepthCullingState = _DepthCullingState;
  2478. var _AlphaState = (function () {
  2479. function _AlphaState() {
  2480. this._isAlphaBlendDirty = false;
  2481. this._isBlendFunctionParametersDirty = false;
  2482. this._alphaBlend = false;
  2483. this._blendFunctionParameters = new Array(4);
  2484. }
  2485. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2486. get: function () {
  2487. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2488. },
  2489. enumerable: true,
  2490. configurable: true
  2491. });
  2492. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2493. get: function () {
  2494. return this._alphaBlend;
  2495. },
  2496. set: function (value) {
  2497. if (this._alphaBlend === value) {
  2498. return;
  2499. }
  2500. this._alphaBlend = value;
  2501. this._isAlphaBlendDirty = true;
  2502. },
  2503. enumerable: true,
  2504. configurable: true
  2505. });
  2506. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2507. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2508. return;
  2509. }
  2510. this._blendFunctionParameters[0] = value0;
  2511. this._blendFunctionParameters[1] = value1;
  2512. this._blendFunctionParameters[2] = value2;
  2513. this._blendFunctionParameters[3] = value3;
  2514. this._isBlendFunctionParametersDirty = true;
  2515. };
  2516. _AlphaState.prototype.reset = function () {
  2517. this._alphaBlend = false;
  2518. this._blendFunctionParameters[0] = null;
  2519. this._blendFunctionParameters[1] = null;
  2520. this._blendFunctionParameters[2] = null;
  2521. this._blendFunctionParameters[3] = null;
  2522. this._isAlphaBlendDirty = true;
  2523. this._isBlendFunctionParametersDirty = false;
  2524. };
  2525. _AlphaState.prototype.apply = function (gl) {
  2526. if (!this.isDirty) {
  2527. return;
  2528. }
  2529. if (this._isAlphaBlendDirty) {
  2530. if (this._alphaBlend === true) {
  2531. gl.enable(gl.BLEND);
  2532. } else if (this._alphaBlend === false) {
  2533. gl.disable(gl.BLEND);
  2534. }
  2535. this._isAlphaBlendDirty = false;
  2536. }
  2537. if (this._isBlendFunctionParametersDirty) {
  2538. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2539. this._isBlendFunctionParametersDirty = false;
  2540. }
  2541. };
  2542. return _AlphaState;
  2543. })();
  2544. BABYLON._AlphaState = _AlphaState;
  2545. var compileShader = function (gl, source, type, defines) {
  2546. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2547. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2548. gl.compileShader(shader);
  2549. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2550. throw new Error(gl.getShaderInfoLog(shader));
  2551. }
  2552. return shader;
  2553. };
  2554. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2555. var magFilter = gl.NEAREST;
  2556. var minFilter = gl.NEAREST;
  2557. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2558. magFilter = gl.LINEAR;
  2559. if (generateMipMaps) {
  2560. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2561. } else {
  2562. minFilter = gl.LINEAR;
  2563. }
  2564. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2565. magFilter = gl.LINEAR;
  2566. if (generateMipMaps) {
  2567. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2568. } else {
  2569. minFilter = gl.LINEAR;
  2570. }
  2571. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2572. magFilter = gl.NEAREST;
  2573. if (generateMipMaps) {
  2574. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2575. } else {
  2576. minFilter = gl.NEAREST;
  2577. }
  2578. }
  2579. return {
  2580. min: minFilter,
  2581. mag: magFilter
  2582. };
  2583. };
  2584. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2585. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2586. var engine = scene.getEngine();
  2587. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2588. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2589. gl.bindTexture(gl.TEXTURE_2D, texture);
  2590. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2591. processFunction(potWidth, potHeight);
  2592. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2593. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2594. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2595. if (!noMipmap && !isCompressed) {
  2596. gl.generateMipmap(gl.TEXTURE_2D);
  2597. }
  2598. gl.bindTexture(gl.TEXTURE_2D, null);
  2599. engine._activeTexturesCache = [];
  2600. texture._baseWidth = width;
  2601. texture._baseHeight = height;
  2602. texture._width = potWidth;
  2603. texture._height = potHeight;
  2604. texture.isReady = true;
  2605. scene._removePendingData(texture);
  2606. };
  2607. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2608. var img;
  2609. var onload = function () {
  2610. loadedImages[index] = img;
  2611. loadedImages._internalCount++;
  2612. scene._removePendingData(img);
  2613. if (loadedImages._internalCount == 6) {
  2614. onfinish(loadedImages);
  2615. }
  2616. };
  2617. var onerror = function () {
  2618. scene._removePendingData(img);
  2619. };
  2620. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2621. scene._addPendingData(img);
  2622. };
  2623. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2624. var loadedImages = [];
  2625. loadedImages._internalCount = 0;
  2626. for (var index = 0; index < 6; index++) {
  2627. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2628. }
  2629. };
  2630. var EngineCapabilities = (function () {
  2631. function EngineCapabilities() {
  2632. }
  2633. return EngineCapabilities;
  2634. })();
  2635. BABYLON.EngineCapabilities = EngineCapabilities;
  2636. var Engine = (function () {
  2637. function Engine(canvas, antialias, options) {
  2638. var _this = this;
  2639. this.isFullscreen = false;
  2640. this.isPointerLock = false;
  2641. this.forceWireframe = false;
  2642. this.cullBackFaces = true;
  2643. this.renderEvenInBackground = true;
  2644. this.scenes = new Array();
  2645. this._windowIsBackground = false;
  2646. this._runningLoop = false;
  2647. this._loadingDivBackgroundColor = "black";
  2648. this._depthCullingState = new _DepthCullingState();
  2649. this._alphaState = new _AlphaState();
  2650. this._loadedTexturesCache = new Array();
  2651. this._activeTexturesCache = new Array();
  2652. this._compiledEffects = {};
  2653. this._renderingCanvas = canvas;
  2654. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2655. options = options || {};
  2656. options.antialias = antialias;
  2657. try {
  2658. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2659. } catch (e) {
  2660. throw new Error("WebGL not supported");
  2661. }
  2662. if (!this._gl) {
  2663. throw new Error("WebGL not supported");
  2664. }
  2665. this._onBlur = function () {
  2666. _this._windowIsBackground = true;
  2667. };
  2668. this._onFocus = function () {
  2669. _this._windowIsBackground = false;
  2670. };
  2671. window.addEventListener("blur", this._onBlur);
  2672. window.addEventListener("focus", this._onFocus);
  2673. this._workingCanvas = document.createElement("canvas");
  2674. this._workingContext = this._workingCanvas.getContext("2d");
  2675. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2676. this.resize();
  2677. this._caps = new EngineCapabilities();
  2678. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2679. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2680. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2681. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2682. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2683. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2684. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2685. 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');
  2686. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2687. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2688. this.setDepthBuffer(true);
  2689. this.setDepthFunctionToLessOrEqual();
  2690. this.setDepthWrite(true);
  2691. this._onFullscreenChange = function () {
  2692. if (document.fullscreen !== undefined) {
  2693. _this.isFullscreen = document.fullscreen;
  2694. } else if (document.mozFullScreen !== undefined) {
  2695. _this.isFullscreen = document.mozFullScreen;
  2696. } else if (document.webkitIsFullScreen !== undefined) {
  2697. _this.isFullscreen = document.webkitIsFullScreen;
  2698. } else if (document.msIsFullScreen !== undefined) {
  2699. _this.isFullscreen = document.msIsFullScreen;
  2700. }
  2701. if (_this.isFullscreen && _this._pointerLockRequested) {
  2702. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2703. if (canvas.requestPointerLock) {
  2704. canvas.requestPointerLock();
  2705. }
  2706. }
  2707. };
  2708. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2709. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2710. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2711. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2712. this._onPointerLockChange = function () {
  2713. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2714. };
  2715. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2716. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2717. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2718. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2719. }
  2720. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2721. get: function () {
  2722. return Engine._ALPHA_DISABLE;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Engine, "ALPHA_ADD", {
  2728. get: function () {
  2729. return Engine._ALPHA_ADD;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2735. get: function () {
  2736. return Engine._ALPHA_COMBINE;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2742. get: function () {
  2743. return Engine._DELAYLOADSTATE_NONE;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2749. get: function () {
  2750. return Engine._DELAYLOADSTATE_LOADED;
  2751. },
  2752. enumerable: true,
  2753. configurable: true
  2754. });
  2755. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2756. get: function () {
  2757. return Engine._DELAYLOADSTATE_LOADING;
  2758. },
  2759. enumerable: true,
  2760. configurable: true
  2761. });
  2762. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2763. get: function () {
  2764. return Engine._DELAYLOADSTATE_NOTLOADED;
  2765. },
  2766. enumerable: true,
  2767. configurable: true
  2768. });
  2769. Object.defineProperty(Engine, "Version", {
  2770. get: function () {
  2771. return "1.14.0";
  2772. },
  2773. enumerable: true,
  2774. configurable: true
  2775. });
  2776. Engine.prototype.getAspectRatio = function (camera) {
  2777. var viewport = camera.viewport;
  2778. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2779. };
  2780. Engine.prototype.getRenderWidth = function () {
  2781. if (this._currentRenderTarget) {
  2782. return this._currentRenderTarget._width;
  2783. }
  2784. return this._renderingCanvas.width;
  2785. };
  2786. Engine.prototype.getRenderHeight = function () {
  2787. if (this._currentRenderTarget) {
  2788. return this._currentRenderTarget._height;
  2789. }
  2790. return this._renderingCanvas.height;
  2791. };
  2792. Engine.prototype.getRenderingCanvas = function () {
  2793. return this._renderingCanvas;
  2794. };
  2795. Engine.prototype.getRenderingCanvasClientRect = function () {
  2796. return this._renderingCanvas.getBoundingClientRect();
  2797. };
  2798. Engine.prototype.setHardwareScalingLevel = function (level) {
  2799. this._hardwareScalingLevel = level;
  2800. this.resize();
  2801. };
  2802. Engine.prototype.getHardwareScalingLevel = function () {
  2803. return this._hardwareScalingLevel;
  2804. };
  2805. Engine.prototype.getLoadedTexturesCache = function () {
  2806. return this._loadedTexturesCache;
  2807. };
  2808. Engine.prototype.getCaps = function () {
  2809. return this._caps;
  2810. };
  2811. Engine.prototype.setDepthFunctionToGreater = function () {
  2812. this._depthCullingState.depthFunc = this._gl.GREATER;
  2813. };
  2814. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2815. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2816. };
  2817. Engine.prototype.setDepthFunctionToLess = function () {
  2818. this._depthCullingState.depthFunc = this._gl.LESS;
  2819. };
  2820. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2821. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2822. };
  2823. Engine.prototype.stopRenderLoop = function () {
  2824. this._renderFunction = null;
  2825. this._runningLoop = false;
  2826. };
  2827. Engine.prototype._renderLoop = function () {
  2828. var _this = this;
  2829. var shouldRender = true;
  2830. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2831. shouldRender = false;
  2832. }
  2833. if (shouldRender) {
  2834. this.beginFrame();
  2835. if (this._renderFunction) {
  2836. this._renderFunction();
  2837. }
  2838. this.endFrame();
  2839. }
  2840. if (this._runningLoop) {
  2841. BABYLON.Tools.QueueNewFrame(function () {
  2842. _this._renderLoop();
  2843. });
  2844. }
  2845. };
  2846. Engine.prototype.runRenderLoop = function (renderFunction) {
  2847. var _this = this;
  2848. this._runningLoop = true;
  2849. this._renderFunction = renderFunction;
  2850. BABYLON.Tools.QueueNewFrame(function () {
  2851. _this._renderLoop();
  2852. });
  2853. };
  2854. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2855. if (this.isFullscreen) {
  2856. BABYLON.Tools.ExitFullscreen();
  2857. } else {
  2858. this._pointerLockRequested = requestPointerLock;
  2859. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2860. }
  2861. };
  2862. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2863. this.applyStates();
  2864. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2865. if (this._depthCullingState.depthMask) {
  2866. this._gl.clearDepth(1.0);
  2867. }
  2868. var mode = 0;
  2869. if (backBuffer)
  2870. mode |= this._gl.COLOR_BUFFER_BIT;
  2871. if (depthStencil && this._depthCullingState.depthMask)
  2872. mode |= this._gl.DEPTH_BUFFER_BIT;
  2873. this._gl.clear(mode);
  2874. };
  2875. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2876. var width = requiredWidth || this._renderingCanvas.width;
  2877. var height = requiredHeight || this._renderingCanvas.height;
  2878. var x = viewport.x || 0;
  2879. var y = viewport.y || 0;
  2880. this._cachedViewport = viewport;
  2881. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2882. };
  2883. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2884. this._cachedViewport = null;
  2885. this._gl.viewport(x, y, width, height);
  2886. };
  2887. Engine.prototype.beginFrame = function () {
  2888. BABYLON.Tools._MeasureFps();
  2889. };
  2890. Engine.prototype.endFrame = function () {
  2891. this.flushFramebuffer();
  2892. };
  2893. Engine.prototype.resize = function () {
  2894. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2895. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2896. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2897. };
  2898. Engine.prototype.bindFramebuffer = function (texture) {
  2899. this._currentRenderTarget = texture;
  2900. var gl = this._gl;
  2901. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2902. this._gl.viewport(0, 0, texture._width, texture._height);
  2903. this.wipeCaches();
  2904. };
  2905. Engine.prototype.unBindFramebuffer = function (texture) {
  2906. this._currentRenderTarget = null;
  2907. if (texture.generateMipMaps) {
  2908. var gl = this._gl;
  2909. gl.bindTexture(gl.TEXTURE_2D, texture);
  2910. gl.generateMipmap(gl.TEXTURE_2D);
  2911. gl.bindTexture(gl.TEXTURE_2D, null);
  2912. }
  2913. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2914. };
  2915. Engine.prototype.flushFramebuffer = function () {
  2916. this._gl.flush();
  2917. };
  2918. Engine.prototype.restoreDefaultFramebuffer = function () {
  2919. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2920. this.setViewport(this._cachedViewport);
  2921. this.wipeCaches();
  2922. };
  2923. Engine.prototype._resetVertexBufferBinding = function () {
  2924. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2925. this._cachedVertexBuffers = null;
  2926. };
  2927. Engine.prototype.createVertexBuffer = function (vertices) {
  2928. var vbo = this._gl.createBuffer();
  2929. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2930. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2931. this._resetVertexBufferBinding();
  2932. vbo.references = 1;
  2933. return vbo;
  2934. };
  2935. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2936. var vbo = this._gl.createBuffer();
  2937. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2938. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2939. this._resetVertexBufferBinding();
  2940. vbo.references = 1;
  2941. return vbo;
  2942. };
  2943. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2944. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2945. if (vertices instanceof Float32Array) {
  2946. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2947. } else {
  2948. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2949. }
  2950. this._resetVertexBufferBinding();
  2951. };
  2952. Engine.prototype._resetIndexBufferBinding = function () {
  2953. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2954. this._cachedIndexBuffer = null;
  2955. };
  2956. Engine.prototype.createIndexBuffer = function (indices) {
  2957. var vbo = this._gl.createBuffer();
  2958. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2959. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2960. this._resetIndexBufferBinding();
  2961. vbo.references = 1;
  2962. return vbo;
  2963. };
  2964. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2965. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2966. this._cachedVertexBuffers = vertexBuffer;
  2967. this._cachedEffectForVertexBuffers = effect;
  2968. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2969. var offset = 0;
  2970. for (var index = 0; index < vertexDeclaration.length; index++) {
  2971. var order = effect.getAttributeLocation(index);
  2972. if (order >= 0) {
  2973. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2974. }
  2975. offset += vertexDeclaration[index] * 4;
  2976. }
  2977. }
  2978. if (this._cachedIndexBuffer !== indexBuffer) {
  2979. this._cachedIndexBuffer = indexBuffer;
  2980. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2981. }
  2982. };
  2983. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2984. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2985. this._cachedVertexBuffers = vertexBuffers;
  2986. this._cachedEffectForVertexBuffers = effect;
  2987. var attributes = effect.getAttributesNames();
  2988. for (var index = 0; index < attributes.length; index++) {
  2989. var order = effect.getAttributeLocation(index);
  2990. if (order >= 0) {
  2991. var vertexBuffer = vertexBuffers[attributes[index]];
  2992. if (!vertexBuffer) {
  2993. continue;
  2994. }
  2995. var stride = vertexBuffer.getStrideSize();
  2996. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2997. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2998. }
  2999. }
  3000. }
  3001. if (this._cachedIndexBuffer !== indexBuffer) {
  3002. this._cachedIndexBuffer = indexBuffer;
  3003. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3004. }
  3005. };
  3006. Engine.prototype._releaseBuffer = function (buffer) {
  3007. buffer.references--;
  3008. if (buffer.references === 0) {
  3009. this._gl.deleteBuffer(buffer);
  3010. return true;
  3011. }
  3012. return false;
  3013. };
  3014. Engine.prototype.createInstancesBuffer = function (capacity) {
  3015. var buffer = this._gl.createBuffer();
  3016. buffer.capacity = capacity;
  3017. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3018. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3019. return buffer;
  3020. };
  3021. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3022. this._gl.deleteBuffer(buffer);
  3023. };
  3024. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3025. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3027. for (var index = 0; index < 4; index++) {
  3028. var offsetLocation = offsetLocations[index];
  3029. this._gl.enableVertexAttribArray(offsetLocation);
  3030. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3031. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3032. }
  3033. };
  3034. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3035. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3036. for (var index = 0; index < 4; index++) {
  3037. var offsetLocation = offsetLocations[index];
  3038. this._gl.disableVertexAttribArray(offsetLocation);
  3039. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3040. }
  3041. };
  3042. Engine.prototype.applyStates = function () {
  3043. this._depthCullingState.apply(this._gl);
  3044. this._alphaState.apply(this._gl);
  3045. };
  3046. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3047. this.applyStates();
  3048. if (instancesCount) {
  3049. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3050. return;
  3051. }
  3052. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3053. };
  3054. Engine.prototype._releaseEffect = function (effect) {
  3055. if (this._compiledEffects[effect._key]) {
  3056. delete this._compiledEffects[effect._key];
  3057. if (effect.getProgram()) {
  3058. this._gl.deleteProgram(effect.getProgram());
  3059. }
  3060. }
  3061. };
  3062. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3063. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3064. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3065. var name = vertex + "+" + fragment + "@" + defines;
  3066. if (this._compiledEffects[name]) {
  3067. return this._compiledEffects[name];
  3068. }
  3069. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3070. effect._key = name;
  3071. this._compiledEffects[name] = effect;
  3072. return effect;
  3073. };
  3074. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3075. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3076. if (typeof samplers === "undefined") { samplers = []; }
  3077. if (typeof defines === "undefined") { defines = ""; }
  3078. return this.createEffect({
  3079. vertex: "particles",
  3080. fragmentElement: fragmentName
  3081. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3082. };
  3083. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3084. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3085. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3086. var shaderProgram = this._gl.createProgram();
  3087. this._gl.attachShader(shaderProgram, vertexShader);
  3088. this._gl.attachShader(shaderProgram, fragmentShader);
  3089. this._gl.linkProgram(shaderProgram);
  3090. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3091. if (!linked) {
  3092. var error = this._gl.getProgramInfoLog(shaderProgram);
  3093. if (error) {
  3094. throw new Error(error);
  3095. }
  3096. }
  3097. this._gl.deleteShader(vertexShader);
  3098. this._gl.deleteShader(fragmentShader);
  3099. return shaderProgram;
  3100. };
  3101. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3102. var results = [];
  3103. for (var index = 0; index < uniformsNames.length; index++) {
  3104. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3105. }
  3106. return results;
  3107. };
  3108. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3109. var results = [];
  3110. for (var index = 0; index < attributesNames.length; index++) {
  3111. try {
  3112. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3113. } catch (e) {
  3114. results.push(-1);
  3115. }
  3116. }
  3117. return results;
  3118. };
  3119. Engine.prototype.enableEffect = function (effect) {
  3120. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3121. return;
  3122. }
  3123. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3124. this._gl.useProgram(effect.getProgram());
  3125. for (var i in this._vertexAttribArrays) {
  3126. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3127. continue;
  3128. }
  3129. this._vertexAttribArrays[i] = false;
  3130. this._gl.disableVertexAttribArray(i);
  3131. }
  3132. var attributesCount = effect.getAttributesCount();
  3133. for (var index = 0; index < attributesCount; index++) {
  3134. var order = effect.getAttributeLocation(index);
  3135. if (order >= 0) {
  3136. this._vertexAttribArrays[order] = true;
  3137. this._gl.enableVertexAttribArray(order);
  3138. }
  3139. }
  3140. this._currentEffect = effect;
  3141. };
  3142. Engine.prototype.setArray = function (uniform, array) {
  3143. if (!uniform)
  3144. return;
  3145. this._gl.uniform1fv(uniform, array);
  3146. };
  3147. Engine.prototype.setMatrices = function (uniform, matrices) {
  3148. if (!uniform)
  3149. return;
  3150. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3151. };
  3152. Engine.prototype.setMatrix = function (uniform, matrix) {
  3153. if (!uniform)
  3154. return;
  3155. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3156. };
  3157. Engine.prototype.setFloat = function (uniform, value) {
  3158. if (!uniform)
  3159. return;
  3160. this._gl.uniform1f(uniform, value);
  3161. };
  3162. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3163. if (!uniform)
  3164. return;
  3165. this._gl.uniform2f(uniform, x, y);
  3166. };
  3167. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3168. if (!uniform)
  3169. return;
  3170. this._gl.uniform3f(uniform, x, y, z);
  3171. };
  3172. Engine.prototype.setBool = function (uniform, bool) {
  3173. if (!uniform)
  3174. return;
  3175. this._gl.uniform1i(uniform, bool);
  3176. };
  3177. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3178. if (!uniform)
  3179. return;
  3180. this._gl.uniform4f(uniform, x, y, z, w);
  3181. };
  3182. Engine.prototype.setColor3 = function (uniform, color3) {
  3183. if (!uniform)
  3184. return;
  3185. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3186. };
  3187. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3188. if (!uniform)
  3189. return;
  3190. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3191. };
  3192. Engine.prototype.setState = function (culling, force) {
  3193. if (this._depthCullingState.cull !== culling || force) {
  3194. if (culling) {
  3195. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3196. this._depthCullingState.cull = true;
  3197. } else {
  3198. this._depthCullingState.cull = false;
  3199. }
  3200. }
  3201. };
  3202. Engine.prototype.setDepthBuffer = function (enable) {
  3203. this._depthCullingState.depthTest = enable;
  3204. };
  3205. Engine.prototype.getDepthWrite = function () {
  3206. return this._depthCullingState.depthMask;
  3207. };
  3208. Engine.prototype.setDepthWrite = function (enable) {
  3209. this._depthCullingState.depthMask = enable;
  3210. };
  3211. Engine.prototype.setColorWrite = function (enable) {
  3212. this._gl.colorMask(enable, enable, enable, enable);
  3213. };
  3214. Engine.prototype.setAlphaMode = function (mode) {
  3215. switch (mode) {
  3216. case BABYLON.Engine.ALPHA_DISABLE:
  3217. this.setDepthWrite(true);
  3218. this._alphaState.alphaBlend = false;
  3219. break;
  3220. case BABYLON.Engine.ALPHA_COMBINE:
  3221. this.setDepthWrite(false);
  3222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3223. this._alphaState.alphaBlend = true;
  3224. break;
  3225. case BABYLON.Engine.ALPHA_ADD:
  3226. this.setDepthWrite(false);
  3227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3228. this._alphaState.alphaBlend = true;
  3229. break;
  3230. }
  3231. };
  3232. Engine.prototype.setAlphaTesting = function (enable) {
  3233. this._alphaTest = enable;
  3234. };
  3235. Engine.prototype.getAlphaTesting = function () {
  3236. return this._alphaTest;
  3237. };
  3238. Engine.prototype.wipeCaches = function () {
  3239. this._activeTexturesCache = [];
  3240. this._currentEffect = null;
  3241. this._depthCullingState.reset();
  3242. this._alphaState.reset();
  3243. this._cachedVertexBuffers = null;
  3244. this._cachedIndexBuffer = null;
  3245. this._cachedEffectForVertexBuffers = null;
  3246. };
  3247. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3248. var gl = this._gl;
  3249. gl.bindTexture(gl.TEXTURE_2D, texture);
  3250. var magFilter = gl.NEAREST;
  3251. var minFilter = gl.NEAREST;
  3252. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3253. magFilter = gl.LINEAR;
  3254. minFilter = gl.LINEAR;
  3255. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3256. magFilter = gl.LINEAR;
  3257. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3258. }
  3259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3261. gl.bindTexture(gl.TEXTURE_2D, null);
  3262. };
  3263. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3264. var _this = this;
  3265. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3266. if (typeof onLoad === "undefined") { onLoad = null; }
  3267. if (typeof onError === "undefined") { onError = null; }
  3268. if (typeof buffer === "undefined") { buffer = null; }
  3269. var texture = this._gl.createTexture();
  3270. var extension;
  3271. var fromData = false;
  3272. if (url.substr(0, 5) === "data:") {
  3273. fromData = true;
  3274. }
  3275. if (!fromData)
  3276. extension = url.substr(url.length - 4, 4).toLowerCase();
  3277. else {
  3278. var oldUrl = url;
  3279. fromData = oldUrl.split(':');
  3280. url = oldUrl;
  3281. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3282. }
  3283. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3284. var isTGA = (extension === ".tga");
  3285. scene._addPendingData(texture);
  3286. texture.url = url;
  3287. texture.noMipmap = noMipmap;
  3288. texture.references = 1;
  3289. this._loadedTexturesCache.push(texture);
  3290. var onerror = function () {
  3291. scene._removePendingData(texture);
  3292. if (onError) {
  3293. onError();
  3294. }
  3295. };
  3296. if (isTGA) {
  3297. var callback = function (arrayBuffer) {
  3298. var data = new Uint8Array(arrayBuffer);
  3299. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3300. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3301. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3302. if (onLoad) {
  3303. onLoad();
  3304. }
  3305. }, samplingMode);
  3306. };
  3307. if (!(fromData instanceof Array))
  3308. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3309. callback(arrayBuffer);
  3310. }, onerror, scene.database, true);
  3311. else
  3312. callback(buffer);
  3313. } else if (isDDS) {
  3314. callback = function (data) {
  3315. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3316. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3317. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3318. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3319. if (onLoad) {
  3320. onLoad();
  3321. }
  3322. }, samplingMode);
  3323. };
  3324. if (!(fromData instanceof Array))
  3325. BABYLON.Tools.LoadFile(url, function (data) {
  3326. callback(data);
  3327. }, onerror, scene.database, true);
  3328. else
  3329. callback(buffer);
  3330. } else {
  3331. var onload = function (img) {
  3332. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3333. var isPot = (img.width == potWidth && img.height == potHeight);
  3334. if (!isPot) {
  3335. _this._workingCanvas.width = potWidth;
  3336. _this._workingCanvas.height = potHeight;
  3337. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3338. }
  3339. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3340. if (onLoad) {
  3341. onLoad();
  3342. }
  3343. }, samplingMode);
  3344. };
  3345. if (!(fromData instanceof Array))
  3346. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3347. else
  3348. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3349. }
  3350. return texture;
  3351. };
  3352. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3353. var texture = this._gl.createTexture();
  3354. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3355. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3356. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3357. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3358. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3359. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3360. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3361. this._activeTexturesCache = [];
  3362. texture._baseWidth = width;
  3363. texture._baseHeight = height;
  3364. texture._width = width;
  3365. texture._height = height;
  3366. texture.isReady = false;
  3367. texture.generateMipMaps = generateMipMaps;
  3368. texture.references = 1;
  3369. this._loadedTexturesCache.push(texture);
  3370. return texture;
  3371. };
  3372. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3373. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3374. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3375. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3376. if (texture.generateMipMaps) {
  3377. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3378. }
  3379. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3380. this._activeTexturesCache = [];
  3381. texture.isReady = true;
  3382. };
  3383. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3384. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3385. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3386. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3387. if (!texture._workingCanvas) {
  3388. texture._workingCanvas = document.createElement("canvas");
  3389. texture._workingContext = texture._workingCanvas.getContext("2d");
  3390. texture._workingCanvas.width = texture._width;
  3391. texture._workingCanvas.height = texture._height;
  3392. }
  3393. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3394. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3395. } else {
  3396. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3397. }
  3398. if (texture.generateMipMaps) {
  3399. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3400. }
  3401. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3402. this._activeTexturesCache = [];
  3403. texture.isReady = true;
  3404. };
  3405. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3406. var generateMipMaps = false;
  3407. var generateDepthBuffer = true;
  3408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3409. if (options !== undefined) {
  3410. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3412. if (options.samplingMode !== undefined) {
  3413. samplingMode = options.samplingMode;
  3414. }
  3415. }
  3416. var gl = this._gl;
  3417. var texture = gl.createTexture();
  3418. gl.bindTexture(gl.TEXTURE_2D, texture);
  3419. var width = size.width || size;
  3420. var height = size.height || size;
  3421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3426. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3427. var depthBuffer;
  3428. if (generateDepthBuffer) {
  3429. depthBuffer = gl.createRenderbuffer();
  3430. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3431. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3432. }
  3433. var framebuffer = gl.createFramebuffer();
  3434. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3435. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3436. if (generateDepthBuffer) {
  3437. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3438. }
  3439. gl.bindTexture(gl.TEXTURE_2D, null);
  3440. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3441. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3442. texture._framebuffer = framebuffer;
  3443. if (generateDepthBuffer) {
  3444. texture._depthBuffer = depthBuffer;
  3445. }
  3446. texture._width = width;
  3447. texture._height = height;
  3448. texture.isReady = true;
  3449. texture.generateMipMaps = generateMipMaps;
  3450. texture.references = 1;
  3451. this._activeTexturesCache = [];
  3452. this._loadedTexturesCache.push(texture);
  3453. return texture;
  3454. };
  3455. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3456. var _this = this;
  3457. var gl = this._gl;
  3458. var texture = gl.createTexture();
  3459. texture.isCube = true;
  3460. texture.url = rootUrl;
  3461. texture.references = 1;
  3462. this._loadedTexturesCache.push(texture);
  3463. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3464. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3465. if (isDDS) {
  3466. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3467. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3468. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3469. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3470. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3471. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3472. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3473. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3474. }
  3475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3479. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3480. _this._activeTexturesCache = [];
  3481. texture._width = info.width;
  3482. texture._height = info.height;
  3483. texture.isReady = true;
  3484. }, null, null, true);
  3485. } else {
  3486. cascadeLoad(rootUrl, scene, function (imgs) {
  3487. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3488. var height = width;
  3489. _this._workingCanvas.width = width;
  3490. _this._workingCanvas.height = height;
  3491. var faces = [
  3492. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3493. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3494. ];
  3495. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3497. for (var index = 0; index < faces.length; index++) {
  3498. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3499. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3500. }
  3501. if (!noMipmap) {
  3502. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3503. }
  3504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3508. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3509. _this._activeTexturesCache = [];
  3510. texture._width = width;
  3511. texture._height = height;
  3512. texture.isReady = true;
  3513. }, extensions);
  3514. }
  3515. return texture;
  3516. };
  3517. Engine.prototype._releaseTexture = function (texture) {
  3518. var gl = this._gl;
  3519. if (texture._framebuffer) {
  3520. gl.deleteFramebuffer(texture._framebuffer);
  3521. }
  3522. if (texture._depthBuffer) {
  3523. gl.deleteRenderbuffer(texture._depthBuffer);
  3524. }
  3525. gl.deleteTexture(texture);
  3526. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3527. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3528. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3529. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3530. this._activeTexturesCache[channel] = null;
  3531. }
  3532. var index = this._loadedTexturesCache.indexOf(texture);
  3533. if (index !== -1) {
  3534. this._loadedTexturesCache.splice(index, 1);
  3535. }
  3536. };
  3537. Engine.prototype.bindSamplers = function (effect) {
  3538. this._gl.useProgram(effect.getProgram());
  3539. var samplers = effect.getSamplers();
  3540. for (var index = 0; index < samplers.length; index++) {
  3541. var uniform = effect.getUniform(samplers[index]);
  3542. this._gl.uniform1i(uniform, index);
  3543. }
  3544. this._currentEffect = null;
  3545. };
  3546. Engine.prototype._bindTexture = function (channel, texture) {
  3547. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3548. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3549. this._activeTexturesCache[channel] = null;
  3550. };
  3551. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3552. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3553. };
  3554. Engine.prototype.setTexture = function (channel, texture) {
  3555. if (channel < 0) {
  3556. return;
  3557. }
  3558. if (!texture || !texture.isReady()) {
  3559. if (this._activeTexturesCache[channel] != null) {
  3560. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3561. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3562. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3563. this._activeTexturesCache[channel] = null;
  3564. }
  3565. return;
  3566. }
  3567. if (texture instanceof BABYLON.VideoTexture) {
  3568. if (texture.update()) {
  3569. this._activeTexturesCache[channel] = null;
  3570. }
  3571. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3572. texture.delayLoad();
  3573. return;
  3574. }
  3575. if (this._activeTexturesCache[channel] == texture) {
  3576. return;
  3577. }
  3578. this._activeTexturesCache[channel] = texture;
  3579. var internalTexture = texture.getInternalTexture();
  3580. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3581. if (internalTexture.isCube) {
  3582. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3583. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3584. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3585. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3586. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3587. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3588. }
  3589. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3590. } else {
  3591. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3592. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3593. internalTexture._cachedWrapU = texture.wrapU;
  3594. switch (texture.wrapU) {
  3595. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3597. break;
  3598. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3600. break;
  3601. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3602. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3603. break;
  3604. }
  3605. }
  3606. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3607. internalTexture._cachedWrapV = texture.wrapV;
  3608. switch (texture.wrapV) {
  3609. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3611. break;
  3612. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3614. break;
  3615. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3617. break;
  3618. }
  3619. }
  3620. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3621. }
  3622. };
  3623. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3624. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3625. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3626. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3627. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3628. }
  3629. };
  3630. Engine.prototype.readPixels = function (x, y, width, height) {
  3631. var data = new Uint8Array(height * width * 4);
  3632. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3633. return data;
  3634. };
  3635. Engine.prototype.dispose = function () {
  3636. this.hideLoadingUI();
  3637. this.stopRenderLoop();
  3638. while (this.scenes.length) {
  3639. this.scenes[0].dispose();
  3640. }
  3641. for (var name in this._compiledEffects) {
  3642. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3643. }
  3644. for (var i in this._vertexAttribArrays) {
  3645. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3646. continue;
  3647. }
  3648. this._gl.disableVertexAttribArray(i);
  3649. }
  3650. window.removeEventListener("blur", this._onBlur);
  3651. window.removeEventListener("focus", this._onFocus);
  3652. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3653. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3654. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3655. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3656. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3657. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3658. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3659. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3660. };
  3661. Engine.prototype.displayLoadingUI = function () {
  3662. var _this = this;
  3663. this._loadingDiv = document.createElement("div");
  3664. this._loadingDiv.style.opacity = "0";
  3665. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3666. this._loadingTextDiv = document.createElement("div");
  3667. this._loadingTextDiv.style.position = "absolute";
  3668. this._loadingTextDiv.style.left = "0";
  3669. this._loadingTextDiv.style.top = "50%";
  3670. this._loadingTextDiv.style.marginTop = "80px";
  3671. this._loadingTextDiv.style.width = "100%";
  3672. this._loadingTextDiv.style.height = "20px";
  3673. this._loadingTextDiv.style.fontFamily = "Arial";
  3674. this._loadingTextDiv.style.fontSize = "14px";
  3675. this._loadingTextDiv.style.color = "white";
  3676. this._loadingTextDiv.style.textAlign = "center";
  3677. this._loadingTextDiv.innerHTML = "Loading";
  3678. this._loadingDiv.appendChild(this._loadingTextDiv);
  3679. var imgBack = new Image();
  3680. 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==";
  3681. imgBack.style.position = "absolute";
  3682. imgBack.style.left = "50%";
  3683. imgBack.style.top = "50%";
  3684. imgBack.style.marginLeft = "-50px";
  3685. imgBack.style.marginTop = "-50px";
  3686. imgBack.style.transition = "transform 1.0s ease";
  3687. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3688. var deg = 360;
  3689. var onTransitionEnd = function () {
  3690. deg += 360;
  3691. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3692. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3693. };
  3694. imgBack.addEventListener("transitionend", onTransitionEnd);
  3695. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3696. this._loadingDiv.appendChild(imgBack);
  3697. var imgFront = new Image();
  3698. 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=";
  3699. imgFront.style.position = "absolute";
  3700. imgFront.style.left = "50%";
  3701. imgFront.style.top = "50%";
  3702. imgFront.style.marginLeft = "-50px";
  3703. imgFront.style.marginTop = "-50px";
  3704. this._loadingDiv.appendChild(imgFront);
  3705. this._resizeLoadingUI = function () {
  3706. var canvasRect = _this.getRenderingCanvasClientRect();
  3707. _this._loadingDiv.style.position = "absolute";
  3708. _this._loadingDiv.style.left = canvasRect.left + "px";
  3709. _this._loadingDiv.style.top = canvasRect.top + "px";
  3710. _this._loadingDiv.style.width = canvasRect.width + "px";
  3711. _this._loadingDiv.style.height = canvasRect.height + "px";
  3712. };
  3713. this._resizeLoadingUI();
  3714. window.addEventListener("resize", this._resizeLoadingUI);
  3715. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3716. document.body.appendChild(this._loadingDiv);
  3717. setTimeout(function () {
  3718. _this._loadingDiv.style.opacity = "1";
  3719. imgBack.style.transform = "rotateZ(360deg)";
  3720. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3721. }, 0);
  3722. };
  3723. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3724. set: function (text) {
  3725. if (!this._loadingDiv) {
  3726. return;
  3727. }
  3728. this._loadingTextDiv.innerHTML = text;
  3729. },
  3730. enumerable: true,
  3731. configurable: true
  3732. });
  3733. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3734. get: function () {
  3735. return this._loadingDivBackgroundColor;
  3736. },
  3737. set: function (color) {
  3738. this._loadingDivBackgroundColor = color;
  3739. if (!this._loadingDiv) {
  3740. return;
  3741. }
  3742. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3743. },
  3744. enumerable: true,
  3745. configurable: true
  3746. });
  3747. Engine.prototype.hideLoadingUI = function () {
  3748. var _this = this;
  3749. if (!this._loadingDiv) {
  3750. return;
  3751. }
  3752. var onTransitionEnd = function () {
  3753. if (!_this._loadingDiv) {
  3754. return;
  3755. }
  3756. document.body.removeChild(_this._loadingDiv);
  3757. window.removeEventListener("resize", _this._resizeLoadingUI);
  3758. _this._loadingDiv = null;
  3759. };
  3760. this._loadingDiv.style.opacity = "0";
  3761. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3762. };
  3763. Engine.isSupported = function () {
  3764. try {
  3765. var tempcanvas = document.createElement("canvas");
  3766. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3767. return gl != null && !!window.WebGLRenderingContext;
  3768. } catch (e) {
  3769. return false;
  3770. }
  3771. };
  3772. Engine._ALPHA_DISABLE = 0;
  3773. Engine._ALPHA_ADD = 1;
  3774. Engine._ALPHA_COMBINE = 2;
  3775. Engine._DELAYLOADSTATE_NONE = 0;
  3776. Engine._DELAYLOADSTATE_LOADED = 1;
  3777. Engine._DELAYLOADSTATE_LOADING = 2;
  3778. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3779. Engine.Epsilon = 0.001;
  3780. Engine.CollisionsEpsilon = 0.001;
  3781. Engine.ShadersRepository = "Babylon/Shaders/";
  3782. return Engine;
  3783. })();
  3784. BABYLON.Engine = Engine;
  3785. })(BABYLON || (BABYLON = {}));
  3786. var BABYLON;
  3787. (function (BABYLON) {
  3788. var Node = (function () {
  3789. function Node(name, scene) {
  3790. this.state = "";
  3791. this.animations = new Array();
  3792. this._childrenFlag = -1;
  3793. this._isEnabled = true;
  3794. this._isReady = true;
  3795. this._currentRenderId = -1;
  3796. this.name = name;
  3797. this.id = name;
  3798. this._scene = scene;
  3799. this._initCache();
  3800. }
  3801. Node.prototype.getScene = function () {
  3802. return this._scene;
  3803. };
  3804. Node.prototype.getEngine = function () {
  3805. return this._scene.getEngine();
  3806. };
  3807. Node.prototype.getWorldMatrix = function () {
  3808. return BABYLON.Matrix.Identity();
  3809. };
  3810. Node.prototype._initCache = function () {
  3811. this._cache = {};
  3812. this._cache.parent = undefined;
  3813. };
  3814. Node.prototype.updateCache = function (force) {
  3815. if (!force && this.isSynchronized())
  3816. return;
  3817. this._cache.parent = this.parent;
  3818. this._updateCache();
  3819. };
  3820. Node.prototype._updateCache = function (ignoreParentClass) {
  3821. };
  3822. Node.prototype._isSynchronized = function () {
  3823. return true;
  3824. };
  3825. Node.prototype.isSynchronizedWithParent = function () {
  3826. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3827. };
  3828. Node.prototype.isSynchronized = function (updateCache) {
  3829. var check = this.hasNewParent();
  3830. check = check || !this.isSynchronizedWithParent();
  3831. check = check || !this._isSynchronized();
  3832. if (updateCache)
  3833. this.updateCache(true);
  3834. return !check;
  3835. };
  3836. Node.prototype.hasNewParent = function (update) {
  3837. if (this._cache.parent === this.parent)
  3838. return false;
  3839. if (update)
  3840. this._cache.parent = this.parent;
  3841. return true;
  3842. };
  3843. Node.prototype.isReady = function () {
  3844. return this._isReady;
  3845. };
  3846. Node.prototype.isEnabled = function () {
  3847. if (!this._isEnabled) {
  3848. return false;
  3849. }
  3850. if (this.parent) {
  3851. return this.parent.isEnabled();
  3852. }
  3853. return true;
  3854. };
  3855. Node.prototype.setEnabled = function (value) {
  3856. this._isEnabled = value;
  3857. };
  3858. Node.prototype.isDescendantOf = function (ancestor) {
  3859. if (this.parent) {
  3860. if (this.parent === ancestor) {
  3861. return true;
  3862. }
  3863. return this.parent.isDescendantOf(ancestor);
  3864. }
  3865. return false;
  3866. };
  3867. Node.prototype._getDescendants = function (list, results) {
  3868. for (var index = 0; index < list.length; index++) {
  3869. var item = list[index];
  3870. if (item.isDescendantOf(this)) {
  3871. results.push(item);
  3872. }
  3873. }
  3874. };
  3875. Node.prototype.getDescendants = function () {
  3876. var results = [];
  3877. this._getDescendants(this._scene.meshes, results);
  3878. this._getDescendants(this._scene.lights, results);
  3879. this._getDescendants(this._scene.cameras, results);
  3880. return results;
  3881. };
  3882. Node.prototype._setReady = function (state) {
  3883. if (state == this._isReady) {
  3884. return;
  3885. }
  3886. if (!state) {
  3887. this._isReady = false;
  3888. return;
  3889. }
  3890. this._isReady = true;
  3891. if (this.onReady) {
  3892. this.onReady(this);
  3893. }
  3894. };
  3895. return Node;
  3896. })();
  3897. BABYLON.Node = Node;
  3898. })(BABYLON || (BABYLON = {}));
  3899. var BABYLON;
  3900. (function (BABYLON) {
  3901. var BoundingSphere = (function () {
  3902. function BoundingSphere(minimum, maximum) {
  3903. this.minimum = minimum;
  3904. this.maximum = maximum;
  3905. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3906. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3907. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3908. this.radius = distance * 0.5;
  3909. this.centerWorld = BABYLON.Vector3.Zero();
  3910. this._update(BABYLON.Matrix.Identity());
  3911. }
  3912. BoundingSphere.prototype._update = function (world) {
  3913. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3914. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3915. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3916. };
  3917. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3918. for (var i = 0; i < 6; i++) {
  3919. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3920. return false;
  3921. }
  3922. return true;
  3923. };
  3924. BoundingSphere.prototype.intersectsPoint = function (point) {
  3925. var x = this.centerWorld.x - point.x;
  3926. var y = this.centerWorld.y - point.y;
  3927. var z = this.centerWorld.z - point.z;
  3928. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3929. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3930. return false;
  3931. return true;
  3932. };
  3933. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3934. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3935. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3936. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3937. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3938. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3939. return false;
  3940. return true;
  3941. };
  3942. return BoundingSphere;
  3943. })();
  3944. BABYLON.BoundingSphere = BoundingSphere;
  3945. })(BABYLON || (BABYLON = {}));
  3946. var BABYLON;
  3947. (function (BABYLON) {
  3948. var BoundingBox = (function () {
  3949. function BoundingBox(minimum, maximum) {
  3950. this.minimum = minimum;
  3951. this.maximum = maximum;
  3952. this.vectors = new Array();
  3953. this.vectorsWorld = new Array();
  3954. this.vectors.push(this.minimum.clone());
  3955. this.vectors.push(this.maximum.clone());
  3956. this.vectors.push(this.minimum.clone());
  3957. this.vectors[2].x = this.maximum.x;
  3958. this.vectors.push(this.minimum.clone());
  3959. this.vectors[3].y = this.maximum.y;
  3960. this.vectors.push(this.minimum.clone());
  3961. this.vectors[4].z = this.maximum.z;
  3962. this.vectors.push(this.maximum.clone());
  3963. this.vectors[5].z = this.minimum.z;
  3964. this.vectors.push(this.maximum.clone());
  3965. this.vectors[6].x = this.minimum.x;
  3966. this.vectors.push(this.maximum.clone());
  3967. this.vectors[7].y = this.minimum.y;
  3968. this.center = this.maximum.add(this.minimum).scale(0.5);
  3969. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3970. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3971. for (var index = 0; index < this.vectors.length; index++) {
  3972. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3973. }
  3974. this.minimumWorld = BABYLON.Vector3.Zero();
  3975. this.maximumWorld = BABYLON.Vector3.Zero();
  3976. this._update(BABYLON.Matrix.Identity());
  3977. }
  3978. BoundingBox.prototype.getWorldMatrix = function () {
  3979. return this._worldMatrix;
  3980. };
  3981. BoundingBox.prototype._update = function (world) {
  3982. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3983. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3984. for (var index = 0; index < this.vectors.length; index++) {
  3985. var v = this.vectorsWorld[index];
  3986. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3987. if (v.x < this.minimumWorld.x)
  3988. this.minimumWorld.x = v.x;
  3989. if (v.y < this.minimumWorld.y)
  3990. this.minimumWorld.y = v.y;
  3991. if (v.z < this.minimumWorld.z)
  3992. this.minimumWorld.z = v.z;
  3993. if (v.x > this.maximumWorld.x)
  3994. this.maximumWorld.x = v.x;
  3995. if (v.y > this.maximumWorld.y)
  3996. this.maximumWorld.y = v.y;
  3997. if (v.z > this.maximumWorld.z)
  3998. this.maximumWorld.z = v.z;
  3999. }
  4000. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4001. this.center.scaleInPlace(0.5);
  4002. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4003. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4004. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4005. this._worldMatrix = world;
  4006. };
  4007. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4008. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4009. };
  4010. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4011. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4012. };
  4013. BoundingBox.prototype.intersectsPoint = function (point) {
  4014. var delta = BABYLON.Engine.Epsilon;
  4015. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4016. return false;
  4017. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4018. return false;
  4019. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4020. return false;
  4021. return true;
  4022. };
  4023. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4024. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4025. };
  4026. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4027. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4028. return false;
  4029. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4030. return false;
  4031. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4032. return false;
  4033. return true;
  4034. };
  4035. BoundingBox.Intersects = function (box0, box1) {
  4036. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4037. return false;
  4038. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4039. return false;
  4040. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4041. return false;
  4042. return true;
  4043. };
  4044. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4045. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4046. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4047. return (num <= (sphereRadius * sphereRadius));
  4048. };
  4049. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4050. for (var p = 0; p < 6; p++) {
  4051. for (var i = 0; i < 8; i++) {
  4052. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4053. return false;
  4054. }
  4055. }
  4056. }
  4057. return true;
  4058. };
  4059. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4060. for (var p = 0; p < 6; p++) {
  4061. var inCount = 8;
  4062. for (var i = 0; i < 8; i++) {
  4063. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4064. --inCount;
  4065. } else {
  4066. break;
  4067. }
  4068. }
  4069. if (inCount == 0)
  4070. return false;
  4071. }
  4072. return true;
  4073. };
  4074. return BoundingBox;
  4075. })();
  4076. BABYLON.BoundingBox = BoundingBox;
  4077. })(BABYLON || (BABYLON = {}));
  4078. var BABYLON;
  4079. (function (BABYLON) {
  4080. var computeBoxExtents = function (axis, box) {
  4081. var p = BABYLON.Vector3.Dot(box.center, axis);
  4082. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4083. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4084. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4085. var r = r0 + r1 + r2;
  4086. return {
  4087. min: p - r,
  4088. max: p + r
  4089. };
  4090. };
  4091. var extentsOverlap = function (min0, max0, min1, max1) {
  4092. return !(min0 > max1 || min1 > max0);
  4093. };
  4094. var axisOverlap = function (axis, box0, box1) {
  4095. var result0 = computeBoxExtents(axis, box0);
  4096. var result1 = computeBoxExtents(axis, box1);
  4097. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4098. };
  4099. var BoundingInfo = (function () {
  4100. function BoundingInfo(minimum, maximum) {
  4101. this.minimum = minimum;
  4102. this.maximum = maximum;
  4103. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4104. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4105. }
  4106. BoundingInfo.prototype._update = function (world) {
  4107. this.boundingBox._update(world);
  4108. this.boundingSphere._update(world);
  4109. };
  4110. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4111. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4112. return false;
  4113. return this.boundingBox.isInFrustum(frustumPlanes);
  4114. };
  4115. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4116. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4117. };
  4118. BoundingInfo.prototype._checkCollision = function (collider) {
  4119. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4120. };
  4121. BoundingInfo.prototype.intersectsPoint = function (point) {
  4122. if (!this.boundingSphere.centerWorld) {
  4123. return false;
  4124. }
  4125. if (!this.boundingSphere.intersectsPoint(point)) {
  4126. return false;
  4127. }
  4128. if (!this.boundingBox.intersectsPoint(point)) {
  4129. return false;
  4130. }
  4131. return true;
  4132. };
  4133. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4134. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4135. return false;
  4136. }
  4137. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4138. return false;
  4139. }
  4140. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4141. return false;
  4142. }
  4143. if (!precise) {
  4144. return true;
  4145. }
  4146. var box0 = this.boundingBox;
  4147. var box1 = boundingInfo.boundingBox;
  4148. if (!axisOverlap(box0.directions[0], box0, box1))
  4149. return false;
  4150. if (!axisOverlap(box0.directions[1], box0, box1))
  4151. return false;
  4152. if (!axisOverlap(box0.directions[2], box0, box1))
  4153. return false;
  4154. if (!axisOverlap(box1.directions[0], box0, box1))
  4155. return false;
  4156. if (!axisOverlap(box1.directions[1], box0, box1))
  4157. return false;
  4158. if (!axisOverlap(box1.directions[2], box0, box1))
  4159. return false;
  4160. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4161. return false;
  4162. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4163. return false;
  4164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4165. return false;
  4166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4167. return false;
  4168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4169. return false;
  4170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4171. return false;
  4172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4173. return false;
  4174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4175. return false;
  4176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4177. return false;
  4178. return true;
  4179. };
  4180. return BoundingInfo;
  4181. })();
  4182. BABYLON.BoundingInfo = BoundingInfo;
  4183. })(BABYLON || (BABYLON = {}));
  4184. var __extends = this.__extends || function (d, b) {
  4185. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4186. function __() { this.constructor = d; }
  4187. __.prototype = b.prototype;
  4188. d.prototype = new __();
  4189. };
  4190. var BABYLON;
  4191. (function (BABYLON) {
  4192. var Light = (function (_super) {
  4193. __extends(Light, _super);
  4194. function Light(name, scene) {
  4195. _super.call(this, name, scene);
  4196. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4197. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4198. this.intensity = 1.0;
  4199. this.range = Number.MAX_VALUE;
  4200. this.includedOnlyMeshes = new Array();
  4201. this.excludedMeshes = new Array();
  4202. this._excludedMeshesIds = new Array();
  4203. this._includedOnlyMeshesIds = new Array();
  4204. scene.lights.push(this);
  4205. }
  4206. Light.prototype.getShadowGenerator = function () {
  4207. return this._shadowGenerator;
  4208. };
  4209. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4210. };
  4211. Light.prototype._getWorldMatrix = function () {
  4212. return BABYLON.Matrix.Identity();
  4213. };
  4214. Light.prototype.canAffectMesh = function (mesh) {
  4215. if (!mesh) {
  4216. return true;
  4217. }
  4218. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4219. return false;
  4220. }
  4221. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4222. return false;
  4223. }
  4224. return true;
  4225. };
  4226. Light.prototype.getWorldMatrix = function () {
  4227. this._currentRenderId = this.getScene().getRenderId();
  4228. var worldMatrix = this._getWorldMatrix();
  4229. if (this.parent && this.parent.getWorldMatrix) {
  4230. if (!this._parentedWorldMatrix) {
  4231. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4232. }
  4233. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4234. return this._parentedWorldMatrix;
  4235. }
  4236. return worldMatrix;
  4237. };
  4238. Light.prototype.dispose = function () {
  4239. if (this._shadowGenerator) {
  4240. this._shadowGenerator.dispose();
  4241. this._shadowGenerator = null;
  4242. }
  4243. var index = this.getScene().lights.indexOf(this);
  4244. this.getScene().lights.splice(index, 1);
  4245. };
  4246. return Light;
  4247. })(BABYLON.Node);
  4248. BABYLON.Light = Light;
  4249. })(BABYLON || (BABYLON = {}));
  4250. var __extends = this.__extends || function (d, b) {
  4251. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4252. function __() { this.constructor = d; }
  4253. __.prototype = b.prototype;
  4254. d.prototype = new __();
  4255. };
  4256. var BABYLON;
  4257. (function (BABYLON) {
  4258. var PointLight = (function (_super) {
  4259. __extends(PointLight, _super);
  4260. function PointLight(name, position, scene) {
  4261. _super.call(this, name, scene);
  4262. this.position = position;
  4263. }
  4264. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4265. if (this.parent && this.parent.getWorldMatrix) {
  4266. if (!this._transformedPosition) {
  4267. this._transformedPosition = BABYLON.Vector3.Zero();
  4268. }
  4269. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4270. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4271. return;
  4272. }
  4273. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4274. };
  4275. PointLight.prototype.getShadowGenerator = function () {
  4276. return null;
  4277. };
  4278. PointLight.prototype._getWorldMatrix = function () {
  4279. if (!this._worldMatrix) {
  4280. this._worldMatrix = BABYLON.Matrix.Identity();
  4281. }
  4282. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4283. return this._worldMatrix;
  4284. };
  4285. return PointLight;
  4286. })(BABYLON.Light);
  4287. BABYLON.PointLight = PointLight;
  4288. })(BABYLON || (BABYLON = {}));
  4289. var __extends = this.__extends || function (d, b) {
  4290. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4291. function __() { this.constructor = d; }
  4292. __.prototype = b.prototype;
  4293. d.prototype = new __();
  4294. };
  4295. var BABYLON;
  4296. (function (BABYLON) {
  4297. var SpotLight = (function (_super) {
  4298. __extends(SpotLight, _super);
  4299. function SpotLight(name, position, direction, angle, exponent, scene) {
  4300. _super.call(this, name, scene);
  4301. this.position = position;
  4302. this.direction = direction;
  4303. this.angle = angle;
  4304. this.exponent = exponent;
  4305. }
  4306. SpotLight.prototype.setDirectionToTarget = function (target) {
  4307. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4308. return this.direction;
  4309. };
  4310. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4311. var normalizeDirection;
  4312. if (this.parent && this.parent.getWorldMatrix) {
  4313. if (!this._transformedDirection) {
  4314. this._transformedDirection = BABYLON.Vector3.Zero();
  4315. }
  4316. if (!this._transformedPosition) {
  4317. this._transformedPosition = BABYLON.Vector3.Zero();
  4318. }
  4319. var parentWorldMatrix = this.parent.getWorldMatrix();
  4320. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4321. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4322. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4323. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4324. } else {
  4325. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4326. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4327. }
  4328. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4329. };
  4330. SpotLight.prototype._getWorldMatrix = function () {
  4331. if (!this._worldMatrix) {
  4332. this._worldMatrix = BABYLON.Matrix.Identity();
  4333. }
  4334. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4335. return this._worldMatrix;
  4336. };
  4337. return SpotLight;
  4338. })(BABYLON.Light);
  4339. BABYLON.SpotLight = SpotLight;
  4340. })(BABYLON || (BABYLON = {}));
  4341. var __extends = this.__extends || function (d, b) {
  4342. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4343. function __() { this.constructor = d; }
  4344. __.prototype = b.prototype;
  4345. d.prototype = new __();
  4346. };
  4347. var BABYLON;
  4348. (function (BABYLON) {
  4349. var DirectionalLight = (function (_super) {
  4350. __extends(DirectionalLight, _super);
  4351. function DirectionalLight(name, direction, scene) {
  4352. _super.call(this, name, scene);
  4353. this.direction = direction;
  4354. this.position = direction.scale(-1);
  4355. }
  4356. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4357. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4358. return this.direction;
  4359. };
  4360. DirectionalLight.prototype._computeTransformedPosition = function () {
  4361. if (this.parent && this.parent.getWorldMatrix) {
  4362. if (!this._transformedPosition) {
  4363. this._transformedPosition = BABYLON.Vector3.Zero();
  4364. }
  4365. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4366. return true;
  4367. }
  4368. return false;
  4369. };
  4370. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4371. if (this.parent && this.parent.getWorldMatrix) {
  4372. if (!this._transformedDirection) {
  4373. this._transformedDirection = BABYLON.Vector3.Zero();
  4374. }
  4375. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4376. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4377. return;
  4378. }
  4379. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4380. };
  4381. DirectionalLight.prototype._getWorldMatrix = function () {
  4382. if (!this._worldMatrix) {
  4383. this._worldMatrix = BABYLON.Matrix.Identity();
  4384. }
  4385. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4386. return this._worldMatrix;
  4387. };
  4388. return DirectionalLight;
  4389. })(BABYLON.Light);
  4390. BABYLON.DirectionalLight = DirectionalLight;
  4391. })(BABYLON || (BABYLON = {}));
  4392. var BABYLON;
  4393. (function (BABYLON) {
  4394. var ShadowGenerator = (function () {
  4395. function ShadowGenerator(mapSize, light) {
  4396. var _this = this;
  4397. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4398. this._darkness = 0;
  4399. this._transparencyShadow = false;
  4400. this._viewMatrix = BABYLON.Matrix.Zero();
  4401. this._projectionMatrix = BABYLON.Matrix.Zero();
  4402. this._transformMatrix = BABYLON.Matrix.Zero();
  4403. this._worldViewProjection = BABYLON.Matrix.Zero();
  4404. this._light = light;
  4405. this._scene = light.getScene();
  4406. light._shadowGenerator = this;
  4407. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4408. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4409. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4410. this._shadowMap.renderParticles = false;
  4411. var renderSubMesh = function (subMesh) {
  4412. var mesh = subMesh.getRenderingMesh();
  4413. var scene = _this._scene;
  4414. var engine = scene.getEngine();
  4415. engine.setState(subMesh.getMaterial().backFaceCulling);
  4416. var batch = mesh._getInstancesRenderList(subMesh._id);
  4417. if (batch.mustReturn) {
  4418. return;
  4419. }
  4420. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4421. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4422. engine.enableEffect(_this._effect);
  4423. mesh._bind(subMesh, _this._effect, false);
  4424. var material = subMesh.getMaterial();
  4425. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4426. if (material && material.needAlphaTesting()) {
  4427. var alphaTexture = material.getAlphaTestTexture();
  4428. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4429. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4430. }
  4431. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4432. if (useBones) {
  4433. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4434. }
  4435. if (hardwareInstancedRendering) {
  4436. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4437. } else {
  4438. if (batch.renderSelf[subMesh._id]) {
  4439. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4440. mesh._draw(subMesh, true);
  4441. }
  4442. if (batch.visibleInstances[subMesh._id]) {
  4443. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4444. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4445. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4446. mesh._draw(subMesh, true);
  4447. }
  4448. }
  4449. }
  4450. } else {
  4451. _this._shadowMap.resetRefreshCounter();
  4452. }
  4453. };
  4454. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4455. var index;
  4456. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4457. renderSubMesh(opaqueSubMeshes.data[index]);
  4458. }
  4459. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4460. renderSubMesh(alphaTestSubMeshes.data[index]);
  4461. }
  4462. if (_this._transparencyShadow) {
  4463. for (index = 0; index < transparentSubMeshes.length; index++) {
  4464. renderSubMesh(transparentSubMeshes.data[index]);
  4465. }
  4466. }
  4467. };
  4468. }
  4469. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4470. get: function () {
  4471. return ShadowGenerator._FILTER_NONE;
  4472. },
  4473. enumerable: true,
  4474. configurable: true
  4475. });
  4476. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4477. get: function () {
  4478. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4479. },
  4480. enumerable: true,
  4481. configurable: true
  4482. });
  4483. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4484. get: function () {
  4485. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4486. },
  4487. enumerable: true,
  4488. configurable: true
  4489. });
  4490. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4491. get: function () {
  4492. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4493. },
  4494. set: function (value) {
  4495. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4501. get: function () {
  4502. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4503. },
  4504. set: function (value) {
  4505. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4506. },
  4507. enumerable: true,
  4508. configurable: true
  4509. });
  4510. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4511. var defines = [];
  4512. if (this.useVarianceShadowMap) {
  4513. defines.push("#define VSM");
  4514. }
  4515. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4516. var mesh = subMesh.getMesh();
  4517. var material = subMesh.getMaterial();
  4518. if (material && material.needAlphaTesting()) {
  4519. defines.push("#define ALPHATEST");
  4520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4521. attribs.push(BABYLON.VertexBuffer.UVKind);
  4522. defines.push("#define UV1");
  4523. }
  4524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4525. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4526. defines.push("#define UV2");
  4527. }
  4528. }
  4529. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4530. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4531. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4532. defines.push("#define BONES");
  4533. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4534. }
  4535. if (useInstances) {
  4536. defines.push("#define INSTANCES");
  4537. attribs.push("world0");
  4538. attribs.push("world1");
  4539. attribs.push("world2");
  4540. attribs.push("world3");
  4541. }
  4542. var join = defines.join("\n");
  4543. if (this._cachedDefines != join) {
  4544. this._cachedDefines = join;
  4545. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4546. }
  4547. return this._effect.isReady();
  4548. };
  4549. ShadowGenerator.prototype.getShadowMap = function () {
  4550. return this._shadowMap;
  4551. };
  4552. ShadowGenerator.prototype.getLight = function () {
  4553. return this._light;
  4554. };
  4555. ShadowGenerator.prototype.getTransformMatrix = function () {
  4556. var lightPosition = this._light.position;
  4557. var lightDirection = this._light.direction;
  4558. if (this._light._computeTransformedPosition()) {
  4559. lightPosition = this._light._transformedPosition;
  4560. }
  4561. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4562. this._cachedPosition = lightPosition.clone();
  4563. this._cachedDirection = lightDirection.clone();
  4564. var activeCamera = this._scene.activeCamera;
  4565. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4566. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4567. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4568. }
  4569. return this._transformMatrix;
  4570. };
  4571. ShadowGenerator.prototype.getDarkness = function () {
  4572. return this._darkness;
  4573. };
  4574. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4575. if (darkness >= 1.0)
  4576. this._darkness = 1.0;
  4577. else if (darkness <= 0.0)
  4578. this._darkness = 0.0;
  4579. else
  4580. this._darkness = darkness;
  4581. };
  4582. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4583. this._transparencyShadow = hasShadow;
  4584. };
  4585. ShadowGenerator.prototype.dispose = function () {
  4586. this._shadowMap.dispose();
  4587. };
  4588. ShadowGenerator._FILTER_NONE = 0;
  4589. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4590. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4591. return ShadowGenerator;
  4592. })();
  4593. BABYLON.ShadowGenerator = ShadowGenerator;
  4594. })(BABYLON || (BABYLON = {}));
  4595. var __extends = this.__extends || function (d, b) {
  4596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4597. function __() { this.constructor = d; }
  4598. __.prototype = b.prototype;
  4599. d.prototype = new __();
  4600. };
  4601. var BABYLON;
  4602. (function (BABYLON) {
  4603. var HemisphericLight = (function (_super) {
  4604. __extends(HemisphericLight, _super);
  4605. function HemisphericLight(name, direction, scene) {
  4606. _super.call(this, name, scene);
  4607. this.direction = direction;
  4608. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4609. }
  4610. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4611. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4612. return this.direction;
  4613. };
  4614. HemisphericLight.prototype.getShadowGenerator = function () {
  4615. return null;
  4616. };
  4617. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4618. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4619. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4620. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4621. };
  4622. HemisphericLight.prototype._getWorldMatrix = function () {
  4623. if (!this._worldMatrix) {
  4624. this._worldMatrix = BABYLON.Matrix.Identity();
  4625. }
  4626. return this._worldMatrix;
  4627. };
  4628. return HemisphericLight;
  4629. })(BABYLON.Light);
  4630. BABYLON.HemisphericLight = HemisphericLight;
  4631. })(BABYLON || (BABYLON = {}));
  4632. var BABYLON;
  4633. (function (BABYLON) {
  4634. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4635. if (boxMin.x > sphereCenter.x + sphereRadius)
  4636. return false;
  4637. if (sphereCenter.x - sphereRadius > boxMax.x)
  4638. return false;
  4639. if (boxMin.y > sphereCenter.y + sphereRadius)
  4640. return false;
  4641. if (sphereCenter.y - sphereRadius > boxMax.y)
  4642. return false;
  4643. if (boxMin.z > sphereCenter.z + sphereRadius)
  4644. return false;
  4645. if (sphereCenter.z - sphereRadius > boxMax.z)
  4646. return false;
  4647. return true;
  4648. };
  4649. var getLowestRoot = function (a, b, c, maxR) {
  4650. var determinant = b * b - 4.0 * a * c;
  4651. var result = { root: 0, found: false };
  4652. if (determinant < 0)
  4653. return result;
  4654. var sqrtD = Math.sqrt(determinant);
  4655. var r1 = (-b - sqrtD) / (2.0 * a);
  4656. var r2 = (-b + sqrtD) / (2.0 * a);
  4657. if (r1 > r2) {
  4658. var temp = r2;
  4659. r2 = r1;
  4660. r1 = temp;
  4661. }
  4662. if (r1 > 0 && r1 < maxR) {
  4663. result.root = r1;
  4664. result.found = true;
  4665. return result;
  4666. }
  4667. if (r2 > 0 && r2 < maxR) {
  4668. result.root = r2;
  4669. result.found = true;
  4670. return result;
  4671. }
  4672. return result;
  4673. };
  4674. var Collider = (function () {
  4675. function Collider() {
  4676. this.radius = new BABYLON.Vector3(1, 1, 1);
  4677. this.retry = 0;
  4678. this.basePointWorld = BABYLON.Vector3.Zero();
  4679. this.velocityWorld = BABYLON.Vector3.Zero();
  4680. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4681. this._collisionPoint = BABYLON.Vector3.Zero();
  4682. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4683. this._tempVector = BABYLON.Vector3.Zero();
  4684. this._tempVector2 = BABYLON.Vector3.Zero();
  4685. this._tempVector3 = BABYLON.Vector3.Zero();
  4686. this._tempVector4 = BABYLON.Vector3.Zero();
  4687. this._edge = BABYLON.Vector3.Zero();
  4688. this._baseToVertex = BABYLON.Vector3.Zero();
  4689. this._destinationPoint = BABYLON.Vector3.Zero();
  4690. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4691. this._displacementVector = BABYLON.Vector3.Zero();
  4692. }
  4693. Collider.prototype._initialize = function (source, dir, e) {
  4694. this.velocity = dir;
  4695. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4696. this.basePoint = source;
  4697. source.multiplyToRef(this.radius, this.basePointWorld);
  4698. dir.multiplyToRef(this.radius, this.velocityWorld);
  4699. this.velocityWorldLength = this.velocityWorld.length();
  4700. this.epsilon = e;
  4701. this.collisionFound = false;
  4702. };
  4703. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4704. pa.subtractToRef(point, this._tempVector);
  4705. pb.subtractToRef(point, this._tempVector2);
  4706. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4707. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4708. if (d < 0)
  4709. return false;
  4710. pc.subtractToRef(point, this._tempVector3);
  4711. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4712. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4713. if (d < 0)
  4714. return false;
  4715. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4716. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4717. return d >= 0;
  4718. };
  4719. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4720. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4721. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4722. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4723. return false;
  4724. }
  4725. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4726. return false;
  4727. return true;
  4728. };
  4729. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4730. var t0;
  4731. var embeddedInPlane = false;
  4732. if (!subMesh._trianglePlanes) {
  4733. subMesh._trianglePlanes = [];
  4734. }
  4735. if (!subMesh._trianglePlanes[faceIndex]) {
  4736. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4737. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4738. }
  4739. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4740. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4741. return;
  4742. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4743. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4744. if (normalDotVelocity == 0) {
  4745. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4746. return;
  4747. embeddedInPlane = true;
  4748. t0 = 0;
  4749. } else {
  4750. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4751. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4752. if (t0 > t1) {
  4753. var temp = t1;
  4754. t1 = t0;
  4755. t0 = temp;
  4756. }
  4757. if (t0 > 1.0 || t1 < 0.0)
  4758. return;
  4759. if (t0 < 0)
  4760. t0 = 0;
  4761. if (t0 > 1.0)
  4762. t0 = 1.0;
  4763. }
  4764. this._collisionPoint.copyFromFloats(0, 0, 0);
  4765. var found = false;
  4766. var t = 1.0;
  4767. if (!embeddedInPlane) {
  4768. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4769. this.velocity.scaleToRef(t0, this._tempVector);
  4770. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4771. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4772. found = true;
  4773. t = t0;
  4774. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4775. }
  4776. }
  4777. if (!found) {
  4778. var velocitySquaredLength = this.velocity.lengthSquared();
  4779. var a = velocitySquaredLength;
  4780. this.basePoint.subtractToRef(p1, this._tempVector);
  4781. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4782. var c = this._tempVector.lengthSquared() - 1.0;
  4783. var lowestRoot = getLowestRoot(a, b, c, t);
  4784. if (lowestRoot.found) {
  4785. t = lowestRoot.root;
  4786. found = true;
  4787. this._collisionPoint.copyFrom(p1);
  4788. }
  4789. this.basePoint.subtractToRef(p2, this._tempVector);
  4790. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4791. c = this._tempVector.lengthSquared() - 1.0;
  4792. lowestRoot = getLowestRoot(a, b, c, t);
  4793. if (lowestRoot.found) {
  4794. t = lowestRoot.root;
  4795. found = true;
  4796. this._collisionPoint.copyFrom(p2);
  4797. }
  4798. this.basePoint.subtractToRef(p3, this._tempVector);
  4799. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4800. c = this._tempVector.lengthSquared() - 1.0;
  4801. lowestRoot = getLowestRoot(a, b, c, t);
  4802. if (lowestRoot.found) {
  4803. t = lowestRoot.root;
  4804. found = true;
  4805. this._collisionPoint.copyFrom(p3);
  4806. }
  4807. p2.subtractToRef(p1, this._edge);
  4808. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4809. var edgeSquaredLength = this._edge.lengthSquared();
  4810. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4811. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4812. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4813. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4814. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4815. lowestRoot = getLowestRoot(a, b, c, t);
  4816. if (lowestRoot.found) {
  4817. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4818. if (f >= 0.0 && f <= 1.0) {
  4819. t = lowestRoot.root;
  4820. found = true;
  4821. this._edge.scaleInPlace(f);
  4822. p1.addToRef(this._edge, this._collisionPoint);
  4823. }
  4824. }
  4825. p3.subtractToRef(p2, this._edge);
  4826. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4827. edgeSquaredLength = this._edge.lengthSquared();
  4828. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4829. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4830. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4831. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4832. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4833. lowestRoot = getLowestRoot(a, b, c, t);
  4834. if (lowestRoot.found) {
  4835. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4836. if (f >= 0.0 && f <= 1.0) {
  4837. t = lowestRoot.root;
  4838. found = true;
  4839. this._edge.scaleInPlace(f);
  4840. p2.addToRef(this._edge, this._collisionPoint);
  4841. }
  4842. }
  4843. p1.subtractToRef(p3, this._edge);
  4844. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4845. edgeSquaredLength = this._edge.lengthSquared();
  4846. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4847. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4848. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4849. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4850. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4851. lowestRoot = getLowestRoot(a, b, c, t);
  4852. if (lowestRoot.found) {
  4853. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4854. if (f >= 0.0 && f <= 1.0) {
  4855. t = lowestRoot.root;
  4856. found = true;
  4857. this._edge.scaleInPlace(f);
  4858. p3.addToRef(this._edge, this._collisionPoint);
  4859. }
  4860. }
  4861. }
  4862. if (found) {
  4863. var distToCollision = t * this.velocity.length();
  4864. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4865. if (!this.intersectionPoint) {
  4866. this.intersectionPoint = this._collisionPoint.clone();
  4867. } else {
  4868. this.intersectionPoint.copyFrom(this._collisionPoint);
  4869. }
  4870. this.nearestDistance = distToCollision;
  4871. this.collisionFound = true;
  4872. this.collidedMesh = subMesh.getMesh();
  4873. }
  4874. }
  4875. };
  4876. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4877. for (var i = indexStart; i < indexEnd; i += 3) {
  4878. var p1 = pts[indices[i] - decal];
  4879. var p2 = pts[indices[i + 1] - decal];
  4880. var p3 = pts[indices[i + 2] - decal];
  4881. this._testTriangle(i, subMesh, p3, p2, p1);
  4882. }
  4883. };
  4884. Collider.prototype._getResponse = function (pos, vel) {
  4885. pos.addToRef(vel, this._destinationPoint);
  4886. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4887. this.basePoint.addToRef(vel, pos);
  4888. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4889. this._slidePlaneNormal.normalize();
  4890. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4891. pos.addInPlace(this._displacementVector);
  4892. this.intersectionPoint.addInPlace(this._displacementVector);
  4893. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4894. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4895. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4896. };
  4897. return Collider;
  4898. })();
  4899. BABYLON.Collider = Collider;
  4900. })(BABYLON || (BABYLON = {}));
  4901. var __extends = this.__extends || function (d, b) {
  4902. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4903. function __() { this.constructor = d; }
  4904. __.prototype = b.prototype;
  4905. d.prototype = new __();
  4906. };
  4907. var BABYLON;
  4908. (function (BABYLON) {
  4909. var Camera = (function (_super) {
  4910. __extends(Camera, _super);
  4911. function Camera(name, position, scene) {
  4912. _super.call(this, name, scene);
  4913. this.position = position;
  4914. this.upVector = BABYLON.Vector3.Up();
  4915. this.orthoLeft = null;
  4916. this.orthoRight = null;
  4917. this.orthoBottom = null;
  4918. this.orthoTop = null;
  4919. this.fov = 0.8;
  4920. this.minZ = 1.0;
  4921. this.maxZ = 10000.0;
  4922. this.inertia = 0.9;
  4923. this.mode = Camera.PERSPECTIVE_CAMERA;
  4924. this.isIntermediate = false;
  4925. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4926. this.subCameras = [];
  4927. this.layerMask = 0xFFFFFFFF;
  4928. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4929. this._projectionMatrix = new BABYLON.Matrix();
  4930. this._postProcesses = new Array();
  4931. this._postProcessesTakenIndices = [];
  4932. scene.cameras.push(this);
  4933. if (!scene.activeCamera) {
  4934. scene.activeCamera = this;
  4935. }
  4936. }
  4937. Camera.prototype._initCache = function () {
  4938. _super.prototype._initCache.call(this);
  4939. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4940. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4941. this._cache.mode = undefined;
  4942. this._cache.minZ = undefined;
  4943. this._cache.maxZ = undefined;
  4944. this._cache.fov = undefined;
  4945. this._cache.aspectRatio = undefined;
  4946. this._cache.orthoLeft = undefined;
  4947. this._cache.orthoRight = undefined;
  4948. this._cache.orthoBottom = undefined;
  4949. this._cache.orthoTop = undefined;
  4950. this._cache.renderWidth = undefined;
  4951. this._cache.renderHeight = undefined;
  4952. };
  4953. Camera.prototype._updateCache = function (ignoreParentClass) {
  4954. if (!ignoreParentClass) {
  4955. _super.prototype._updateCache.call(this);
  4956. }
  4957. var engine = this.getEngine();
  4958. this._cache.position.copyFrom(this.position);
  4959. this._cache.upVector.copyFrom(this.upVector);
  4960. this._cache.mode = this.mode;
  4961. this._cache.minZ = this.minZ;
  4962. this._cache.maxZ = this.maxZ;
  4963. this._cache.fov = this.fov;
  4964. this._cache.aspectRatio = engine.getAspectRatio(this);
  4965. this._cache.orthoLeft = this.orthoLeft;
  4966. this._cache.orthoRight = this.orthoRight;
  4967. this._cache.orthoBottom = this.orthoBottom;
  4968. this._cache.orthoTop = this.orthoTop;
  4969. this._cache.renderWidth = engine.getRenderWidth();
  4970. this._cache.renderHeight = engine.getRenderHeight();
  4971. };
  4972. Camera.prototype._updateFromScene = function () {
  4973. this.updateCache();
  4974. this._update();
  4975. };
  4976. Camera.prototype._isSynchronized = function () {
  4977. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4978. };
  4979. Camera.prototype._isSynchronizedViewMatrix = function () {
  4980. if (!_super.prototype._isSynchronized.call(this))
  4981. return false;
  4982. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4983. };
  4984. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4985. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4986. if (!check) {
  4987. return false;
  4988. }
  4989. var engine = this.getEngine();
  4990. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4991. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4992. } else {
  4993. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  4994. }
  4995. return check;
  4996. };
  4997. Camera.prototype.attachControl = function (element) {
  4998. };
  4999. Camera.prototype.detachControl = function (element) {
  5000. };
  5001. Camera.prototype._update = function () {
  5002. };
  5003. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5004. if (typeof insertAt === "undefined") { insertAt = null; }
  5005. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5006. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5007. return 0;
  5008. }
  5009. if (insertAt == null || insertAt < 0) {
  5010. this._postProcesses.push(postProcess);
  5011. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5012. return this._postProcesses.length - 1;
  5013. }
  5014. var add = 0;
  5015. if (this._postProcesses[insertAt]) {
  5016. var start = this._postProcesses.length - 1;
  5017. for (var i = start; i >= insertAt + 1; --i) {
  5018. this._postProcesses[i + 1] = this._postProcesses[i];
  5019. }
  5020. add = 1;
  5021. }
  5022. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5023. if (this._postProcessesTakenIndices[i] < insertAt) {
  5024. continue;
  5025. }
  5026. start = this._postProcessesTakenIndices.length - 1;
  5027. for (var j = start; j >= i; --j) {
  5028. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5029. }
  5030. this._postProcessesTakenIndices[i] = insertAt;
  5031. break;
  5032. }
  5033. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5034. this._postProcessesTakenIndices.push(insertAt);
  5035. }
  5036. var result = insertAt + add;
  5037. this._postProcesses[result] = postProcess;
  5038. return result;
  5039. };
  5040. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5041. if (typeof atIndices === "undefined") { atIndices = null; }
  5042. var result = [];
  5043. if (!atIndices) {
  5044. var length = this._postProcesses.length;
  5045. for (var i = 0; i < length; i++) {
  5046. if (this._postProcesses[i] !== postProcess) {
  5047. continue;
  5048. }
  5049. delete this._postProcesses[i];
  5050. var index = this._postProcessesTakenIndices.indexOf(i);
  5051. this._postProcessesTakenIndices.splice(index, 1);
  5052. }
  5053. } else {
  5054. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5055. for (i = 0; i < atIndices.length; i++) {
  5056. var foundPostProcess = this._postProcesses[atIndices[i]];
  5057. if (foundPostProcess !== postProcess) {
  5058. result.push(i);
  5059. continue;
  5060. }
  5061. delete this._postProcesses[atIndices[i]];
  5062. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5063. this._postProcessesTakenIndices.splice(index, 1);
  5064. }
  5065. }
  5066. return result;
  5067. };
  5068. Camera.prototype.getWorldMatrix = function () {
  5069. if (!this._worldMatrix) {
  5070. this._worldMatrix = BABYLON.Matrix.Identity();
  5071. }
  5072. var viewMatrix = this.getViewMatrix();
  5073. viewMatrix.invertToRef(this._worldMatrix);
  5074. return this._worldMatrix;
  5075. };
  5076. Camera.prototype._getViewMatrix = function () {
  5077. return BABYLON.Matrix.Identity();
  5078. };
  5079. Camera.prototype.getViewMatrix = function () {
  5080. this._computedViewMatrix = this._computeViewMatrix();
  5081. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5082. return this._computedViewMatrix;
  5083. }
  5084. if (!this._worldMatrix) {
  5085. this._worldMatrix = BABYLON.Matrix.Identity();
  5086. }
  5087. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5088. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5089. this._computedViewMatrix.invert();
  5090. this._currentRenderId = this.getScene().getRenderId();
  5091. return this._computedViewMatrix;
  5092. };
  5093. Camera.prototype._computeViewMatrix = function (force) {
  5094. if (!force && this._isSynchronizedViewMatrix()) {
  5095. return this._computedViewMatrix;
  5096. }
  5097. this._computedViewMatrix = this._getViewMatrix();
  5098. if (!this.parent || !this.parent.getWorldMatrix) {
  5099. this._currentRenderId = this.getScene().getRenderId();
  5100. }
  5101. return this._computedViewMatrix;
  5102. };
  5103. Camera.prototype.getProjectionMatrix = function (force) {
  5104. if (!force && this._isSynchronizedProjectionMatrix()) {
  5105. return this._projectionMatrix;
  5106. }
  5107. var engine = this.getEngine();
  5108. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5109. if (this.minZ <= 0) {
  5110. this.minZ = 0.1;
  5111. }
  5112. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5113. return this._projectionMatrix;
  5114. }
  5115. var halfWidth = engine.getRenderWidth() / 2.0;
  5116. var halfHeight = engine.getRenderHeight() / 2.0;
  5117. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5118. return this._projectionMatrix;
  5119. };
  5120. Camera.prototype.dispose = function () {
  5121. var index = this.getScene().cameras.indexOf(this);
  5122. this.getScene().cameras.splice(index, 1);
  5123. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5124. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5125. }
  5126. };
  5127. Camera.PERSPECTIVE_CAMERA = 0;
  5128. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5129. return Camera;
  5130. })(BABYLON.Node);
  5131. BABYLON.Camera = Camera;
  5132. })(BABYLON || (BABYLON = {}));
  5133. var __extends = this.__extends || function (d, b) {
  5134. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5135. function __() { this.constructor = d; }
  5136. __.prototype = b.prototype;
  5137. d.prototype = new __();
  5138. };
  5139. var BABYLON;
  5140. (function (BABYLON) {
  5141. var TargetCamera = (function (_super) {
  5142. __extends(TargetCamera, _super);
  5143. function TargetCamera(name, position, scene) {
  5144. _super.call(this, name, position, scene);
  5145. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5146. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5147. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5148. this.speed = 2.0;
  5149. this.noRotationConstraint = false;
  5150. this.lockedTarget = null;
  5151. this._currentTarget = BABYLON.Vector3.Zero();
  5152. this._viewMatrix = BABYLON.Matrix.Zero();
  5153. this._camMatrix = BABYLON.Matrix.Zero();
  5154. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5155. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5156. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5157. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5158. this._lookAtTemp = BABYLON.Matrix.Zero();
  5159. this._tempMatrix = BABYLON.Matrix.Zero();
  5160. }
  5161. TargetCamera.prototype._getLockedTargetPosition = function () {
  5162. if (!this.lockedTarget) {
  5163. return null;
  5164. }
  5165. return this.lockedTarget.position || this.lockedTarget;
  5166. };
  5167. TargetCamera.prototype._initCache = function () {
  5168. _super.prototype._initCache.call(this);
  5169. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5170. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5171. };
  5172. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5173. if (!ignoreParentClass) {
  5174. _super.prototype._updateCache.call(this);
  5175. }
  5176. var lockedTargetPosition = this._getLockedTargetPosition();
  5177. if (!lockedTargetPosition) {
  5178. this._cache.lockedTarget = null;
  5179. } else {
  5180. if (!this._cache.lockedTarget) {
  5181. this._cache.lockedTarget = lockedTargetPosition.clone();
  5182. } else {
  5183. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5184. }
  5185. }
  5186. this._cache.rotation.copyFrom(this.rotation);
  5187. };
  5188. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5189. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5190. return false;
  5191. }
  5192. var lockedTargetPosition = this._getLockedTargetPosition();
  5193. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5194. };
  5195. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5196. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5197. };
  5198. TargetCamera.prototype.setTarget = function (target) {
  5199. this.upVector.normalize();
  5200. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5201. this._camMatrix.invert();
  5202. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5203. var vDir = target.subtract(this.position);
  5204. if (vDir.x >= 0.0) {
  5205. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5206. } else {
  5207. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5208. }
  5209. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5210. if (isNaN(this.rotation.x)) {
  5211. this.rotation.x = 0;
  5212. }
  5213. if (isNaN(this.rotation.y)) {
  5214. this.rotation.y = 0;
  5215. }
  5216. if (isNaN(this.rotation.z)) {
  5217. this.rotation.z = 0;
  5218. }
  5219. };
  5220. TargetCamera.prototype.getTarget = function () {
  5221. return this._currentTarget;
  5222. };
  5223. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5224. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5225. };
  5226. TargetCamera.prototype._updatePosition = function () {
  5227. this.position.addInPlace(this.cameraDirection);
  5228. };
  5229. TargetCamera.prototype._update = function () {
  5230. var needToMove = this._decideIfNeedsToMove();
  5231. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5232. if (needToMove) {
  5233. this._updatePosition();
  5234. }
  5235. if (needToRotate) {
  5236. this.rotation.x += this.cameraRotation.x;
  5237. this.rotation.y += this.cameraRotation.y;
  5238. if (!this.noRotationConstraint) {
  5239. var limit = (Math.PI / 2) * 0.95;
  5240. if (this.rotation.x > limit)
  5241. this.rotation.x = limit;
  5242. if (this.rotation.x < -limit)
  5243. this.rotation.x = -limit;
  5244. }
  5245. }
  5246. if (needToMove) {
  5247. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5248. this.cameraDirection.x = 0;
  5249. }
  5250. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5251. this.cameraDirection.y = 0;
  5252. }
  5253. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5254. this.cameraDirection.z = 0;
  5255. }
  5256. this.cameraDirection.scaleInPlace(this.inertia);
  5257. }
  5258. if (needToRotate) {
  5259. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5260. this.cameraRotation.x = 0;
  5261. }
  5262. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5263. this.cameraRotation.y = 0;
  5264. }
  5265. this.cameraRotation.scaleInPlace(this.inertia);
  5266. }
  5267. };
  5268. TargetCamera.prototype._getViewMatrix = function () {
  5269. if (!this.lockedTarget) {
  5270. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5271. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5272. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5273. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5274. this._lookAtTemp.invert();
  5275. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5276. } else {
  5277. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5278. }
  5279. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5280. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5281. } else {
  5282. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5283. }
  5284. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5285. return this._viewMatrix;
  5286. };
  5287. return TargetCamera;
  5288. })(BABYLON.Camera);
  5289. BABYLON.TargetCamera = TargetCamera;
  5290. })(BABYLON || (BABYLON = {}));
  5291. var __extends = this.__extends || function (d, b) {
  5292. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5293. function __() { this.constructor = d; }
  5294. __.prototype = b.prototype;
  5295. d.prototype = new __();
  5296. };
  5297. var BABYLON;
  5298. (function (BABYLON) {
  5299. var FollowCamera = (function (_super) {
  5300. __extends(FollowCamera, _super);
  5301. function FollowCamera(name, position, scene) {
  5302. _super.call(this, name, position, scene);
  5303. this.radius = 12;
  5304. this.rotationOffset = 0;
  5305. this.heightOffset = 4;
  5306. this.cameraAcceleration = 0.05;
  5307. this.maxCameraSpeed = 20;
  5308. }
  5309. FollowCamera.prototype.getRadians = function (degrees) {
  5310. return degrees * Math.PI / 180;
  5311. };
  5312. FollowCamera.prototype.follow = function (cameraTarget) {
  5313. if (!cameraTarget)
  5314. return;
  5315. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5316. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5317. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5318. var dx = targetX - this.position.x;
  5319. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5320. var dz = (targetZ) - this.position.z;
  5321. var vx = dx * this.cameraAcceleration * 2;
  5322. var vy = dy * this.cameraAcceleration;
  5323. var vz = dz * this.cameraAcceleration * 2;
  5324. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5325. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5326. }
  5327. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5328. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5329. }
  5330. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5331. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5332. }
  5333. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5334. this.setTarget(cameraTarget.position);
  5335. };
  5336. FollowCamera.prototype._update = function () {
  5337. _super.prototype._update.call(this);
  5338. this.follow(this.target);
  5339. };
  5340. return FollowCamera;
  5341. })(BABYLON.TargetCamera);
  5342. BABYLON.FollowCamera = FollowCamera;
  5343. })(BABYLON || (BABYLON = {}));
  5344. var __extends = this.__extends || function (d, b) {
  5345. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5346. function __() { this.constructor = d; }
  5347. __.prototype = b.prototype;
  5348. d.prototype = new __();
  5349. };
  5350. var BABYLON;
  5351. (function (BABYLON) {
  5352. var FreeCamera = (function (_super) {
  5353. __extends(FreeCamera, _super);
  5354. function FreeCamera(name, position, scene) {
  5355. _super.call(this, name, position, scene);
  5356. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5357. this.keysUp = [38];
  5358. this.keysDown = [40];
  5359. this.keysLeft = [37];
  5360. this.keysRight = [39];
  5361. this.checkCollisions = false;
  5362. this.applyGravity = false;
  5363. this.angularSensibility = 2000.0;
  5364. this._keys = [];
  5365. this._collider = new BABYLON.Collider();
  5366. this._needMoveForGravity = true;
  5367. this._oldPosition = BABYLON.Vector3.Zero();
  5368. this._diffPosition = BABYLON.Vector3.Zero();
  5369. this._newPosition = BABYLON.Vector3.Zero();
  5370. }
  5371. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5372. var _this = this;
  5373. var previousPosition;
  5374. var engine = this.getEngine();
  5375. if (this._attachedElement) {
  5376. return;
  5377. }
  5378. this._attachedElement = element;
  5379. if (this._onMouseDown === undefined) {
  5380. this._onMouseDown = function (evt) {
  5381. previousPosition = {
  5382. x: evt.clientX,
  5383. y: evt.clientY
  5384. };
  5385. if (!noPreventDefault) {
  5386. evt.preventDefault();
  5387. }
  5388. };
  5389. this._onMouseUp = function (evt) {
  5390. previousPosition = null;
  5391. if (!noPreventDefault) {
  5392. evt.preventDefault();
  5393. }
  5394. };
  5395. this._onMouseOut = function (evt) {
  5396. previousPosition = null;
  5397. _this._keys = [];
  5398. if (!noPreventDefault) {
  5399. evt.preventDefault();
  5400. }
  5401. };
  5402. this._onMouseMove = function (evt) {
  5403. if (!previousPosition && !engine.isPointerLock) {
  5404. return;
  5405. }
  5406. var offsetX;
  5407. var offsetY;
  5408. if (!engine.isPointerLock) {
  5409. offsetX = evt.clientX - previousPosition.x;
  5410. offsetY = evt.clientY - previousPosition.y;
  5411. } else {
  5412. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5413. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5414. }
  5415. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5416. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5417. previousPosition = {
  5418. x: evt.clientX,
  5419. y: evt.clientY
  5420. };
  5421. if (!noPreventDefault) {
  5422. evt.preventDefault();
  5423. }
  5424. };
  5425. this._onKeyDown = function (evt) {
  5426. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5427. var index = _this._keys.indexOf(evt.keyCode);
  5428. if (index === -1) {
  5429. _this._keys.push(evt.keyCode);
  5430. }
  5431. if (!noPreventDefault) {
  5432. evt.preventDefault();
  5433. }
  5434. }
  5435. };
  5436. this._onKeyUp = function (evt) {
  5437. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5438. var index = _this._keys.indexOf(evt.keyCode);
  5439. if (index >= 0) {
  5440. _this._keys.splice(index, 1);
  5441. }
  5442. if (!noPreventDefault) {
  5443. evt.preventDefault();
  5444. }
  5445. }
  5446. };
  5447. this._onLostFocus = function () {
  5448. _this._keys = [];
  5449. };
  5450. this._reset = function () {
  5451. _this._keys = [];
  5452. previousPosition = null;
  5453. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5454. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5455. };
  5456. }
  5457. element.addEventListener("mousedown", this._onMouseDown, false);
  5458. element.addEventListener("mouseup", this._onMouseUp, false);
  5459. element.addEventListener("mouseout", this._onMouseOut, false);
  5460. element.addEventListener("mousemove", this._onMouseMove, false);
  5461. BABYLON.Tools.RegisterTopRootEvents([
  5462. { name: "keydown", handler: this._onKeyDown },
  5463. { name: "keyup", handler: this._onKeyUp },
  5464. { name: "blur", handler: this._onLostFocus }
  5465. ]);
  5466. };
  5467. FreeCamera.prototype.detachControl = function (element) {
  5468. if (this._attachedElement != element) {
  5469. return;
  5470. }
  5471. element.removeEventListener("mousedown", this._onMouseDown);
  5472. element.removeEventListener("mouseup", this._onMouseUp);
  5473. element.removeEventListener("mouseout", this._onMouseOut);
  5474. element.removeEventListener("mousemove", this._onMouseMove);
  5475. BABYLON.Tools.UnregisterTopRootEvents([
  5476. { name: "keydown", handler: this._onKeyDown },
  5477. { name: "keyup", handler: this._onKeyUp },
  5478. { name: "blur", handler: this._onLostFocus }
  5479. ]);
  5480. this._attachedElement = null;
  5481. if (this._reset) {
  5482. this._reset();
  5483. }
  5484. };
  5485. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5486. var globalPosition;
  5487. if (this.parent) {
  5488. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5489. } else {
  5490. globalPosition = this.position;
  5491. }
  5492. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5493. this._collider.radius = this.ellipsoid;
  5494. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5495. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5496. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5497. this.position.addInPlace(this._diffPosition);
  5498. if (this.onCollide) {
  5499. this.onCollide(this._collider.collidedMesh);
  5500. }
  5501. }
  5502. };
  5503. FreeCamera.prototype._checkInputs = function () {
  5504. if (!this._localDirection) {
  5505. this._localDirection = BABYLON.Vector3.Zero();
  5506. this._transformedDirection = BABYLON.Vector3.Zero();
  5507. }
  5508. for (var index = 0; index < this._keys.length; index++) {
  5509. var keyCode = this._keys[index];
  5510. var speed = this._computeLocalCameraSpeed();
  5511. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5512. this._localDirection.copyFromFloats(-speed, 0, 0);
  5513. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5514. this._localDirection.copyFromFloats(0, 0, speed);
  5515. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5516. this._localDirection.copyFromFloats(speed, 0, 0);
  5517. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5518. this._localDirection.copyFromFloats(0, 0, -speed);
  5519. }
  5520. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5521. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5522. this.cameraDirection.addInPlace(this._transformedDirection);
  5523. }
  5524. };
  5525. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5526. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5527. };
  5528. FreeCamera.prototype._updatePosition = function () {
  5529. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5530. this._collideWithWorld(this.cameraDirection);
  5531. if (this.applyGravity) {
  5532. var oldPosition = this.position;
  5533. this._collideWithWorld(this.getScene().gravity);
  5534. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5535. }
  5536. } else {
  5537. this.position.addInPlace(this.cameraDirection);
  5538. }
  5539. };
  5540. FreeCamera.prototype._update = function () {
  5541. this._checkInputs();
  5542. _super.prototype._update.call(this);
  5543. };
  5544. return FreeCamera;
  5545. })(BABYLON.TargetCamera);
  5546. BABYLON.FreeCamera = FreeCamera;
  5547. })(BABYLON || (BABYLON = {}));
  5548. var __extends = this.__extends || function (d, b) {
  5549. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5550. function __() { this.constructor = d; }
  5551. __.prototype = b.prototype;
  5552. d.prototype = new __();
  5553. };
  5554. var BABYLON;
  5555. (function (BABYLON) {
  5556. var TouchCamera = (function (_super) {
  5557. __extends(TouchCamera, _super);
  5558. function TouchCamera(name, position, scene) {
  5559. _super.call(this, name, position, scene);
  5560. this._offsetX = null;
  5561. this._offsetY = null;
  5562. this._pointerCount = 0;
  5563. this._pointerPressed = [];
  5564. this.angularSensibility = 200000.0;
  5565. this.moveSensibility = 500.0;
  5566. }
  5567. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5568. var _this = this;
  5569. var previousPosition;
  5570. if (this._attachedCanvas) {
  5571. return;
  5572. }
  5573. this._attachedCanvas = canvas;
  5574. if (this._onPointerDown === undefined) {
  5575. this._onPointerDown = function (evt) {
  5576. if (!noPreventDefault) {
  5577. evt.preventDefault();
  5578. }
  5579. _this._pointerPressed.push(evt.pointerId);
  5580. if (_this._pointerPressed.length !== 1) {
  5581. return;
  5582. }
  5583. previousPosition = {
  5584. x: evt.clientX,
  5585. y: evt.clientY
  5586. };
  5587. };
  5588. this._onPointerUp = function (evt) {
  5589. if (!noPreventDefault) {
  5590. evt.preventDefault();
  5591. }
  5592. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5593. if (index === -1) {
  5594. return;
  5595. }
  5596. _this._pointerPressed.splice(index, 1);
  5597. if (index != 0) {
  5598. return;
  5599. }
  5600. previousPosition = null;
  5601. _this._offsetX = null;
  5602. _this._offsetY = null;
  5603. };
  5604. this._onPointerMove = function (evt) {
  5605. if (!noPreventDefault) {
  5606. evt.preventDefault();
  5607. }
  5608. if (!previousPosition) {
  5609. return;
  5610. }
  5611. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5612. if (index != 0) {
  5613. return;
  5614. }
  5615. _this._offsetX = evt.clientX - previousPosition.x;
  5616. _this._offsetY = -(evt.clientY - previousPosition.y);
  5617. };
  5618. this._onLostFocus = function () {
  5619. _this._offsetX = null;
  5620. _this._offsetY = null;
  5621. };
  5622. }
  5623. canvas.addEventListener("pointerdown", this._onPointerDown);
  5624. canvas.addEventListener("pointerup", this._onPointerUp);
  5625. canvas.addEventListener("pointerout", this._onPointerUp);
  5626. canvas.addEventListener("pointermove", this._onPointerMove);
  5627. BABYLON.Tools.RegisterTopRootEvents([
  5628. { name: "blur", handler: this._onLostFocus }
  5629. ]);
  5630. };
  5631. TouchCamera.prototype.detachControl = function (canvas) {
  5632. if (this._attachedCanvas != canvas) {
  5633. return;
  5634. }
  5635. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5636. canvas.removeEventListener("pointerup", this._onPointerUp);
  5637. canvas.removeEventListener("pointerout", this._onPointerUp);
  5638. canvas.removeEventListener("pointermove", this._onPointerMove);
  5639. BABYLON.Tools.UnregisterTopRootEvents([
  5640. { name: "blur", handler: this._onLostFocus }
  5641. ]);
  5642. this._attachedCanvas = null;
  5643. };
  5644. TouchCamera.prototype._checkInputs = function () {
  5645. if (!this._offsetX) {
  5646. return;
  5647. }
  5648. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5649. if (this._pointerPressed.length > 1) {
  5650. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5651. } else {
  5652. var speed = this._computeLocalCameraSpeed();
  5653. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5654. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5655. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5656. }
  5657. };
  5658. return TouchCamera;
  5659. })(BABYLON.FreeCamera);
  5660. BABYLON.TouchCamera = TouchCamera;
  5661. })(BABYLON || (BABYLON = {}));
  5662. var __extends = this.__extends || function (d, b) {
  5663. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5664. function __() { this.constructor = d; }
  5665. __.prototype = b.prototype;
  5666. d.prototype = new __();
  5667. };
  5668. var BABYLON;
  5669. (function (BABYLON) {
  5670. var DeviceOrientationCamera = (function (_super) {
  5671. __extends(DeviceOrientationCamera, _super);
  5672. function DeviceOrientationCamera(name, position, scene) {
  5673. var _this = this;
  5674. _super.call(this, name, position, scene);
  5675. this._offsetX = null;
  5676. this._offsetY = null;
  5677. this._orientationGamma = 0;
  5678. this._orientationBeta = 0;
  5679. this._initialOrientationGamma = 0;
  5680. this._initialOrientationBeta = 0;
  5681. this.angularSensibility = 10000.0;
  5682. this.moveSensibility = 50.0;
  5683. window.addEventListener("resize", function () {
  5684. _this._initialOrientationGamma = null;
  5685. }, false);
  5686. }
  5687. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5688. var _this = this;
  5689. if (this._attachedCanvas) {
  5690. return;
  5691. }
  5692. this._attachedCanvas = canvas;
  5693. if (!this._orientationChanged) {
  5694. this._orientationChanged = function (evt) {
  5695. if (!_this._initialOrientationGamma) {
  5696. _this._initialOrientationGamma = evt.gamma;
  5697. _this._initialOrientationBeta = evt.beta;
  5698. }
  5699. _this._orientationGamma = evt.gamma;
  5700. _this._orientationBeta = evt.beta;
  5701. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5702. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5703. };
  5704. }
  5705. window.addEventListener("deviceorientation", this._orientationChanged);
  5706. };
  5707. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5708. if (this._attachedCanvas != canvas) {
  5709. return;
  5710. }
  5711. window.removeEventListener("deviceorientation", this._orientationChanged);
  5712. this._attachedCanvas = null;
  5713. this._orientationGamma = 0;
  5714. this._orientationBeta = 0;
  5715. this._initialOrientationGamma = 0;
  5716. this._initialOrientationBeta = 0;
  5717. };
  5718. DeviceOrientationCamera.prototype._checkInputs = function () {
  5719. if (!this._offsetX) {
  5720. return;
  5721. }
  5722. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5723. var speed = this._computeLocalCameraSpeed();
  5724. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5725. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5726. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5727. };
  5728. return DeviceOrientationCamera;
  5729. })(BABYLON.FreeCamera);
  5730. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5731. })(BABYLON || (BABYLON = {}));
  5732. var __extends = this.__extends || function (d, b) {
  5733. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5734. function __() { this.constructor = d; }
  5735. __.prototype = b.prototype;
  5736. d.prototype = new __();
  5737. };
  5738. var BABYLON;
  5739. (function (BABYLON) {
  5740. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5741. var ArcRotateCamera = (function (_super) {
  5742. __extends(ArcRotateCamera, _super);
  5743. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5744. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5745. this.alpha = alpha;
  5746. this.beta = beta;
  5747. this.radius = radius;
  5748. this.target = target;
  5749. this.inertialAlphaOffset = 0;
  5750. this.inertialBetaOffset = 0;
  5751. this.inertialRadiusOffset = 0;
  5752. this.lowerAlphaLimit = null;
  5753. this.upperAlphaLimit = null;
  5754. this.lowerBetaLimit = 0.01;
  5755. this.upperBetaLimit = Math.PI;
  5756. this.lowerRadiusLimit = null;
  5757. this.upperRadiusLimit = null;
  5758. this.angularSensibility = 1000.0;
  5759. this.wheelPrecision = 3.0;
  5760. this.keysUp = [38];
  5761. this.keysDown = [40];
  5762. this.keysLeft = [37];
  5763. this.keysRight = [39];
  5764. this.zoomOnFactor = 1;
  5765. this.targetScreenOffset = BABYLON.Vector2.Zero();
  5766. this._keys = [];
  5767. this._viewMatrix = new BABYLON.Matrix();
  5768. this.checkCollisions = false;
  5769. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5770. this._collider = new BABYLON.Collider();
  5771. this._previousPosition = BABYLON.Vector3.Zero();
  5772. this._collisionVelocity = BABYLON.Vector3.Zero();
  5773. this._newPosition = BABYLON.Vector3.Zero();
  5774. this.pinchPrecision = 20;
  5775. this.getViewMatrix();
  5776. }
  5777. ArcRotateCamera.prototype._getTargetPosition = function () {
  5778. return this.target.position || this.target;
  5779. };
  5780. ArcRotateCamera.prototype._initCache = function () {
  5781. _super.prototype._initCache.call(this);
  5782. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5783. this._cache.alpha = undefined;
  5784. this._cache.beta = undefined;
  5785. this._cache.radius = undefined;
  5786. this._cache.targetScreenOffset = undefined;
  5787. };
  5788. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5789. if (!ignoreParentClass) {
  5790. _super.prototype._updateCache.call(this);
  5791. }
  5792. this._cache.target.copyFrom(this._getTargetPosition());
  5793. this._cache.alpha = this.alpha;
  5794. this._cache.beta = this.beta;
  5795. this._cache.radius = this.radius;
  5796. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  5797. };
  5798. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5799. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5800. return false;
  5801. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  5802. };
  5803. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5804. var _this = this;
  5805. var previousPosition;
  5806. var pointerId;
  5807. var pinchStarted = false;
  5808. var pinchPointX1, pinchPointX2;
  5809. if (this._attachedElement) {
  5810. return;
  5811. }
  5812. this._attachedElement = element;
  5813. var engine = this.getEngine();
  5814. if (this._onPointerDown === undefined) {
  5815. this._onPointerDown = function (evt) {
  5816. if (pointerId) {
  5817. return;
  5818. }
  5819. pointerId = evt.pointerId;
  5820. previousPosition = {
  5821. x: evt.clientX,
  5822. y: evt.clientY
  5823. };
  5824. if (!noPreventDefault) {
  5825. evt.preventDefault();
  5826. }
  5827. };
  5828. this._onPointerUp = function (evt) {
  5829. previousPosition = null;
  5830. pointerId = null;
  5831. if (!noPreventDefault) {
  5832. evt.preventDefault();
  5833. }
  5834. };
  5835. this._onPointerMove = function (evt) {
  5836. if (!previousPosition) {
  5837. return;
  5838. }
  5839. if (pointerId !== evt.pointerId) {
  5840. return;
  5841. }
  5842. if (pinchStarted) {
  5843. return;
  5844. }
  5845. var offsetX = evt.clientX - previousPosition.x;
  5846. var offsetY = evt.clientY - previousPosition.y;
  5847. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5848. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5849. previousPosition = {
  5850. x: evt.clientX,
  5851. y: evt.clientY
  5852. };
  5853. if (!noPreventDefault) {
  5854. evt.preventDefault();
  5855. }
  5856. };
  5857. this._onMouseMove = function (evt) {
  5858. if (!engine.isPointerLock) {
  5859. return;
  5860. }
  5861. if (pinchStarted) {
  5862. return;
  5863. }
  5864. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5865. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5866. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5867. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5868. if (!noPreventDefault) {
  5869. evt.preventDefault();
  5870. }
  5871. };
  5872. this._wheel = function (event) {
  5873. var delta = 0;
  5874. if (event.wheelDelta) {
  5875. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5876. } else if (event.detail) {
  5877. delta = -event.detail / _this.wheelPrecision;
  5878. }
  5879. if (delta)
  5880. _this.inertialRadiusOffset += delta;
  5881. if (event.preventDefault) {
  5882. if (!noPreventDefault) {
  5883. event.preventDefault();
  5884. }
  5885. }
  5886. };
  5887. this._onKeyDown = function (evt) {
  5888. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5889. var index = _this._keys.indexOf(evt.keyCode);
  5890. if (index === -1) {
  5891. _this._keys.push(evt.keyCode);
  5892. }
  5893. if (evt.preventDefault) {
  5894. if (!noPreventDefault) {
  5895. evt.preventDefault();
  5896. }
  5897. }
  5898. }
  5899. };
  5900. this._onKeyUp = function (evt) {
  5901. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5902. var index = _this._keys.indexOf(evt.keyCode);
  5903. if (index >= 0) {
  5904. _this._keys.splice(index, 1);
  5905. }
  5906. if (evt.preventDefault) {
  5907. if (!noPreventDefault) {
  5908. evt.preventDefault();
  5909. }
  5910. }
  5911. }
  5912. };
  5913. this._onLostFocus = function () {
  5914. _this._keys = [];
  5915. pointerId = null;
  5916. };
  5917. this._onGestureStart = function (e) {
  5918. if (window.MSGesture === undefined) {
  5919. return;
  5920. }
  5921. if (!_this._MSGestureHandler) {
  5922. _this._MSGestureHandler = new MSGesture();
  5923. _this._MSGestureHandler.target = element;
  5924. }
  5925. _this._MSGestureHandler.addPointer(e.pointerId);
  5926. };
  5927. this._onGesture = function (e) {
  5928. _this.radius *= e.scale;
  5929. if (e.preventDefault) {
  5930. if (!noPreventDefault) {
  5931. e.stopPropagation();
  5932. e.preventDefault();
  5933. }
  5934. }
  5935. };
  5936. this._reset = function () {
  5937. _this._keys = [];
  5938. _this.inertialAlphaOffset = 0;
  5939. _this.inertialBetaOffset = 0;
  5940. _this.inertialRadiusOffset = 0;
  5941. previousPosition = null;
  5942. pointerId = null;
  5943. };
  5944. this._touchStart = function (event) {
  5945. if (event.touches.length == 2) {
  5946. pinchStarted = true;
  5947. _this._pinchStart(event);
  5948. }
  5949. };
  5950. this._touchMove = function (event) {
  5951. if (pinchStarted) {
  5952. _this._pinchMove(event);
  5953. }
  5954. };
  5955. this._touchEnd = function (event) {
  5956. if (pinchStarted) {
  5957. _this._pinchEnd(event);
  5958. }
  5959. };
  5960. this._pinchStart = function (event) {
  5961. pinchPointX1 = event.touches[0].clientX;
  5962. pinchPointX2 = event.touches[1].clientX;
  5963. pinchStarted = true;
  5964. };
  5965. this._pinchMove = function (event) {
  5966. var delta = 0;
  5967. var direction = 1;
  5968. var distanceXOrigine, distanceXNow;
  5969. if (event.touches.length != 2)
  5970. return;
  5971. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5972. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5973. if (distanceXNow < distanceXOrigine) {
  5974. direction = -1;
  5975. }
  5976. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5977. _this.inertialRadiusOffset += delta;
  5978. pinchPointX1 = event.touches[0].clientX;
  5979. pinchPointX2 = event.touches[1].clientX;
  5980. };
  5981. this._pinchEnd = function (event) {
  5982. pinchStarted = false;
  5983. };
  5984. }
  5985. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5986. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5987. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5988. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5989. element.addEventListener("mousemove", this._onMouseMove, false);
  5990. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5991. element.addEventListener("MSGestureChange", this._onGesture, false);
  5992. element.addEventListener('mousewheel', this._wheel, false);
  5993. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5994. element.addEventListener('touchstart', this._touchStart, false);
  5995. element.addEventListener('touchmove', this._touchMove, false);
  5996. element.addEventListener('touchend', this._touchEnd, false);
  5997. BABYLON.Tools.RegisterTopRootEvents([
  5998. { name: "keydown", handler: this._onKeyDown },
  5999. { name: "keyup", handler: this._onKeyUp },
  6000. { name: "blur", handler: this._onLostFocus }
  6001. ]);
  6002. };
  6003. ArcRotateCamera.prototype.detachControl = function (element) {
  6004. if (this._attachedElement != element) {
  6005. return;
  6006. }
  6007. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6008. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6009. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6010. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6011. element.removeEventListener("mousemove", this._onMouseMove);
  6012. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6013. element.removeEventListener("MSGestureChange", this._onGesture);
  6014. element.removeEventListener('mousewheel', this._wheel);
  6015. element.removeEventListener('DOMMouseScroll', this._wheel);
  6016. element.removeEventListener('touchstart', this._touchStart);
  6017. element.removeEventListener('touchmove', this._touchMove);
  6018. element.removeEventListener('touchend', this._touchEnd);
  6019. BABYLON.Tools.UnregisterTopRootEvents([
  6020. { name: "keydown", handler: this._onKeyDown },
  6021. { name: "keyup", handler: this._onKeyUp },
  6022. { name: "blur", handler: this._onLostFocus }
  6023. ]);
  6024. this._MSGestureHandler = null;
  6025. this._attachedElement = null;
  6026. if (this._reset) {
  6027. this._reset();
  6028. }
  6029. };
  6030. ArcRotateCamera.prototype._update = function () {
  6031. for (var index = 0; index < this._keys.length; index++) {
  6032. var keyCode = this._keys[index];
  6033. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6034. this.inertialAlphaOffset -= 0.01;
  6035. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6036. this.inertialBetaOffset -= 0.01;
  6037. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6038. this.inertialAlphaOffset += 0.01;
  6039. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6040. this.inertialBetaOffset += 0.01;
  6041. }
  6042. }
  6043. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6044. this.alpha += this.inertialAlphaOffset;
  6045. this.beta += this.inertialBetaOffset;
  6046. this.radius -= this.inertialRadiusOffset;
  6047. this.inertialAlphaOffset *= this.inertia;
  6048. this.inertialBetaOffset *= this.inertia;
  6049. this.inertialRadiusOffset *= this.inertia;
  6050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6051. this.inertialAlphaOffset = 0;
  6052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6053. this.inertialBetaOffset = 0;
  6054. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6055. this.inertialRadiusOffset = 0;
  6056. }
  6057. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6058. this.alpha = this.lowerAlphaLimit;
  6059. }
  6060. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6061. this.alpha = this.upperAlphaLimit;
  6062. }
  6063. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6064. this.beta = this.lowerBetaLimit;
  6065. }
  6066. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6067. this.beta = this.upperBetaLimit;
  6068. }
  6069. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6070. this.radius = this.lowerRadiusLimit;
  6071. }
  6072. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6073. this.radius = this.upperRadiusLimit;
  6074. }
  6075. };
  6076. ArcRotateCamera.prototype.setPosition = function (position) {
  6077. var radiusv3 = position.subtract(this._getTargetPosition());
  6078. this.radius = radiusv3.length();
  6079. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6080. if (radiusv3.z < 0) {
  6081. this.alpha = 2 * Math.PI - this.alpha;
  6082. }
  6083. this.beta = Math.acos(radiusv3.y / this.radius);
  6084. };
  6085. ArcRotateCamera.prototype._getViewMatrix = function () {
  6086. var cosa = Math.cos(this.alpha);
  6087. var sina = Math.sin(this.alpha);
  6088. var cosb = Math.cos(this.beta);
  6089. var sinb = Math.sin(this.beta);
  6090. var target = this._getTargetPosition();
  6091. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6092. if (this.checkCollisions) {
  6093. this._collider.radius = this.collisionRadius;
  6094. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6095. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6096. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6097. this.position.copyFrom(this._previousPosition);
  6098. this.alpha = this._previousAlpha;
  6099. this.beta = this._previousBeta;
  6100. this.radius = this._previousRadius;
  6101. if (this.onCollide) {
  6102. this.onCollide(this._collider.collidedMesh);
  6103. }
  6104. }
  6105. }
  6106. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6107. this._previousAlpha = this.alpha;
  6108. this._previousBeta = this.beta;
  6109. this._previousRadius = this.radius;
  6110. this._previousPosition.copyFrom(this.position);
  6111. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6112. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6113. return this._viewMatrix;
  6114. };
  6115. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6116. meshes = meshes || this.getScene().meshes;
  6117. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6118. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6119. this.radius = distance * this.zoomOnFactor;
  6120. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6121. };
  6122. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6123. var meshesOrMinMaxVector;
  6124. var distance;
  6125. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6126. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6127. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6128. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6129. } else {
  6130. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6131. distance = meshesOrMinMaxVectorAndDistance.distance;
  6132. }
  6133. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6134. this.maxZ = distance * 2;
  6135. };
  6136. return ArcRotateCamera;
  6137. })(BABYLON.Camera);
  6138. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6139. })(BABYLON || (BABYLON = {}));
  6140. var BABYLON;
  6141. (function (BABYLON) {
  6142. var Scene = (function () {
  6143. function Scene(engine) {
  6144. this.autoClear = true;
  6145. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6146. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6147. this.forceWireframe = false;
  6148. this.cameraToUseForPointers = null;
  6149. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6150. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6151. this.fogDensity = 0.1;
  6152. this.fogStart = 0;
  6153. this.fogEnd = 1000.0;
  6154. this.shadowsEnabled = true;
  6155. this.lightsEnabled = true;
  6156. this.lights = new Array();
  6157. this.cameras = new Array();
  6158. this.activeCameras = new Array();
  6159. this.meshes = new Array();
  6160. this._geometries = new Array();
  6161. this.materials = new Array();
  6162. this.multiMaterials = new Array();
  6163. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6164. this.texturesEnabled = true;
  6165. this.textures = new Array();
  6166. this.particlesEnabled = true;
  6167. this.particleSystems = new Array();
  6168. this.spriteManagers = new Array();
  6169. this.layers = new Array();
  6170. this.skeletons = new Array();
  6171. this.lensFlaresEnabled = true;
  6172. this.lensFlareSystems = new Array();
  6173. this.collisionsEnabled = true;
  6174. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6175. this.postProcessesEnabled = true;
  6176. this.renderTargetsEnabled = true;
  6177. this.customRenderTargets = new Array();
  6178. this.importedMeshesFiles = new Array();
  6179. this._actionManagers = new Array();
  6180. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6181. this.proceduralTexturesEnabled = true;
  6182. this._proceduralTextures = new Array();
  6183. this._totalVertices = 0;
  6184. this._activeVertices = 0;
  6185. this._activeParticles = 0;
  6186. this._lastFrameDuration = 0;
  6187. this._evaluateActiveMeshesDuration = 0;
  6188. this._renderTargetsDuration = 0;
  6189. this._particlesDuration = 0;
  6190. this._renderDuration = 0;
  6191. this._spritesDuration = 0;
  6192. this._animationRatio = 0;
  6193. this._renderId = 0;
  6194. this._executeWhenReadyTimeoutId = -1;
  6195. this._toBeDisposed = new BABYLON.SmartArray(256);
  6196. this._onReadyCallbacks = new Array();
  6197. this._pendingData = [];
  6198. this._onBeforeRenderCallbacks = new Array();
  6199. this._activeMeshes = new BABYLON.SmartArray(256);
  6200. this._processedMaterials = new BABYLON.SmartArray(256);
  6201. this._renderTargets = new BABYLON.SmartArray(256);
  6202. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6203. this._activeSkeletons = new BABYLON.SmartArray(32);
  6204. this._activeAnimatables = new Array();
  6205. this._transformMatrix = BABYLON.Matrix.Zero();
  6206. this._scaledPosition = BABYLON.Vector3.Zero();
  6207. this._scaledVelocity = BABYLON.Vector3.Zero();
  6208. this._engine = engine;
  6209. engine.scenes.push(this);
  6210. this._renderingManager = new BABYLON.RenderingManager(this);
  6211. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6212. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6213. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6214. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6215. this.attachControl();
  6216. }
  6217. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6218. get: function () {
  6219. return this._meshUnderPointer;
  6220. },
  6221. enumerable: true,
  6222. configurable: true
  6223. });
  6224. Object.defineProperty(Scene.prototype, "pointerX", {
  6225. get: function () {
  6226. return this._pointerX;
  6227. },
  6228. enumerable: true,
  6229. configurable: true
  6230. });
  6231. Object.defineProperty(Scene.prototype, "pointerY", {
  6232. get: function () {
  6233. return this._pointerY;
  6234. },
  6235. enumerable: true,
  6236. configurable: true
  6237. });
  6238. Scene.prototype.getBoundingBoxRenderer = function () {
  6239. return this._boundingBoxRenderer;
  6240. };
  6241. Scene.prototype.getOutlineRenderer = function () {
  6242. return this._outlineRenderer;
  6243. };
  6244. Scene.prototype.getEngine = function () {
  6245. return this._engine;
  6246. };
  6247. Scene.prototype.getTotalVertices = function () {
  6248. return this._totalVertices;
  6249. };
  6250. Scene.prototype.getActiveVertices = function () {
  6251. return this._activeVertices;
  6252. };
  6253. Scene.prototype.getActiveParticles = function () {
  6254. return this._activeParticles;
  6255. };
  6256. Scene.prototype.getLastFrameDuration = function () {
  6257. return this._lastFrameDuration;
  6258. };
  6259. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6260. return this._evaluateActiveMeshesDuration;
  6261. };
  6262. Scene.prototype.getActiveMeshes = function () {
  6263. return this._activeMeshes;
  6264. };
  6265. Scene.prototype.getRenderTargetsDuration = function () {
  6266. return this._renderTargetsDuration;
  6267. };
  6268. Scene.prototype.getRenderDuration = function () {
  6269. return this._renderDuration;
  6270. };
  6271. Scene.prototype.getParticlesDuration = function () {
  6272. return this._particlesDuration;
  6273. };
  6274. Scene.prototype.getSpritesDuration = function () {
  6275. return this._spritesDuration;
  6276. };
  6277. Scene.prototype.getAnimationRatio = function () {
  6278. return this._animationRatio;
  6279. };
  6280. Scene.prototype.getRenderId = function () {
  6281. return this._renderId;
  6282. };
  6283. Scene.prototype._updatePointerPosition = function (evt) {
  6284. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6285. this._pointerX = evt.clientX - canvasRect.left;
  6286. this._pointerY = evt.clientY - canvasRect.top;
  6287. if (this.cameraToUseForPointers) {
  6288. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6289. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6290. }
  6291. };
  6292. Scene.prototype.attachControl = function () {
  6293. var _this = this;
  6294. this._onPointerMove = function (evt) {
  6295. var canvas = _this._engine.getRenderingCanvas();
  6296. _this._updatePointerPosition(evt);
  6297. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6298. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6299. }, false, _this.cameraToUseForPointers);
  6300. if (pickResult.hit) {
  6301. _this._meshUnderPointer = pickResult.pickedMesh;
  6302. _this.setPointerOverMesh(pickResult.pickedMesh);
  6303. canvas.style.cursor = "pointer";
  6304. } else {
  6305. _this.setPointerOverMesh(null);
  6306. canvas.style.cursor = "";
  6307. _this._meshUnderPointer = null;
  6308. }
  6309. };
  6310. this._onPointerDown = function (evt) {
  6311. var predicate = null;
  6312. if (!_this.onPointerDown) {
  6313. predicate = function (mesh) {
  6314. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6315. };
  6316. }
  6317. _this._updatePointerPosition(evt);
  6318. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6319. if (pickResult.hit) {
  6320. if (pickResult.pickedMesh.actionManager) {
  6321. switch (evt.button) {
  6322. case 0:
  6323. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6324. break;
  6325. case 1:
  6326. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6327. break;
  6328. case 2:
  6329. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6330. break;
  6331. }
  6332. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6333. }
  6334. }
  6335. if (_this.onPointerDown) {
  6336. _this.onPointerDown(evt, pickResult);
  6337. }
  6338. };
  6339. this._onKeyDown = function (evt) {
  6340. if (_this.actionManager) {
  6341. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6342. }
  6343. };
  6344. this._onKeyUp = function (evt) {
  6345. if (_this.actionManager) {
  6346. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6347. }
  6348. };
  6349. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6350. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6351. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6352. window.addEventListener("keydown", this._onKeyDown, false);
  6353. window.addEventListener("keyup", this._onKeyUp, false);
  6354. };
  6355. Scene.prototype.detachControl = function () {
  6356. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6357. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6358. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6359. window.removeEventListener("keydown", this._onKeyDown);
  6360. window.removeEventListener("keyup", this._onKeyUp);
  6361. };
  6362. Scene.prototype.isReady = function () {
  6363. if (this._pendingData.length > 0) {
  6364. return false;
  6365. }
  6366. for (var index = 0; index < this._geometries.length; index++) {
  6367. var geometry = this._geometries[index];
  6368. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6369. return false;
  6370. }
  6371. }
  6372. for (index = 0; index < this.meshes.length; index++) {
  6373. var mesh = this.meshes[index];
  6374. if (!mesh.isReady()) {
  6375. return false;
  6376. }
  6377. var mat = mesh.material;
  6378. if (mat) {
  6379. if (!mat.isReady(mesh)) {
  6380. return false;
  6381. }
  6382. }
  6383. }
  6384. return true;
  6385. };
  6386. Scene.prototype.registerBeforeRender = function (func) {
  6387. this._onBeforeRenderCallbacks.push(func);
  6388. };
  6389. Scene.prototype.unregisterBeforeRender = function (func) {
  6390. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6391. if (index > -1) {
  6392. this._onBeforeRenderCallbacks.splice(index, 1);
  6393. }
  6394. };
  6395. Scene.prototype._addPendingData = function (data) {
  6396. this._pendingData.push(data);
  6397. };
  6398. Scene.prototype._removePendingData = function (data) {
  6399. var index = this._pendingData.indexOf(data);
  6400. if (index !== -1) {
  6401. this._pendingData.splice(index, 1);
  6402. }
  6403. };
  6404. Scene.prototype.getWaitingItemsCount = function () {
  6405. return this._pendingData.length;
  6406. };
  6407. Scene.prototype.executeWhenReady = function (func) {
  6408. var _this = this;
  6409. this._onReadyCallbacks.push(func);
  6410. if (this._executeWhenReadyTimeoutId !== -1) {
  6411. return;
  6412. }
  6413. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6414. _this._checkIsReady();
  6415. }, 150);
  6416. };
  6417. Scene.prototype._checkIsReady = function () {
  6418. var _this = this;
  6419. if (this.isReady()) {
  6420. this._onReadyCallbacks.forEach(function (func) {
  6421. func();
  6422. });
  6423. this._onReadyCallbacks = [];
  6424. this._executeWhenReadyTimeoutId = -1;
  6425. return;
  6426. }
  6427. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6428. _this._checkIsReady();
  6429. }, 150);
  6430. };
  6431. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6432. if (speedRatio === undefined) {
  6433. speedRatio = 1.0;
  6434. }
  6435. this.stopAnimation(target);
  6436. if (!animatable) {
  6437. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6438. }
  6439. if (target.animations) {
  6440. animatable.appendAnimations(target, target.animations);
  6441. }
  6442. if (target.getAnimatables) {
  6443. var animatables = target.getAnimatables();
  6444. for (var index = 0; index < animatables.length; index++) {
  6445. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6446. }
  6447. }
  6448. return animatable;
  6449. };
  6450. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6451. if (speedRatio === undefined) {
  6452. speedRatio = 1.0;
  6453. }
  6454. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6455. return animatable;
  6456. };
  6457. Scene.prototype.getAnimatableByTarget = function (target) {
  6458. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6459. if (this._activeAnimatables[index].target === target) {
  6460. return this._activeAnimatables[index];
  6461. }
  6462. }
  6463. return null;
  6464. };
  6465. Scene.prototype.stopAnimation = function (target) {
  6466. var animatable = this.getAnimatableByTarget(target);
  6467. if (animatable) {
  6468. animatable.stop();
  6469. }
  6470. };
  6471. Scene.prototype._animate = function () {
  6472. if (!this._animationStartDate) {
  6473. this._animationStartDate = BABYLON.Tools.Now;
  6474. }
  6475. var now = BABYLON.Tools.Now;
  6476. var delay = now - this._animationStartDate;
  6477. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6478. if (!this._activeAnimatables[index]._animate(delay)) {
  6479. this._activeAnimatables.splice(index, 1);
  6480. index--;
  6481. }
  6482. }
  6483. };
  6484. Scene.prototype.getViewMatrix = function () {
  6485. return this._viewMatrix;
  6486. };
  6487. Scene.prototype.getProjectionMatrix = function () {
  6488. return this._projectionMatrix;
  6489. };
  6490. Scene.prototype.getTransformMatrix = function () {
  6491. return this._transformMatrix;
  6492. };
  6493. Scene.prototype.setTransformMatrix = function (view, projection) {
  6494. this._viewMatrix = view;
  6495. this._projectionMatrix = projection;
  6496. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6497. };
  6498. Scene.prototype.setActiveCameraByID = function (id) {
  6499. var camera = this.getCameraByID(id);
  6500. if (camera) {
  6501. this.activeCamera = camera;
  6502. return camera;
  6503. }
  6504. return null;
  6505. };
  6506. Scene.prototype.setActiveCameraByName = function (name) {
  6507. var camera = this.getCameraByName(name);
  6508. if (camera) {
  6509. this.activeCamera = camera;
  6510. return camera;
  6511. }
  6512. return null;
  6513. };
  6514. Scene.prototype.getMaterialByID = function (id) {
  6515. for (var index = 0; index < this.materials.length; index++) {
  6516. if (this.materials[index].id === id) {
  6517. return this.materials[index];
  6518. }
  6519. }
  6520. return null;
  6521. };
  6522. Scene.prototype.getMaterialByName = function (name) {
  6523. for (var index = 0; index < this.materials.length; index++) {
  6524. if (this.materials[index].name === name) {
  6525. return this.materials[index];
  6526. }
  6527. }
  6528. return null;
  6529. };
  6530. Scene.prototype.getCameraByID = function (id) {
  6531. for (var index = 0; index < this.cameras.length; index++) {
  6532. if (this.cameras[index].id === id) {
  6533. return this.cameras[index];
  6534. }
  6535. }
  6536. return null;
  6537. };
  6538. Scene.prototype.getCameraByName = function (name) {
  6539. for (var index = 0; index < this.cameras.length; index++) {
  6540. if (this.cameras[index].name === name) {
  6541. return this.cameras[index];
  6542. }
  6543. }
  6544. return null;
  6545. };
  6546. Scene.prototype.getLightByName = function (name) {
  6547. for (var index = 0; index < this.lights.length; index++) {
  6548. if (this.lights[index].name === name) {
  6549. return this.lights[index];
  6550. }
  6551. }
  6552. return null;
  6553. };
  6554. Scene.prototype.getLightByID = function (id) {
  6555. for (var index = 0; index < this.lights.length; index++) {
  6556. if (this.lights[index].id === id) {
  6557. return this.lights[index];
  6558. }
  6559. }
  6560. return null;
  6561. };
  6562. Scene.prototype.getGeometryByID = function (id) {
  6563. for (var index = 0; index < this._geometries.length; index++) {
  6564. if (this._geometries[index].id === id) {
  6565. return this._geometries[index];
  6566. }
  6567. }
  6568. return null;
  6569. };
  6570. Scene.prototype.pushGeometry = function (geometry, force) {
  6571. if (!force && this.getGeometryByID(geometry.id)) {
  6572. return false;
  6573. }
  6574. this._geometries.push(geometry);
  6575. return true;
  6576. };
  6577. Scene.prototype.getGeometries = function () {
  6578. return this._geometries;
  6579. };
  6580. Scene.prototype.getMeshByID = function (id) {
  6581. for (var index = 0; index < this.meshes.length; index++) {
  6582. if (this.meshes[index].id === id) {
  6583. return this.meshes[index];
  6584. }
  6585. }
  6586. return null;
  6587. };
  6588. Scene.prototype.getLastMeshByID = function (id) {
  6589. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6590. if (this.meshes[index].id === id) {
  6591. return this.meshes[index];
  6592. }
  6593. }
  6594. return null;
  6595. };
  6596. Scene.prototype.getLastEntryByID = function (id) {
  6597. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6598. if (this.meshes[index].id === id) {
  6599. return this.meshes[index];
  6600. }
  6601. }
  6602. for (index = this.cameras.length - 1; index >= 0; index--) {
  6603. if (this.cameras[index].id === id) {
  6604. return this.cameras[index];
  6605. }
  6606. }
  6607. for (index = this.lights.length - 1; index >= 0; index--) {
  6608. if (this.lights[index].id === id) {
  6609. return this.lights[index];
  6610. }
  6611. }
  6612. return null;
  6613. };
  6614. Scene.prototype.getMeshByName = function (name) {
  6615. for (var index = 0; index < this.meshes.length; index++) {
  6616. if (this.meshes[index].name === name) {
  6617. return this.meshes[index];
  6618. }
  6619. }
  6620. return null;
  6621. };
  6622. Scene.prototype.getLastSkeletonByID = function (id) {
  6623. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6624. if (this.skeletons[index].id === id) {
  6625. return this.skeletons[index];
  6626. }
  6627. }
  6628. return null;
  6629. };
  6630. Scene.prototype.getSkeletonById = function (id) {
  6631. for (var index = 0; index < this.skeletons.length; index++) {
  6632. if (this.skeletons[index].id === id) {
  6633. return this.skeletons[index];
  6634. }
  6635. }
  6636. return null;
  6637. };
  6638. Scene.prototype.getSkeletonByName = function (name) {
  6639. for (var index = 0; index < this.skeletons.length; index++) {
  6640. if (this.skeletons[index].name === name) {
  6641. return this.skeletons[index];
  6642. }
  6643. }
  6644. return null;
  6645. };
  6646. Scene.prototype.isActiveMesh = function (mesh) {
  6647. return (this._activeMeshes.indexOf(mesh) !== -1);
  6648. };
  6649. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6650. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6651. var material = subMesh.getMaterial();
  6652. if (mesh.showSubMeshesBoundingBox) {
  6653. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6654. }
  6655. if (material) {
  6656. if (material.getRenderTargetTextures) {
  6657. if (this._processedMaterials.indexOf(material) === -1) {
  6658. this._processedMaterials.push(material);
  6659. this._renderTargets.concat(material.getRenderTargetTextures());
  6660. }
  6661. }
  6662. this._activeVertices += subMesh.verticesCount;
  6663. this._renderingManager.dispatch(subMesh);
  6664. }
  6665. }
  6666. };
  6667. Scene.prototype._evaluateActiveMeshes = function () {
  6668. this._activeMeshes.reset();
  6669. this._renderingManager.reset();
  6670. this._processedMaterials.reset();
  6671. this._activeParticleSystems.reset();
  6672. this._activeSkeletons.reset();
  6673. this._boundingBoxRenderer.reset();
  6674. if (!this._frustumPlanes) {
  6675. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6676. } else {
  6677. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6678. }
  6679. var meshes;
  6680. var len;
  6681. if (this._selectionOctree) {
  6682. var selection = this._selectionOctree.select(this._frustumPlanes);
  6683. meshes = selection.data;
  6684. len = selection.length;
  6685. } else {
  6686. len = this.meshes.length;
  6687. meshes = this.meshes;
  6688. }
  6689. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6690. var mesh = meshes[meshIndex];
  6691. this._totalVertices += mesh.getTotalVertices();
  6692. if (!mesh.isReady()) {
  6693. continue;
  6694. }
  6695. mesh.computeWorldMatrix();
  6696. mesh._preActivate();
  6697. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6698. this._meshesForIntersections.pushNoDuplicate(mesh);
  6699. }
  6700. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6701. this._activeMeshes.push(mesh);
  6702. mesh._activate(this._renderId);
  6703. this._activeMesh(mesh);
  6704. }
  6705. }
  6706. var beforeParticlesDate = BABYLON.Tools.Now;
  6707. if (this.particlesEnabled) {
  6708. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  6709. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6710. var particleSystem = this.particleSystems[particleIndex];
  6711. if (!particleSystem.isStarted()) {
  6712. continue;
  6713. }
  6714. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6715. this._activeParticleSystems.push(particleSystem);
  6716. particleSystem.animate();
  6717. }
  6718. }
  6719. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  6720. }
  6721. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  6722. };
  6723. Scene.prototype._activeMesh = function (mesh) {
  6724. if (mesh.skeleton) {
  6725. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6726. }
  6727. if (mesh.showBoundingBox) {
  6728. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6729. }
  6730. if (mesh.subMeshes) {
  6731. var len;
  6732. var subMeshes;
  6733. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6734. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6735. len = intersections.length;
  6736. subMeshes = intersections.data;
  6737. } else {
  6738. subMeshes = mesh.subMeshes;
  6739. len = subMeshes.length;
  6740. }
  6741. for (var subIndex = 0; subIndex < len; subIndex++) {
  6742. var subMesh = subMeshes[subIndex];
  6743. this._evaluateSubMesh(subMesh, mesh);
  6744. }
  6745. }
  6746. };
  6747. Scene.prototype.updateTransformMatrix = function (force) {
  6748. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6749. };
  6750. Scene.prototype._renderForCamera = function (camera) {
  6751. var engine = this._engine;
  6752. this.activeCamera = camera;
  6753. if (!this.activeCamera)
  6754. throw new Error("Active camera not set");
  6755. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  6756. engine.setViewport(this.activeCamera.viewport);
  6757. this._renderId++;
  6758. this.updateTransformMatrix();
  6759. if (this.beforeCameraRender) {
  6760. this.beforeCameraRender(this.activeCamera);
  6761. }
  6762. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  6763. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  6764. this._evaluateActiveMeshes();
  6765. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  6766. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  6767. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6768. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6769. skeleton.prepare();
  6770. }
  6771. var beforeRenderTargetDate = BABYLON.Tools.Now;
  6772. if (this.renderTargetsEnabled) {
  6773. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  6774. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6775. var renderTarget = this._renderTargets.data[renderIndex];
  6776. if (renderTarget._shouldRender()) {
  6777. this._renderId++;
  6778. renderTarget.render();
  6779. }
  6780. }
  6781. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  6782. this._renderId++;
  6783. }
  6784. if (this._renderTargets.length > 0) {
  6785. engine.restoreDefaultFramebuffer();
  6786. }
  6787. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  6788. this.postProcessManager._prepareFrame();
  6789. var beforeRenderDate = BABYLON.Tools.Now;
  6790. if (this.layers.length) {
  6791. engine.setDepthBuffer(false);
  6792. var layerIndex;
  6793. var layer;
  6794. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6795. layer = this.layers[layerIndex];
  6796. if (layer.isBackground) {
  6797. layer.render();
  6798. }
  6799. }
  6800. engine.setDepthBuffer(true);
  6801. }
  6802. BABYLON.Tools.StartPerformanceCounter("Main render");
  6803. this._renderingManager.render(null, null, true, true);
  6804. BABYLON.Tools.EndPerformanceCounter("Main render");
  6805. this._boundingBoxRenderer.render();
  6806. if (this.lensFlaresEnabled) {
  6807. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  6808. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6809. this.lensFlareSystems[lensFlareSystemIndex].render();
  6810. }
  6811. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  6812. }
  6813. if (this.layers.length) {
  6814. engine.setDepthBuffer(false);
  6815. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6816. layer = this.layers[layerIndex];
  6817. if (!layer.isBackground) {
  6818. layer.render();
  6819. }
  6820. }
  6821. engine.setDepthBuffer(true);
  6822. }
  6823. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  6824. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6825. this.activeCamera._updateFromScene();
  6826. this._renderTargets.reset();
  6827. if (this.afterCameraRender) {
  6828. this.afterCameraRender(this.activeCamera);
  6829. }
  6830. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  6831. };
  6832. Scene.prototype._processSubCameras = function (camera) {
  6833. if (camera.subCameras.length == 0) {
  6834. this._renderForCamera(camera);
  6835. return;
  6836. }
  6837. for (var index = 0; index < camera.subCameras.length; index++) {
  6838. this._renderForCamera(camera.subCameras[index]);
  6839. }
  6840. this.activeCamera = camera;
  6841. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6842. this.activeCamera._updateFromScene();
  6843. };
  6844. Scene.prototype._checkIntersections = function () {
  6845. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6846. var sourceMesh = this._meshesForIntersections.data[index];
  6847. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6848. var action = sourceMesh.actionManager.actions[actionIndex];
  6849. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6850. var otherMesh = action.getTriggerParameter();
  6851. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6852. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6853. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6854. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6855. sourceMesh._intersectionsInProgress.push(otherMesh);
  6856. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6857. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6858. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6859. if (indexOfOther > -1) {
  6860. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6861. }
  6862. }
  6863. }
  6864. }
  6865. }
  6866. };
  6867. Scene.prototype.render = function () {
  6868. var startDate = BABYLON.Tools.Now;
  6869. this._particlesDuration = 0;
  6870. this._spritesDuration = 0;
  6871. this._activeParticles = 0;
  6872. this._renderDuration = 0;
  6873. this._evaluateActiveMeshesDuration = 0;
  6874. this._totalVertices = 0;
  6875. this._activeVertices = 0;
  6876. this._meshesForIntersections.reset();
  6877. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  6878. if (this.actionManager) {
  6879. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6880. }
  6881. if (this.beforeRender) {
  6882. this.beforeRender();
  6883. }
  6884. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6885. this._onBeforeRenderCallbacks[callbackIndex]();
  6886. }
  6887. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6888. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6889. this._animate();
  6890. if (this._physicsEngine) {
  6891. BABYLON.Tools.StartPerformanceCounter("Physics");
  6892. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6893. BABYLON.Tools.EndPerformanceCounter("Physics");
  6894. }
  6895. var beforeRenderTargetDate = BABYLON.Tools.Now;
  6896. var engine = this.getEngine();
  6897. if (this.renderTargetsEnabled) {
  6898. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  6899. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6900. var renderTarget = this.customRenderTargets[customIndex];
  6901. if (renderTarget._shouldRender()) {
  6902. this._renderId++;
  6903. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6904. if (!this.activeCamera)
  6905. throw new Error("Active camera not set");
  6906. engine.setViewport(this.activeCamera.viewport);
  6907. this.updateTransformMatrix();
  6908. renderTarget.render();
  6909. }
  6910. }
  6911. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  6912. this._renderId++;
  6913. }
  6914. if (this.customRenderTargets.length > 0) {
  6915. engine.restoreDefaultFramebuffer();
  6916. }
  6917. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  6918. if (this.proceduralTexturesEnabled) {
  6919. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  6920. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  6921. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  6922. if (proceduralTexture._shouldRender()) {
  6923. proceduralTexture.render();
  6924. }
  6925. }
  6926. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  6927. }
  6928. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6929. if (this.shadowsEnabled) {
  6930. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6931. var light = this.lights[lightIndex];
  6932. var shadowGenerator = light.getShadowGenerator();
  6933. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6934. this._renderTargets.push(shadowGenerator.getShadowMap());
  6935. }
  6936. }
  6937. }
  6938. this.postProcessRenderPipelineManager.update();
  6939. if (this.activeCameras.length > 0) {
  6940. var currentRenderId = this._renderId;
  6941. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6942. this._renderId = currentRenderId;
  6943. this._processSubCameras(this.activeCameras[cameraIndex]);
  6944. }
  6945. } else {
  6946. if (!this.activeCamera) {
  6947. throw new Error("No camera defined");
  6948. }
  6949. this._processSubCameras(this.activeCamera);
  6950. }
  6951. this._checkIntersections();
  6952. if (this.afterRender) {
  6953. this.afterRender();
  6954. }
  6955. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6956. this._toBeDisposed.data[index].dispose();
  6957. this._toBeDisposed[index] = null;
  6958. }
  6959. this._toBeDisposed.reset();
  6960. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  6961. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  6962. };
  6963. Scene.prototype.dispose = function () {
  6964. this.beforeRender = null;
  6965. this.afterRender = null;
  6966. this.skeletons = [];
  6967. this._boundingBoxRenderer.dispose();
  6968. if (this.onDispose) {
  6969. this.onDispose();
  6970. }
  6971. this.detachControl();
  6972. var canvas = this._engine.getRenderingCanvas();
  6973. var index;
  6974. for (index = 0; index < this.cameras.length; index++) {
  6975. this.cameras[index].detachControl(canvas);
  6976. }
  6977. while (this.lights.length) {
  6978. this.lights[0].dispose();
  6979. }
  6980. while (this.meshes.length) {
  6981. this.meshes[0].dispose(true);
  6982. }
  6983. while (this.cameras.length) {
  6984. this.cameras[0].dispose();
  6985. }
  6986. while (this.materials.length) {
  6987. this.materials[0].dispose();
  6988. }
  6989. while (this.particleSystems.length) {
  6990. this.particleSystems[0].dispose();
  6991. }
  6992. while (this.spriteManagers.length) {
  6993. this.spriteManagers[0].dispose();
  6994. }
  6995. while (this.layers.length) {
  6996. this.layers[0].dispose();
  6997. }
  6998. while (this.textures.length) {
  6999. this.textures[0].dispose();
  7000. }
  7001. this.postProcessManager.dispose();
  7002. if (this._physicsEngine) {
  7003. this.disablePhysicsEngine();
  7004. }
  7005. index = this._engine.scenes.indexOf(this);
  7006. if (index > -1) {
  7007. this._engine.scenes.splice(index, 1);
  7008. }
  7009. this._engine.wipeCaches();
  7010. };
  7011. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7012. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7013. position.divideToRef(collider.radius, this._scaledPosition);
  7014. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7015. collider.retry = 0;
  7016. collider.initialVelocity = this._scaledVelocity;
  7017. collider.initialPosition = this._scaledPosition;
  7018. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7019. finalPosition.multiplyInPlace(collider.radius);
  7020. };
  7021. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7022. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7023. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7024. if (collider.retry >= maximumRetry) {
  7025. finalPosition.copyFrom(position);
  7026. return;
  7027. }
  7028. collider._initialize(position, velocity, closeDistance);
  7029. for (var index = 0; index < this.meshes.length; index++) {
  7030. var mesh = this.meshes[index];
  7031. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7032. mesh._checkCollision(collider);
  7033. }
  7034. }
  7035. if (!collider.collisionFound) {
  7036. position.addToRef(velocity, finalPosition);
  7037. return;
  7038. }
  7039. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7040. collider._getResponse(position, velocity);
  7041. }
  7042. if (velocity.length() <= closeDistance) {
  7043. finalPosition.copyFrom(position);
  7044. return;
  7045. }
  7046. collider.retry++;
  7047. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7048. };
  7049. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7050. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7051. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7052. if (!this._selectionOctree) {
  7053. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7054. }
  7055. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7056. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7057. for (var index = 0; index < this.meshes.length; index++) {
  7058. var mesh = this.meshes[index];
  7059. mesh.computeWorldMatrix(true);
  7060. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7061. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7062. BABYLON.Tools.CheckExtends(minBox, min, max);
  7063. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7064. }
  7065. this._selectionOctree.update(min, max, this.meshes);
  7066. return this._selectionOctree;
  7067. };
  7068. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7069. var engine = this._engine;
  7070. if (!camera) {
  7071. if (!this.activeCamera)
  7072. throw new Error("Active camera not set");
  7073. camera = this.activeCamera;
  7074. }
  7075. var cameraViewport = camera.viewport;
  7076. var viewport = cameraViewport.toGlobal(engine);
  7077. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7078. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7079. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7080. };
  7081. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7082. var pickingInfo = null;
  7083. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7084. var mesh = this.meshes[meshIndex];
  7085. if (predicate) {
  7086. if (!predicate(mesh)) {
  7087. continue;
  7088. }
  7089. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7090. continue;
  7091. }
  7092. var world = mesh.getWorldMatrix();
  7093. var ray = rayFunction(world);
  7094. var result = mesh.intersects(ray, fastCheck);
  7095. if (!result || !result.hit)
  7096. continue;
  7097. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7098. continue;
  7099. pickingInfo = result;
  7100. if (fastCheck) {
  7101. break;
  7102. }
  7103. }
  7104. return pickingInfo || new BABYLON.PickingInfo();
  7105. };
  7106. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7107. var _this = this;
  7108. return this._internalPick(function (world) {
  7109. return _this.createPickingRay(x, y, world, camera);
  7110. }, predicate, fastCheck);
  7111. };
  7112. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7113. var _this = this;
  7114. return this._internalPick(function (world) {
  7115. if (!_this._pickWithRayInverseMatrix) {
  7116. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7117. }
  7118. world.invertToRef(_this._pickWithRayInverseMatrix);
  7119. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7120. }, predicate, fastCheck);
  7121. };
  7122. Scene.prototype.setPointerOverMesh = function (mesh) {
  7123. if (this._pointerOverMesh === mesh) {
  7124. return;
  7125. }
  7126. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7127. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7128. }
  7129. this._pointerOverMesh = mesh;
  7130. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7131. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7132. }
  7133. };
  7134. Scene.prototype.getPointerOverMesh = function () {
  7135. return this._pointerOverMesh;
  7136. };
  7137. Scene.prototype.getPhysicsEngine = function () {
  7138. return this._physicsEngine;
  7139. };
  7140. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7141. if (this._physicsEngine) {
  7142. return true;
  7143. }
  7144. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7145. if (!this._physicsEngine.isSupported()) {
  7146. this._physicsEngine = null;
  7147. return false;
  7148. }
  7149. this._physicsEngine._initialize(gravity);
  7150. return true;
  7151. };
  7152. Scene.prototype.disablePhysicsEngine = function () {
  7153. if (!this._physicsEngine) {
  7154. return;
  7155. }
  7156. this._physicsEngine.dispose();
  7157. this._physicsEngine = undefined;
  7158. };
  7159. Scene.prototype.isPhysicsEnabled = function () {
  7160. return this._physicsEngine !== undefined;
  7161. };
  7162. Scene.prototype.setGravity = function (gravity) {
  7163. if (!this._physicsEngine) {
  7164. return;
  7165. }
  7166. this._physicsEngine._setGravity(gravity);
  7167. };
  7168. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7169. if (parts.parts) {
  7170. options = parts;
  7171. parts = parts.parts;
  7172. }
  7173. if (!this._physicsEngine) {
  7174. return null;
  7175. }
  7176. for (var index = 0; index < parts.length; index++) {
  7177. var mesh = parts[index].mesh;
  7178. mesh._physicImpostor = parts[index].impostor;
  7179. mesh._physicsMass = options.mass / parts.length;
  7180. mesh._physicsFriction = options.friction;
  7181. mesh._physicRestitution = options.restitution;
  7182. }
  7183. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7184. };
  7185. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7186. for (var index = 0; index < compound.parts.length; index++) {
  7187. var mesh = compound.parts[index].mesh;
  7188. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7189. this._physicsEngine._unregisterMesh(mesh);
  7190. }
  7191. };
  7192. Scene.prototype._getByTags = function (list, tagsQuery) {
  7193. if (tagsQuery === undefined) {
  7194. return list;
  7195. }
  7196. var listByTags = [];
  7197. for (var i in list) {
  7198. var item = list[i];
  7199. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7200. listByTags.push(item);
  7201. }
  7202. }
  7203. return listByTags;
  7204. };
  7205. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7206. return this._getByTags(this.meshes, tagsQuery);
  7207. };
  7208. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7209. return this._getByTags(this.cameras, tagsQuery);
  7210. };
  7211. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7212. return this._getByTags(this.lights, tagsQuery);
  7213. };
  7214. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7215. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7216. };
  7217. Scene.FOGMODE_NONE = 0;
  7218. Scene.FOGMODE_EXP = 1;
  7219. Scene.FOGMODE_EXP2 = 2;
  7220. Scene.FOGMODE_LINEAR = 3;
  7221. Scene.MinDeltaTime = 1.0;
  7222. Scene.MaxDeltaTime = 1000.0;
  7223. return Scene;
  7224. })();
  7225. BABYLON.Scene = Scene;
  7226. })(BABYLON || (BABYLON = {}));
  7227. var BABYLON;
  7228. (function (BABYLON) {
  7229. var VertexBuffer = (function () {
  7230. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7231. if (engine instanceof BABYLON.Mesh) {
  7232. this._engine = engine.getScene().getEngine();
  7233. } else {
  7234. this._engine = engine;
  7235. }
  7236. this._updatable = updatable;
  7237. this._data = data;
  7238. if (!postponeInternalCreation) {
  7239. this.create();
  7240. }
  7241. this._kind = kind;
  7242. switch (kind) {
  7243. case VertexBuffer.PositionKind:
  7244. this._strideSize = 3;
  7245. break;
  7246. case VertexBuffer.NormalKind:
  7247. this._strideSize = 3;
  7248. break;
  7249. case VertexBuffer.UVKind:
  7250. this._strideSize = 2;
  7251. break;
  7252. case VertexBuffer.UV2Kind:
  7253. this._strideSize = 2;
  7254. break;
  7255. case VertexBuffer.ColorKind:
  7256. this._strideSize = 3;
  7257. break;
  7258. case VertexBuffer.MatricesIndicesKind:
  7259. this._strideSize = 4;
  7260. break;
  7261. case VertexBuffer.MatricesWeightsKind:
  7262. this._strideSize = 4;
  7263. break;
  7264. }
  7265. }
  7266. VertexBuffer.prototype.isUpdatable = function () {
  7267. return this._updatable;
  7268. };
  7269. VertexBuffer.prototype.getData = function () {
  7270. return this._data;
  7271. };
  7272. VertexBuffer.prototype.getBuffer = function () {
  7273. return this._buffer;
  7274. };
  7275. VertexBuffer.prototype.getStrideSize = function () {
  7276. return this._strideSize;
  7277. };
  7278. VertexBuffer.prototype.create = function (data) {
  7279. if (!data && this._buffer) {
  7280. return;
  7281. }
  7282. data = data || this._data;
  7283. if (!this._buffer) {
  7284. if (this._updatable) {
  7285. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7286. } else {
  7287. this._buffer = this._engine.createVertexBuffer(data);
  7288. }
  7289. }
  7290. if (this._updatable) {
  7291. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7292. this._data = data;
  7293. }
  7294. };
  7295. VertexBuffer.prototype.update = function (data) {
  7296. this.create(data);
  7297. };
  7298. VertexBuffer.prototype.updateDirectly = function (data) {
  7299. if (!this._buffer) {
  7300. return;
  7301. }
  7302. if (this._updatable) {
  7303. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7304. this._data = null;
  7305. }
  7306. };
  7307. VertexBuffer.prototype.dispose = function () {
  7308. if (!this._buffer) {
  7309. return;
  7310. }
  7311. if (this._engine._releaseBuffer(this._buffer)) {
  7312. this._buffer = null;
  7313. }
  7314. };
  7315. Object.defineProperty(VertexBuffer, "PositionKind", {
  7316. get: function () {
  7317. return VertexBuffer._PositionKind;
  7318. },
  7319. enumerable: true,
  7320. configurable: true
  7321. });
  7322. Object.defineProperty(VertexBuffer, "NormalKind", {
  7323. get: function () {
  7324. return VertexBuffer._NormalKind;
  7325. },
  7326. enumerable: true,
  7327. configurable: true
  7328. });
  7329. Object.defineProperty(VertexBuffer, "UVKind", {
  7330. get: function () {
  7331. return VertexBuffer._UVKind;
  7332. },
  7333. enumerable: true,
  7334. configurable: true
  7335. });
  7336. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7337. get: function () {
  7338. return VertexBuffer._UV2Kind;
  7339. },
  7340. enumerable: true,
  7341. configurable: true
  7342. });
  7343. Object.defineProperty(VertexBuffer, "ColorKind", {
  7344. get: function () {
  7345. return VertexBuffer._ColorKind;
  7346. },
  7347. enumerable: true,
  7348. configurable: true
  7349. });
  7350. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7351. get: function () {
  7352. return VertexBuffer._MatricesIndicesKind;
  7353. },
  7354. enumerable: true,
  7355. configurable: true
  7356. });
  7357. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7358. get: function () {
  7359. return VertexBuffer._MatricesWeightsKind;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. VertexBuffer._PositionKind = "position";
  7365. VertexBuffer._NormalKind = "normal";
  7366. VertexBuffer._UVKind = "uv";
  7367. VertexBuffer._UV2Kind = "uv2";
  7368. VertexBuffer._ColorKind = "color";
  7369. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7370. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7371. return VertexBuffer;
  7372. })();
  7373. BABYLON.VertexBuffer = VertexBuffer;
  7374. })(BABYLON || (BABYLON = {}));
  7375. var __extends = this.__extends || function (d, b) {
  7376. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7377. function __() { this.constructor = d; }
  7378. __.prototype = b.prototype;
  7379. d.prototype = new __();
  7380. };
  7381. var BABYLON;
  7382. (function (BABYLON) {
  7383. var AbstractMesh = (function (_super) {
  7384. __extends(AbstractMesh, _super);
  7385. function AbstractMesh(name, scene) {
  7386. _super.call(this, name, scene);
  7387. this.position = new BABYLON.Vector3(0, 0, 0);
  7388. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7389. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7390. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7391. this.visibility = 1.0;
  7392. this.infiniteDistance = false;
  7393. this.isVisible = true;
  7394. this.isPickable = true;
  7395. this.showBoundingBox = false;
  7396. this.showSubMeshesBoundingBox = false;
  7397. this.onDispose = null;
  7398. this.checkCollisions = false;
  7399. this.isBlocker = false;
  7400. this.renderingGroupId = 0;
  7401. this.receiveShadows = false;
  7402. this.renderOutline = false;
  7403. this.outlineColor = BABYLON.Color3.Red();
  7404. this.outlineWidth = 0.02;
  7405. this.useOctreeForRenderingSelection = true;
  7406. this.useOctreeForPicking = true;
  7407. this.useOctreeForCollisions = true;
  7408. this.layerMask = 0xFFFFFFFF;
  7409. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7410. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7411. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7412. this._collider = new BABYLON.Collider();
  7413. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7414. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7415. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7416. this._localScaling = BABYLON.Matrix.Zero();
  7417. this._localRotation = BABYLON.Matrix.Zero();
  7418. this._localTranslation = BABYLON.Matrix.Zero();
  7419. this._localBillboard = BABYLON.Matrix.Zero();
  7420. this._localPivotScaling = BABYLON.Matrix.Zero();
  7421. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7422. this._localWorld = BABYLON.Matrix.Zero();
  7423. this._worldMatrix = BABYLON.Matrix.Zero();
  7424. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7425. this._absolutePosition = BABYLON.Vector3.Zero();
  7426. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7427. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7428. this._isDirty = false;
  7429. this._pivotMatrix = BABYLON.Matrix.Identity();
  7430. this._isDisposed = false;
  7431. this._renderId = 0;
  7432. this._intersectionsInProgress = new Array();
  7433. scene.meshes.push(this);
  7434. }
  7435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7436. get: function () {
  7437. return AbstractMesh._BILLBOARDMODE_NONE;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7443. get: function () {
  7444. return AbstractMesh._BILLBOARDMODE_X;
  7445. },
  7446. enumerable: true,
  7447. configurable: true
  7448. });
  7449. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7450. get: function () {
  7451. return AbstractMesh._BILLBOARDMODE_Y;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7457. get: function () {
  7458. return AbstractMesh._BILLBOARDMODE_Z;
  7459. },
  7460. enumerable: true,
  7461. configurable: true
  7462. });
  7463. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7464. get: function () {
  7465. return AbstractMesh._BILLBOARDMODE_ALL;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. AbstractMesh.prototype.getTotalVertices = function () {
  7471. return 0;
  7472. };
  7473. AbstractMesh.prototype.getIndices = function () {
  7474. return null;
  7475. };
  7476. AbstractMesh.prototype.getVerticesData = function (kind) {
  7477. return null;
  7478. };
  7479. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7480. return false;
  7481. };
  7482. AbstractMesh.prototype.getBoundingInfo = function () {
  7483. if (!this._boundingInfo) {
  7484. this._updateBoundingInfo();
  7485. }
  7486. return this._boundingInfo;
  7487. };
  7488. AbstractMesh.prototype._preActivate = function () {
  7489. };
  7490. AbstractMesh.prototype._activate = function (renderId) {
  7491. this._renderId = renderId;
  7492. };
  7493. AbstractMesh.prototype.getWorldMatrix = function () {
  7494. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7495. this.computeWorldMatrix();
  7496. }
  7497. return this._worldMatrix;
  7498. };
  7499. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7500. get: function () {
  7501. return this._worldMatrix;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7507. get: function () {
  7508. return this._absolutePosition;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7514. if (!this.rotationQuaternion) {
  7515. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7516. this.rotation = BABYLON.Vector3.Zero();
  7517. }
  7518. if (!space || space == 0 /* LOCAL */) {
  7519. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7520. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7521. } else {
  7522. if (this.parent) {
  7523. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7524. invertParentWorldMatrix.invert();
  7525. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7526. }
  7527. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7528. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7529. }
  7530. };
  7531. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7532. var displacementVector = axis.scale(distance);
  7533. if (!space || space == 0 /* LOCAL */) {
  7534. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7535. this.setPositionWithLocalVector(tempV3);
  7536. } else {
  7537. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7538. }
  7539. };
  7540. AbstractMesh.prototype.getAbsolutePosition = function () {
  7541. this.computeWorldMatrix();
  7542. return this._absolutePosition;
  7543. };
  7544. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7545. if (!absolutePosition) {
  7546. return;
  7547. }
  7548. var absolutePositionX;
  7549. var absolutePositionY;
  7550. var absolutePositionZ;
  7551. if (absolutePosition.x === undefined) {
  7552. if (arguments.length < 3) {
  7553. return;
  7554. }
  7555. absolutePositionX = arguments[0];
  7556. absolutePositionY = arguments[1];
  7557. absolutePositionZ = arguments[2];
  7558. } else {
  7559. absolutePositionX = absolutePosition.x;
  7560. absolutePositionY = absolutePosition.y;
  7561. absolutePositionZ = absolutePosition.z;
  7562. }
  7563. if (this.parent) {
  7564. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7565. invertParentWorldMatrix.invert();
  7566. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7567. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7568. } else {
  7569. this.position.x = absolutePositionX;
  7570. this.position.y = absolutePositionY;
  7571. this.position.z = absolutePositionZ;
  7572. }
  7573. };
  7574. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7575. this._pivotMatrix = matrix;
  7576. this._cache.pivotMatrixUpdated = true;
  7577. };
  7578. AbstractMesh.prototype.getPivotMatrix = function () {
  7579. return this._pivotMatrix;
  7580. };
  7581. AbstractMesh.prototype._isSynchronized = function () {
  7582. if (this._isDirty) {
  7583. return false;
  7584. }
  7585. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7586. return false;
  7587. if (this._cache.pivotMatrixUpdated) {
  7588. return false;
  7589. }
  7590. if (this.infiniteDistance) {
  7591. return false;
  7592. }
  7593. if (!this._cache.position.equals(this.position))
  7594. return false;
  7595. if (this.rotationQuaternion) {
  7596. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7597. return false;
  7598. } else {
  7599. if (!this._cache.rotation.equals(this.rotation))
  7600. return false;
  7601. }
  7602. if (!this._cache.scaling.equals(this.scaling))
  7603. return false;
  7604. return true;
  7605. };
  7606. AbstractMesh.prototype._initCache = function () {
  7607. _super.prototype._initCache.call(this);
  7608. this._cache.localMatrixUpdated = false;
  7609. this._cache.position = BABYLON.Vector3.Zero();
  7610. this._cache.scaling = BABYLON.Vector3.Zero();
  7611. this._cache.rotation = BABYLON.Vector3.Zero();
  7612. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7613. };
  7614. AbstractMesh.prototype.markAsDirty = function (property) {
  7615. if (property === "rotation") {
  7616. this.rotationQuaternion = null;
  7617. }
  7618. this._currentRenderId = Number.MAX_VALUE;
  7619. this._isDirty = true;
  7620. };
  7621. AbstractMesh.prototype._updateBoundingInfo = function () {
  7622. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7623. this._boundingInfo._update(this.worldMatrixFromCache);
  7624. if (!this.subMeshes) {
  7625. return;
  7626. }
  7627. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7628. var subMesh = this.subMeshes[subIndex];
  7629. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7630. }
  7631. };
  7632. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7633. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7634. return this._worldMatrix;
  7635. }
  7636. this._cache.position.copyFrom(this.position);
  7637. this._cache.scaling.copyFrom(this.scaling);
  7638. this._cache.pivotMatrixUpdated = false;
  7639. this._currentRenderId = this.getScene().getRenderId();
  7640. this._isDirty = false;
  7641. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7642. if (this.rotationQuaternion) {
  7643. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7644. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7645. } else {
  7646. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7647. this._cache.rotation.copyFrom(this.rotation);
  7648. }
  7649. if (this.infiniteDistance && !this.parent) {
  7650. var camera = this.getScene().activeCamera;
  7651. var cameraWorldMatrix = camera.getWorldMatrix();
  7652. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7653. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7654. } else {
  7655. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7656. }
  7657. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7658. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7659. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7660. var localPosition = this.position.clone();
  7661. var zero = this.getScene().activeCamera.position.clone();
  7662. if (this.parent && this.parent.position) {
  7663. localPosition.addInPlace(this.parent.position);
  7664. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7665. }
  7666. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7667. zero = this.getScene().activeCamera.position;
  7668. } else {
  7669. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7670. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7671. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7672. zero.y = localPosition.y + 0.001;
  7673. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7674. zero.z = localPosition.z + 0.001;
  7675. }
  7676. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7677. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7678. this._localBillboard.invert();
  7679. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7680. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7681. }
  7682. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7683. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7684. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7685. } else {
  7686. this._worldMatrix.copyFrom(this._localWorld);
  7687. }
  7688. this._updateBoundingInfo();
  7689. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7690. return this._worldMatrix;
  7691. };
  7692. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7693. this.computeWorldMatrix();
  7694. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7695. };
  7696. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7697. this.computeWorldMatrix();
  7698. var invLocalWorldMatrix = this._localWorld.clone();
  7699. invLocalWorldMatrix.invert();
  7700. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7701. };
  7702. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7703. this.computeWorldMatrix();
  7704. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7705. };
  7706. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7707. yawCor = yawCor || 0;
  7708. pitchCor = pitchCor || 0;
  7709. rollCor = rollCor || 0;
  7710. var dv = targetPoint.subtract(this.position);
  7711. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7712. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7713. var pitch = Math.atan2(dv.y, len);
  7714. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7715. };
  7716. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7717. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7718. return false;
  7719. }
  7720. return true;
  7721. };
  7722. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7723. if (!camera) {
  7724. camera = this.getScene().activeCamera;
  7725. }
  7726. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7727. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7728. return false;
  7729. }
  7730. return true;
  7731. };
  7732. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7733. if (!this._boundingInfo || !mesh._boundingInfo) {
  7734. return false;
  7735. }
  7736. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7737. };
  7738. AbstractMesh.prototype.intersectsPoint = function (point) {
  7739. if (!this._boundingInfo) {
  7740. return false;
  7741. }
  7742. return this._boundingInfo.intersectsPoint(point);
  7743. };
  7744. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7745. var physicsEngine = this.getScene().getPhysicsEngine();
  7746. if (!physicsEngine) {
  7747. return;
  7748. }
  7749. if (impostor.impostor) {
  7750. options = impostor;
  7751. impostor = impostor.impostor;
  7752. }
  7753. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7754. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7755. physicsEngine._unregisterMesh(this);
  7756. return;
  7757. }
  7758. options.mass = options.mass || 0;
  7759. options.friction = options.friction || 0.2;
  7760. options.restitution = options.restitution || 0.2;
  7761. this._physicImpostor = impostor;
  7762. this._physicsMass = options.mass;
  7763. this._physicsFriction = options.friction;
  7764. this._physicRestitution = options.restitution;
  7765. physicsEngine._registerMesh(this, impostor, options);
  7766. };
  7767. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7768. if (!this._physicImpostor) {
  7769. return BABYLON.PhysicsEngine.NoImpostor;
  7770. }
  7771. return this._physicImpostor;
  7772. };
  7773. AbstractMesh.prototype.getPhysicsMass = function () {
  7774. if (!this._physicsMass) {
  7775. return 0;
  7776. }
  7777. return this._physicsMass;
  7778. };
  7779. AbstractMesh.prototype.getPhysicsFriction = function () {
  7780. if (!this._physicsFriction) {
  7781. return 0;
  7782. }
  7783. return this._physicsFriction;
  7784. };
  7785. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7786. if (!this._physicRestitution) {
  7787. return 0;
  7788. }
  7789. return this._physicRestitution;
  7790. };
  7791. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7792. if (!this._physicImpostor) {
  7793. return;
  7794. }
  7795. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7796. };
  7797. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7798. if (!this._physicImpostor) {
  7799. return;
  7800. }
  7801. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7802. };
  7803. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7804. if (!this._physicImpostor) {
  7805. return;
  7806. }
  7807. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7808. };
  7809. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7810. var globalPosition = this.getAbsolutePosition();
  7811. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7812. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7813. this._collider.radius = this.ellipsoid;
  7814. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7815. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7816. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7817. this.position.addInPlace(this._diffPositionForCollisions);
  7818. }
  7819. };
  7820. /**
  7821. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7822. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7823. */
  7824. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7825. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7826. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7827. if (!this._submeshesOctree) {
  7828. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7829. }
  7830. this.computeWorldMatrix(true);
  7831. var bbox = this.getBoundingInfo().boundingBox;
  7832. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7833. return this._submeshesOctree;
  7834. };
  7835. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7836. this._generatePointsArray();
  7837. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7838. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7839. subMesh._lastColliderWorldVertices = [];
  7840. subMesh._trianglePlanes = [];
  7841. var start = subMesh.verticesStart;
  7842. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7843. for (var i = start; i < end; i++) {
  7844. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7845. }
  7846. }
  7847. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7848. };
  7849. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7850. var subMeshes;
  7851. var len;
  7852. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7853. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7854. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7855. len = intersections.length;
  7856. subMeshes = intersections.data;
  7857. } else {
  7858. subMeshes = this.subMeshes;
  7859. len = subMeshes.length;
  7860. }
  7861. for (var index = 0; index < len; index++) {
  7862. var subMesh = subMeshes[index];
  7863. if (len > 1 && !subMesh._checkCollision(collider))
  7864. continue;
  7865. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7866. }
  7867. };
  7868. AbstractMesh.prototype._checkCollision = function (collider) {
  7869. if (!this._boundingInfo._checkCollision(collider))
  7870. return;
  7871. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7872. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7873. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7874. };
  7875. AbstractMesh.prototype._generatePointsArray = function () {
  7876. return false;
  7877. };
  7878. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7879. var pickingInfo = new BABYLON.PickingInfo();
  7880. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7881. return pickingInfo;
  7882. }
  7883. if (!this._generatePointsArray()) {
  7884. return pickingInfo;
  7885. }
  7886. var intersectInfo = null;
  7887. var subMeshes;
  7888. var len;
  7889. if (this._submeshesOctree && this.useOctreeForPicking) {
  7890. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7891. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7892. len = intersections.length;
  7893. subMeshes = intersections.data;
  7894. } else {
  7895. subMeshes = this.subMeshes;
  7896. len = subMeshes.length;
  7897. }
  7898. for (var index = 0; index < len; index++) {
  7899. var subMesh = subMeshes[index];
  7900. if (len > 1 && !subMesh.canIntersects(ray))
  7901. continue;
  7902. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7903. if (currentIntersectInfo) {
  7904. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7905. intersectInfo = currentIntersectInfo;
  7906. if (fastCheck) {
  7907. break;
  7908. }
  7909. }
  7910. }
  7911. }
  7912. if (intersectInfo) {
  7913. var world = this.getWorldMatrix();
  7914. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7915. var direction = ray.direction.clone();
  7916. direction.normalize();
  7917. direction = direction.scale(intersectInfo.distance);
  7918. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7919. var pickedPoint = worldOrigin.add(worldDirection);
  7920. pickingInfo.hit = true;
  7921. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7922. pickingInfo.pickedPoint = pickedPoint;
  7923. pickingInfo.pickedMesh = this;
  7924. pickingInfo.bu = intersectInfo.bu;
  7925. pickingInfo.bv = intersectInfo.bv;
  7926. pickingInfo.faceId = intersectInfo.faceId;
  7927. return pickingInfo;
  7928. }
  7929. return pickingInfo;
  7930. };
  7931. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7932. return null;
  7933. };
  7934. AbstractMesh.prototype.releaseSubMeshes = function () {
  7935. if (this.subMeshes) {
  7936. while (this.subMeshes.length) {
  7937. this.subMeshes[0].dispose();
  7938. }
  7939. } else {
  7940. this.subMeshes = new Array();
  7941. }
  7942. };
  7943. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7944. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7945. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7946. }
  7947. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7948. var other = this._intersectionsInProgress[index];
  7949. var pos = other._intersectionsInProgress.indexOf(this);
  7950. other._intersectionsInProgress.splice(pos, 1);
  7951. }
  7952. this._intersectionsInProgress = [];
  7953. this.releaseSubMeshes();
  7954. var index = this.getScene().meshes.indexOf(this);
  7955. if (index != -1) {
  7956. this.getScene().meshes.splice(index, 1);
  7957. }
  7958. if (!doNotRecurse) {
  7959. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7960. if (this.getScene().particleSystems[index].emitter == this) {
  7961. this.getScene().particleSystems[index].dispose();
  7962. index--;
  7963. }
  7964. }
  7965. var objects = this.getScene().meshes.slice(0);
  7966. for (index = 0; index < objects.length; index++) {
  7967. if (objects[index].parent == this) {
  7968. objects[index].dispose();
  7969. }
  7970. }
  7971. } else {
  7972. for (index = 0; index < this.getScene().meshes.length; index++) {
  7973. var obj = this.getScene().meshes[index];
  7974. if (obj.parent === this) {
  7975. obj.parent = null;
  7976. obj.computeWorldMatrix(true);
  7977. }
  7978. }
  7979. }
  7980. this._isDisposed = true;
  7981. if (this.onDispose) {
  7982. this.onDispose();
  7983. }
  7984. };
  7985. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7986. AbstractMesh._BILLBOARDMODE_X = 1;
  7987. AbstractMesh._BILLBOARDMODE_Y = 2;
  7988. AbstractMesh._BILLBOARDMODE_Z = 4;
  7989. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7990. return AbstractMesh;
  7991. })(BABYLON.Node);
  7992. BABYLON.AbstractMesh = AbstractMesh;
  7993. })(BABYLON || (BABYLON = {}));
  7994. var __extends = this.__extends || function (d, b) {
  7995. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7996. function __() { this.constructor = d; }
  7997. __.prototype = b.prototype;
  7998. d.prototype = new __();
  7999. };
  8000. var BABYLON;
  8001. (function (BABYLON) {
  8002. var _InstancesBatch = (function () {
  8003. function _InstancesBatch() {
  8004. this.mustReturn = false;
  8005. this.visibleInstances = new Array();
  8006. this.renderSelf = new Array();
  8007. }
  8008. return _InstancesBatch;
  8009. })();
  8010. BABYLON._InstancesBatch = _InstancesBatch;
  8011. var Mesh = (function (_super) {
  8012. __extends(Mesh, _super);
  8013. function Mesh(name, scene) {
  8014. _super.call(this, name, scene);
  8015. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8016. this.instances = new Array();
  8017. this._onBeforeRenderCallbacks = new Array();
  8018. this._onAfterRenderCallbacks = new Array();
  8019. this._visibleInstances = {};
  8020. this._renderIdForInstances = new Array();
  8021. this._batchCache = new _InstancesBatch();
  8022. this._instancesBufferSize = 32 * 16 * 4;
  8023. }
  8024. Mesh.prototype.getTotalVertices = function () {
  8025. if (!this._geometry) {
  8026. return 0;
  8027. }
  8028. return this._geometry.getTotalVertices();
  8029. };
  8030. Mesh.prototype.getVerticesData = function (kind) {
  8031. if (!this._geometry) {
  8032. return null;
  8033. }
  8034. return this._geometry.getVerticesData(kind);
  8035. };
  8036. Mesh.prototype.getVertexBuffer = function (kind) {
  8037. if (!this._geometry) {
  8038. return undefined;
  8039. }
  8040. return this._geometry.getVertexBuffer(kind);
  8041. };
  8042. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8043. if (!this._geometry) {
  8044. if (this._delayInfo) {
  8045. return this._delayInfo.indexOf(kind) !== -1;
  8046. }
  8047. return false;
  8048. }
  8049. return this._geometry.isVerticesDataPresent(kind);
  8050. };
  8051. Mesh.prototype.getVerticesDataKinds = function () {
  8052. if (!this._geometry) {
  8053. var result = [];
  8054. if (this._delayInfo) {
  8055. for (var kind in this._delayInfo) {
  8056. result.push(kind);
  8057. }
  8058. }
  8059. return result;
  8060. }
  8061. return this._geometry.getVerticesDataKinds();
  8062. };
  8063. Mesh.prototype.getTotalIndices = function () {
  8064. if (!this._geometry) {
  8065. return 0;
  8066. }
  8067. return this._geometry.getTotalIndices();
  8068. };
  8069. Mesh.prototype.getIndices = function () {
  8070. if (!this._geometry) {
  8071. return [];
  8072. }
  8073. return this._geometry.getIndices();
  8074. };
  8075. Mesh.prototype.isReady = function () {
  8076. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8077. return false;
  8078. }
  8079. return _super.prototype.isReady.call(this);
  8080. };
  8081. Mesh.prototype.isDisposed = function () {
  8082. return this._isDisposed;
  8083. };
  8084. Mesh.prototype._preActivate = function () {
  8085. var sceneRenderId = this.getScene().getRenderId();
  8086. if (this._preActivateId == sceneRenderId) {
  8087. return;
  8088. }
  8089. this._preActivateId = sceneRenderId;
  8090. this._visibleInstances = null;
  8091. };
  8092. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8093. if (!this._visibleInstances) {
  8094. this._visibleInstances = {};
  8095. this._visibleInstances.defaultRenderId = renderId;
  8096. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8097. }
  8098. if (!this._visibleInstances[renderId]) {
  8099. this._visibleInstances[renderId] = new Array();
  8100. }
  8101. this._visibleInstances[renderId].push(instance);
  8102. };
  8103. Mesh.prototype.refreshBoundingInfo = function () {
  8104. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8105. if (data) {
  8106. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8107. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8108. }
  8109. if (this.subMeshes) {
  8110. for (var index = 0; index < this.subMeshes.length; index++) {
  8111. this.subMeshes[index].refreshBoundingInfo();
  8112. }
  8113. }
  8114. this._updateBoundingInfo();
  8115. };
  8116. Mesh.prototype._createGlobalSubMesh = function () {
  8117. var totalVertices = this.getTotalVertices();
  8118. if (!totalVertices || !this.getIndices()) {
  8119. return null;
  8120. }
  8121. this.releaseSubMeshes();
  8122. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8123. };
  8124. Mesh.prototype.subdivide = function (count) {
  8125. if (count < 1) {
  8126. return;
  8127. }
  8128. var totalIndices = this.getTotalIndices();
  8129. var subdivisionSize = (totalIndices / count) | 0;
  8130. var offset = 0;
  8131. while (subdivisionSize % 3 != 0) {
  8132. subdivisionSize++;
  8133. }
  8134. this.releaseSubMeshes();
  8135. for (var index = 0; index < count; index++) {
  8136. if (offset >= totalIndices) {
  8137. break;
  8138. }
  8139. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8140. offset += subdivisionSize;
  8141. }
  8142. this.synchronizeInstances();
  8143. };
  8144. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  8145. if (kind instanceof Array) {
  8146. var temp = data;
  8147. data = kind;
  8148. kind = temp;
  8149. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8150. }
  8151. if (!this._geometry) {
  8152. var vertexData = new BABYLON.VertexData();
  8153. vertexData.set(data, kind);
  8154. var scene = this.getScene();
  8155. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8156. } else {
  8157. this._geometry.setVerticesData(kind, data, updatable);
  8158. }
  8159. };
  8160. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8161. if (!this._geometry) {
  8162. return;
  8163. }
  8164. if (!makeItUnique) {
  8165. this._geometry.updateVerticesData(kind, data, updateExtends);
  8166. } else {
  8167. this.makeGeometryUnique();
  8168. this.updateVerticesData(kind, data, updateExtends, false);
  8169. }
  8170. };
  8171. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8172. if (!this._geometry) {
  8173. return;
  8174. }
  8175. if (!makeItUnique) {
  8176. this._geometry.updateVerticesDataDirectly(kind, data);
  8177. } else {
  8178. this.makeGeometryUnique();
  8179. this.updateVerticesDataDirectly(kind, data, false);
  8180. }
  8181. };
  8182. Mesh.prototype.makeGeometryUnique = function () {
  8183. if (!this._geometry) {
  8184. return;
  8185. }
  8186. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8187. geometry.applyToMesh(this);
  8188. };
  8189. Mesh.prototype.setIndices = function (indices) {
  8190. if (!this._geometry) {
  8191. var vertexData = new BABYLON.VertexData();
  8192. vertexData.indices = indices;
  8193. var scene = this.getScene();
  8194. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8195. } else {
  8196. this._geometry.setIndices(indices);
  8197. }
  8198. };
  8199. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8200. var engine = this.getScene().getEngine();
  8201. var indexToBind = this._geometry.getIndexBuffer();
  8202. if (wireframe) {
  8203. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8204. }
  8205. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8206. };
  8207. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8208. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8209. return;
  8210. }
  8211. var engine = this.getScene().getEngine();
  8212. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8213. };
  8214. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8215. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8216. return;
  8217. }
  8218. var engine = this.getScene().getEngine();
  8219. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8220. };
  8221. Mesh.prototype.registerBeforeRender = function (func) {
  8222. this._onBeforeRenderCallbacks.push(func);
  8223. };
  8224. Mesh.prototype.unregisterBeforeRender = function (func) {
  8225. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8226. if (index > -1) {
  8227. this._onBeforeRenderCallbacks.splice(index, 1);
  8228. }
  8229. };
  8230. Mesh.prototype.registerAfterRender = function (func) {
  8231. this._onAfterRenderCallbacks.push(func);
  8232. };
  8233. Mesh.prototype.unregisterAfterRender = function (func) {
  8234. var index = this._onAfterRenderCallbacks.indexOf(func);
  8235. if (index > -1) {
  8236. this._onAfterRenderCallbacks.splice(index, 1);
  8237. }
  8238. };
  8239. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8240. var scene = this.getScene();
  8241. this._batchCache.mustReturn = false;
  8242. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8243. this._batchCache.visibleInstances[subMeshId] = null;
  8244. if (this._visibleInstances) {
  8245. var currentRenderId = scene.getRenderId();
  8246. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8247. var selfRenderId = this._renderId;
  8248. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8249. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8250. currentRenderId = this._visibleInstances.defaultRenderId;
  8251. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8252. }
  8253. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8254. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8255. this._batchCache.mustReturn = true;
  8256. return this._batchCache;
  8257. }
  8258. if (currentRenderId !== selfRenderId) {
  8259. this._batchCache.renderSelf[subMeshId] = false;
  8260. }
  8261. }
  8262. this._renderIdForInstances[subMeshId] = currentRenderId;
  8263. }
  8264. return this._batchCache;
  8265. };
  8266. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8267. var matricesCount = this.instances.length + 1;
  8268. var bufferSize = matricesCount * 16 * 4;
  8269. while (this._instancesBufferSize < bufferSize) {
  8270. this._instancesBufferSize *= 2;
  8271. }
  8272. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8273. if (this._worldMatricesInstancesBuffer) {
  8274. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8275. }
  8276. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8277. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8278. }
  8279. var offset = 0;
  8280. var instancesCount = 0;
  8281. var world = this.getWorldMatrix();
  8282. if (batch.renderSelf[subMesh._id]) {
  8283. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8284. offset += 16;
  8285. instancesCount++;
  8286. }
  8287. var visibleInstances = batch.visibleInstances[subMesh._id];
  8288. if (visibleInstances) {
  8289. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8290. var instance = visibleInstances[instanceIndex];
  8291. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8292. offset += 16;
  8293. instancesCount++;
  8294. }
  8295. }
  8296. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8297. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8298. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8299. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8300. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8301. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8302. this._draw(subMesh, !wireFrame, instancesCount);
  8303. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8304. };
  8305. Mesh.prototype.render = function (subMesh) {
  8306. var scene = this.getScene();
  8307. var batch = this._getInstancesRenderList(subMesh._id);
  8308. if (batch.mustReturn) {
  8309. return;
  8310. }
  8311. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8312. return;
  8313. }
  8314. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8315. this._onBeforeRenderCallbacks[callbackIndex]();
  8316. }
  8317. var engine = scene.getEngine();
  8318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8319. var effectiveMaterial = subMesh.getMaterial();
  8320. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8321. return;
  8322. }
  8323. var savedDepthWrite = engine.getDepthWrite();
  8324. if (this.renderOutline) {
  8325. engine.setDepthWrite(false);
  8326. scene.getOutlineRenderer().render(subMesh, batch);
  8327. }
  8328. effectiveMaterial._preBind();
  8329. var effect = effectiveMaterial.getEffect();
  8330. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8331. this._bind(subMesh, effect, wireFrame);
  8332. var world = this.getWorldMatrix();
  8333. effectiveMaterial.bind(world, this);
  8334. if (hardwareInstancedRendering) {
  8335. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8336. } else {
  8337. if (batch.renderSelf[subMesh._id]) {
  8338. this._draw(subMesh, !wireFrame);
  8339. }
  8340. if (batch.visibleInstances[subMesh._id]) {
  8341. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8342. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8343. world = instance.getWorldMatrix();
  8344. effectiveMaterial.bindOnlyWorldMatrix(world);
  8345. this._draw(subMesh, !wireFrame);
  8346. }
  8347. }
  8348. }
  8349. effectiveMaterial.unbind();
  8350. if (this.renderOutline && savedDepthWrite) {
  8351. engine.setDepthWrite(true);
  8352. engine.setColorWrite(false);
  8353. scene.getOutlineRenderer().render(subMesh, batch);
  8354. engine.setColorWrite(true);
  8355. }
  8356. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8357. this._onAfterRenderCallbacks[callbackIndex]();
  8358. }
  8359. };
  8360. Mesh.prototype.getEmittedParticleSystems = function () {
  8361. var results = new Array();
  8362. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8363. var particleSystem = this.getScene().particleSystems[index];
  8364. if (particleSystem.emitter === this) {
  8365. results.push(particleSystem);
  8366. }
  8367. }
  8368. return results;
  8369. };
  8370. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8371. var results = new Array();
  8372. var descendants = this.getDescendants();
  8373. descendants.push(this);
  8374. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8375. var particleSystem = this.getScene().particleSystems[index];
  8376. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8377. results.push(particleSystem);
  8378. }
  8379. }
  8380. return results;
  8381. };
  8382. Mesh.prototype.getChildren = function () {
  8383. var results = [];
  8384. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8385. var mesh = this.getScene().meshes[index];
  8386. if (mesh.parent == this) {
  8387. results.push(mesh);
  8388. }
  8389. }
  8390. return results;
  8391. };
  8392. Mesh.prototype._checkDelayState = function () {
  8393. var _this = this;
  8394. var that = this;
  8395. var scene = this.getScene();
  8396. if (this._geometry) {
  8397. this._geometry.load(scene);
  8398. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8399. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8400. scene._addPendingData(that);
  8401. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8402. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8403. if (data instanceof ArrayBuffer) {
  8404. _this._delayLoadingFunction(data, _this);
  8405. } else {
  8406. _this._delayLoadingFunction(JSON.parse(data), _this);
  8407. }
  8408. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8409. scene._removePendingData(_this);
  8410. }, function () {
  8411. }, scene.database, getBinaryData);
  8412. }
  8413. };
  8414. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8415. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8416. return false;
  8417. }
  8418. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8419. return false;
  8420. }
  8421. this._checkDelayState();
  8422. return true;
  8423. };
  8424. Mesh.prototype.setMaterialByID = function (id) {
  8425. var materials = this.getScene().materials;
  8426. for (var index = 0; index < materials.length; index++) {
  8427. if (materials[index].id == id) {
  8428. this.material = materials[index];
  8429. return;
  8430. }
  8431. }
  8432. var multiMaterials = this.getScene().multiMaterials;
  8433. for (index = 0; index < multiMaterials.length; index++) {
  8434. if (multiMaterials[index].id == id) {
  8435. this.material = multiMaterials[index];
  8436. return;
  8437. }
  8438. }
  8439. };
  8440. Mesh.prototype.getAnimatables = function () {
  8441. var results = [];
  8442. if (this.material) {
  8443. results.push(this.material);
  8444. }
  8445. if (this.skeleton) {
  8446. results.push(this.skeleton);
  8447. }
  8448. return results;
  8449. };
  8450. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8451. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8452. return;
  8453. }
  8454. this._resetPointsArrayCache();
  8455. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8456. var temp = [];
  8457. for (var index = 0; index < data.length; index += 3) {
  8458. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8459. }
  8460. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8461. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8462. return;
  8463. }
  8464. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8465. for (index = 0; index < data.length; index += 3) {
  8466. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8467. }
  8468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8469. };
  8470. Mesh.prototype._resetPointsArrayCache = function () {
  8471. this._positions = null;
  8472. };
  8473. Mesh.prototype._generatePointsArray = function () {
  8474. if (this._positions)
  8475. return true;
  8476. this._positions = [];
  8477. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8478. if (!data) {
  8479. return false;
  8480. }
  8481. for (var index = 0; index < data.length; index += 3) {
  8482. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8483. }
  8484. return true;
  8485. };
  8486. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8487. var result = new BABYLON.Mesh(name, this.getScene());
  8488. this._geometry.applyToMesh(result);
  8489. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8490. result.material = this.material;
  8491. if (newParent) {
  8492. result.parent = newParent;
  8493. }
  8494. if (!doNotCloneChildren) {
  8495. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8496. var mesh = this.getScene().meshes[index];
  8497. if (mesh.parent == this) {
  8498. mesh.clone(mesh.name, result);
  8499. }
  8500. }
  8501. }
  8502. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8503. var system = this.getScene().particleSystems[index];
  8504. if (system.emitter == this) {
  8505. system.clone(system.name, result);
  8506. }
  8507. }
  8508. result.computeWorldMatrix(true);
  8509. return result;
  8510. };
  8511. Mesh.prototype.dispose = function (doNotRecurse) {
  8512. if (this._geometry) {
  8513. this._geometry.releaseForMesh(this, true);
  8514. }
  8515. if (this._worldMatricesInstancesBuffer) {
  8516. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8517. this._worldMatricesInstancesBuffer = null;
  8518. }
  8519. while (this.instances.length) {
  8520. this.instances[0].dispose();
  8521. }
  8522. _super.prototype.dispose.call(this, doNotRecurse);
  8523. };
  8524. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8525. var _this = this;
  8526. var scene = this.getScene();
  8527. var onload = function (img) {
  8528. var canvas = document.createElement("canvas");
  8529. var context = canvas.getContext("2d");
  8530. var heightMapWidth = img.width;
  8531. var heightMapHeight = img.height;
  8532. canvas.width = heightMapWidth;
  8533. canvas.height = heightMapHeight;
  8534. context.drawImage(img, 0, 0);
  8535. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8536. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8537. };
  8538. BABYLON.Tools.LoadImage(url, onload, function () {
  8539. }, scene.database);
  8540. };
  8541. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8543. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8544. return;
  8545. }
  8546. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8547. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8548. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8549. var position = BABYLON.Vector3.Zero();
  8550. var normal = BABYLON.Vector3.Zero();
  8551. var uv = BABYLON.Vector2.Zero();
  8552. for (var index = 0; index < positions.length; index += 3) {
  8553. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8554. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8555. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8556. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8557. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8558. var pos = (u + v * heightMapWidth) * 4;
  8559. var r = buffer[pos] / 255.0;
  8560. var g = buffer[pos + 1] / 255.0;
  8561. var b = buffer[pos + 2] / 255.0;
  8562. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8563. normal.normalize();
  8564. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8565. position = position.add(normal);
  8566. position.toArray(positions, index);
  8567. }
  8568. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8569. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8570. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8571. };
  8572. Mesh.prototype.convertToFlatShadedMesh = function () {
  8573. var kinds = this.getVerticesDataKinds();
  8574. var vbs = [];
  8575. var data = [];
  8576. var newdata = [];
  8577. var updatableNormals = false;
  8578. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8579. var kind = kinds[kindIndex];
  8580. var vertexBuffer = this.getVertexBuffer(kind);
  8581. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8582. updatableNormals = vertexBuffer.isUpdatable();
  8583. kinds.splice(kindIndex, 1);
  8584. kindIndex--;
  8585. continue;
  8586. }
  8587. vbs[kind] = vertexBuffer;
  8588. data[kind] = vbs[kind].getData();
  8589. newdata[kind] = [];
  8590. }
  8591. var previousSubmeshes = this.subMeshes.slice(0);
  8592. var indices = this.getIndices();
  8593. var totalIndices = this.getTotalIndices();
  8594. for (index = 0; index < totalIndices; index++) {
  8595. var vertexIndex = indices[index];
  8596. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8597. kind = kinds[kindIndex];
  8598. var stride = vbs[kind].getStrideSize();
  8599. for (var offset = 0; offset < stride; offset++) {
  8600. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8601. }
  8602. }
  8603. }
  8604. var normals = [];
  8605. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8606. for (var index = 0; index < totalIndices; index += 3) {
  8607. indices[index] = index;
  8608. indices[index + 1] = index + 1;
  8609. indices[index + 2] = index + 2;
  8610. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8611. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8612. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8613. var p1p2 = p1.subtract(p2);
  8614. var p3p2 = p3.subtract(p2);
  8615. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8616. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8617. normals.push(normal.x);
  8618. normals.push(normal.y);
  8619. normals.push(normal.z);
  8620. }
  8621. }
  8622. this.setIndices(indices);
  8623. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8624. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8625. kind = kinds[kindIndex];
  8626. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8627. }
  8628. this.releaseSubMeshes();
  8629. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8630. var previousOne = previousSubmeshes[submeshIndex];
  8631. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8632. }
  8633. this.synchronizeInstances();
  8634. };
  8635. Mesh.prototype.createInstance = function (name) {
  8636. return new BABYLON.InstancedMesh(name, this);
  8637. };
  8638. Mesh.prototype.synchronizeInstances = function () {
  8639. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8640. var instance = this.instances[instanceIndex];
  8641. instance._syncSubMeshes();
  8642. }
  8643. };
  8644. Mesh.CreateBox = function (name, size, scene, updatable) {
  8645. var box = new BABYLON.Mesh(name, scene);
  8646. var vertexData = BABYLON.VertexData.CreateBox(size);
  8647. vertexData.applyToMesh(box, updatable);
  8648. return box;
  8649. };
  8650. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8651. var sphere = new BABYLON.Mesh(name, scene);
  8652. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8653. vertexData.applyToMesh(sphere, updatable);
  8654. return sphere;
  8655. };
  8656. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8657. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8658. if (scene !== undefined) {
  8659. updatable = scene;
  8660. }
  8661. scene = subdivisions;
  8662. subdivisions = 1;
  8663. }
  8664. var cylinder = new BABYLON.Mesh(name, scene);
  8665. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8666. vertexData.applyToMesh(cylinder, updatable);
  8667. return cylinder;
  8668. };
  8669. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8670. var torus = new BABYLON.Mesh(name, scene);
  8671. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8672. vertexData.applyToMesh(torus, updatable);
  8673. return torus;
  8674. };
  8675. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8676. var torusKnot = new BABYLON.Mesh(name, scene);
  8677. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8678. vertexData.applyToMesh(torusKnot, updatable);
  8679. return torusKnot;
  8680. };
  8681. Mesh.CreateLines = function (name, points, scene, updatable) {
  8682. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8683. var vertexData = BABYLON.VertexData.CreateLines(points);
  8684. vertexData.applyToMesh(lines, updatable);
  8685. return lines;
  8686. };
  8687. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8688. var plane = new BABYLON.Mesh(name, scene);
  8689. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8690. vertexData.applyToMesh(plane, updatable);
  8691. return plane;
  8692. };
  8693. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8694. var ground = new BABYLON.GroundMesh(name, scene);
  8695. ground._setReady(false);
  8696. ground._subdivisions = subdivisions;
  8697. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8698. vertexData.applyToMesh(ground, updatable);
  8699. ground._setReady(true);
  8700. return ground;
  8701. };
  8702. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8703. var tiledGround = new BABYLON.Mesh(name, scene);
  8704. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8705. vertexData.applyToMesh(tiledGround, updatable);
  8706. return tiledGround;
  8707. };
  8708. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8709. var ground = new BABYLON.GroundMesh(name, scene);
  8710. ground._subdivisions = subdivisions;
  8711. ground._setReady(false);
  8712. var onload = function (img) {
  8713. var canvas = document.createElement("canvas");
  8714. var context = canvas.getContext("2d");
  8715. var heightMapWidth = img.width;
  8716. var heightMapHeight = img.height;
  8717. canvas.width = heightMapWidth;
  8718. canvas.height = heightMapHeight;
  8719. context.drawImage(img, 0, 0);
  8720. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8721. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8722. vertexData.applyToMesh(ground, updatable);
  8723. ground._setReady(true);
  8724. };
  8725. BABYLON.Tools.LoadImage(url, onload, function () {
  8726. }, scene.database);
  8727. return ground;
  8728. };
  8729. Mesh.MinMax = function (meshes) {
  8730. var minVector = null;
  8731. var maxVector = null;
  8732. for (var i in meshes) {
  8733. var mesh = meshes[i];
  8734. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8735. if (!minVector) {
  8736. minVector = boundingBox.minimumWorld;
  8737. maxVector = boundingBox.maximumWorld;
  8738. continue;
  8739. }
  8740. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8741. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8742. }
  8743. return {
  8744. min: minVector,
  8745. max: maxVector
  8746. };
  8747. };
  8748. Mesh.Center = function (meshesOrMinMaxVector) {
  8749. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8750. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8751. };
  8752. return Mesh;
  8753. })(BABYLON.AbstractMesh);
  8754. BABYLON.Mesh = Mesh;
  8755. })(BABYLON || (BABYLON = {}));
  8756. var __extends = this.__extends || function (d, b) {
  8757. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8758. function __() { this.constructor = d; }
  8759. __.prototype = b.prototype;
  8760. d.prototype = new __();
  8761. };
  8762. var BABYLON;
  8763. (function (BABYLON) {
  8764. var GroundMesh = (function (_super) {
  8765. __extends(GroundMesh, _super);
  8766. function GroundMesh(name, scene) {
  8767. _super.call(this, name, scene);
  8768. this.generateOctree = false;
  8769. this._worldInverse = new BABYLON.Matrix();
  8770. }
  8771. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8772. get: function () {
  8773. return this._subdivisions;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. GroundMesh.prototype.optimize = function (chunksCount) {
  8779. this.subdivide(this._subdivisions);
  8780. this.createOrUpdateSubmeshesOctree(32);
  8781. };
  8782. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8783. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8784. this.getWorldMatrix().invertToRef(this._worldInverse);
  8785. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8786. var pickInfo = this.intersects(ray);
  8787. if (pickInfo.hit) {
  8788. return pickInfo.pickedPoint.y;
  8789. }
  8790. return 0;
  8791. };
  8792. return GroundMesh;
  8793. })(BABYLON.Mesh);
  8794. BABYLON.GroundMesh = GroundMesh;
  8795. })(BABYLON || (BABYLON = {}));
  8796. var __extends = this.__extends || function (d, b) {
  8797. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8798. function __() { this.constructor = d; }
  8799. __.prototype = b.prototype;
  8800. d.prototype = new __();
  8801. };
  8802. var BABYLON;
  8803. (function (BABYLON) {
  8804. var InstancedMesh = (function (_super) {
  8805. __extends(InstancedMesh, _super);
  8806. function InstancedMesh(name, source) {
  8807. _super.call(this, name, source.getScene());
  8808. source.instances.push(this);
  8809. this._sourceMesh = source;
  8810. this.position.copyFrom(source.position);
  8811. this.rotation.copyFrom(source.rotation);
  8812. this.scaling.copyFrom(source.scaling);
  8813. if (source.rotationQuaternion) {
  8814. this.rotationQuaternion = source.rotationQuaternion.clone();
  8815. }
  8816. this.infiniteDistance = source.infiniteDistance;
  8817. this.setPivotMatrix(source.getPivotMatrix());
  8818. this.refreshBoundingInfo();
  8819. this._syncSubMeshes();
  8820. }
  8821. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8822. get: function () {
  8823. return this._sourceMesh.receiveShadows;
  8824. },
  8825. enumerable: true,
  8826. configurable: true
  8827. });
  8828. Object.defineProperty(InstancedMesh.prototype, "material", {
  8829. get: function () {
  8830. return this._sourceMesh.material;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8836. get: function () {
  8837. return this._sourceMesh.visibility;
  8838. },
  8839. enumerable: true,
  8840. configurable: true
  8841. });
  8842. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8843. get: function () {
  8844. return this._sourceMesh.skeleton;
  8845. },
  8846. enumerable: true,
  8847. configurable: true
  8848. });
  8849. InstancedMesh.prototype.getTotalVertices = function () {
  8850. return this._sourceMesh.getTotalVertices();
  8851. };
  8852. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8853. get: function () {
  8854. return this._sourceMesh;
  8855. },
  8856. enumerable: true,
  8857. configurable: true
  8858. });
  8859. InstancedMesh.prototype.getVerticesData = function (kind) {
  8860. return this._sourceMesh.getVerticesData(kind);
  8861. };
  8862. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8863. return this._sourceMesh.isVerticesDataPresent(kind);
  8864. };
  8865. InstancedMesh.prototype.getIndices = function () {
  8866. return this._sourceMesh.getIndices();
  8867. };
  8868. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8869. get: function () {
  8870. return this._sourceMesh._positions;
  8871. },
  8872. enumerable: true,
  8873. configurable: true
  8874. });
  8875. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8876. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8877. if (data) {
  8878. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8879. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8880. }
  8881. this._updateBoundingInfo();
  8882. };
  8883. InstancedMesh.prototype._preActivate = function () {
  8884. this.sourceMesh._preActivate();
  8885. };
  8886. InstancedMesh.prototype._activate = function (renderId) {
  8887. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8888. };
  8889. InstancedMesh.prototype._syncSubMeshes = function () {
  8890. this.releaseSubMeshes();
  8891. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8892. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8893. }
  8894. };
  8895. InstancedMesh.prototype._generatePointsArray = function () {
  8896. return this._sourceMesh._generatePointsArray();
  8897. };
  8898. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8899. var result = this._sourceMesh.createInstance(name);
  8900. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8901. this.refreshBoundingInfo();
  8902. if (newParent) {
  8903. result.parent = newParent;
  8904. }
  8905. if (!doNotCloneChildren) {
  8906. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8907. var mesh = this.getScene().meshes[index];
  8908. if (mesh.parent == this) {
  8909. mesh.clone(mesh.name, result);
  8910. }
  8911. }
  8912. }
  8913. result.computeWorldMatrix(true);
  8914. return result;
  8915. };
  8916. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8917. var index = this._sourceMesh.instances.indexOf(this);
  8918. this._sourceMesh.instances.splice(index, 1);
  8919. _super.prototype.dispose.call(this, doNotRecurse);
  8920. };
  8921. return InstancedMesh;
  8922. })(BABYLON.AbstractMesh);
  8923. BABYLON.InstancedMesh = InstancedMesh;
  8924. })(BABYLON || (BABYLON = {}));
  8925. var BABYLON;
  8926. (function (BABYLON) {
  8927. var SubMesh = (function () {
  8928. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8929. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8930. this.materialIndex = materialIndex;
  8931. this.verticesStart = verticesStart;
  8932. this.verticesCount = verticesCount;
  8933. this.indexStart = indexStart;
  8934. this.indexCount = indexCount;
  8935. this._renderId = 0;
  8936. this._mesh = mesh;
  8937. this._renderingMesh = renderingMesh || mesh;
  8938. mesh.subMeshes.push(this);
  8939. this._id = mesh.subMeshes.length - 1;
  8940. if (createBoundingBox) {
  8941. this.refreshBoundingInfo();
  8942. }
  8943. }
  8944. SubMesh.prototype.getBoundingInfo = function () {
  8945. return this._boundingInfo;
  8946. };
  8947. SubMesh.prototype.getMesh = function () {
  8948. return this._mesh;
  8949. };
  8950. SubMesh.prototype.getRenderingMesh = function () {
  8951. return this._renderingMesh;
  8952. };
  8953. SubMesh.prototype.getMaterial = function () {
  8954. var rootMaterial = this._renderingMesh.material;
  8955. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8956. var multiMaterial = rootMaterial;
  8957. return multiMaterial.getSubMaterial(this.materialIndex);
  8958. }
  8959. if (!rootMaterial) {
  8960. return this._mesh.getScene().defaultMaterial;
  8961. }
  8962. return rootMaterial;
  8963. };
  8964. SubMesh.prototype.refreshBoundingInfo = function () {
  8965. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8966. if (!data) {
  8967. this._boundingInfo = this._mesh._boundingInfo;
  8968. return;
  8969. }
  8970. var indices = this._renderingMesh.getIndices();
  8971. var extend;
  8972. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8973. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8974. } else {
  8975. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8976. }
  8977. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8978. };
  8979. SubMesh.prototype._checkCollision = function (collider) {
  8980. return this._boundingInfo._checkCollision(collider);
  8981. };
  8982. SubMesh.prototype.updateBoundingInfo = function (world) {
  8983. if (!this._boundingInfo) {
  8984. this.refreshBoundingInfo();
  8985. }
  8986. this._boundingInfo._update(world);
  8987. };
  8988. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8989. return this._boundingInfo.isInFrustum(frustumPlanes);
  8990. };
  8991. SubMesh.prototype.render = function () {
  8992. this._renderingMesh.render(this);
  8993. };
  8994. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8995. if (!this._linesIndexBuffer) {
  8996. var linesIndices = [];
  8997. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8998. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8999. }
  9000. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9001. this.linesIndexCount = linesIndices.length;
  9002. }
  9003. return this._linesIndexBuffer;
  9004. };
  9005. SubMesh.prototype.canIntersects = function (ray) {
  9006. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9007. };
  9008. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9009. var intersectInfo = null;
  9010. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9011. var p0 = positions[indices[index]];
  9012. var p1 = positions[indices[index + 1]];
  9013. var p2 = positions[indices[index + 2]];
  9014. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9015. if (currentIntersectInfo) {
  9016. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9017. intersectInfo = currentIntersectInfo;
  9018. intersectInfo.faceId = index / 3;
  9019. if (fastCheck) {
  9020. break;
  9021. }
  9022. }
  9023. }
  9024. }
  9025. return intersectInfo;
  9026. };
  9027. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9028. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9029. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9030. return result;
  9031. };
  9032. SubMesh.prototype.dispose = function () {
  9033. if (this._linesIndexBuffer) {
  9034. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9035. this._linesIndexBuffer = null;
  9036. }
  9037. var index = this._mesh.subMeshes.indexOf(this);
  9038. this._mesh.subMeshes.splice(index, 1);
  9039. };
  9040. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9041. var minVertexIndex = Number.MAX_VALUE;
  9042. var maxVertexIndex = -Number.MAX_VALUE;
  9043. renderingMesh = renderingMesh || mesh;
  9044. var indices = renderingMesh.getIndices();
  9045. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9046. var vertexIndex = indices[index];
  9047. if (vertexIndex < minVertexIndex)
  9048. minVertexIndex = vertexIndex;
  9049. if (vertexIndex > maxVertexIndex)
  9050. maxVertexIndex = vertexIndex;
  9051. }
  9052. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9053. };
  9054. return SubMesh;
  9055. })();
  9056. BABYLON.SubMesh = SubMesh;
  9057. })(BABYLON || (BABYLON = {}));
  9058. var BABYLON;
  9059. (function (BABYLON) {
  9060. var BaseTexture = (function () {
  9061. function BaseTexture(scene) {
  9062. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9063. this.hasAlpha = false;
  9064. this.getAlphaFromRGB = false;
  9065. this.level = 1;
  9066. this.isCube = false;
  9067. this.isRenderTarget = false;
  9068. this.animations = new Array();
  9069. this.coordinatesIndex = 0;
  9070. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9071. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9072. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9073. this.anisotropicFilteringLevel = 4;
  9074. this._scene = scene;
  9075. this._scene.textures.push(this);
  9076. }
  9077. BaseTexture.prototype.getScene = function () {
  9078. return this._scene;
  9079. };
  9080. BaseTexture.prototype.getTextureMatrix = function () {
  9081. return null;
  9082. };
  9083. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9084. return null;
  9085. };
  9086. BaseTexture.prototype.getInternalTexture = function () {
  9087. return this._texture;
  9088. };
  9089. BaseTexture.prototype.isReady = function () {
  9090. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9091. return true;
  9092. }
  9093. if (this._texture) {
  9094. return this._texture.isReady;
  9095. }
  9096. return false;
  9097. };
  9098. BaseTexture.prototype.getSize = function () {
  9099. if (this._texture._width) {
  9100. return { width: this._texture._width, height: this._texture._height };
  9101. }
  9102. if (this._texture._size) {
  9103. return { width: this._texture._size, height: this._texture._size };
  9104. }
  9105. return { width: 0, height: 0 };
  9106. };
  9107. BaseTexture.prototype.getBaseSize = function () {
  9108. if (!this.isReady())
  9109. return { width: 0, height: 0 };
  9110. if (this._texture._size) {
  9111. return { width: this._texture._size, height: this._texture._size };
  9112. }
  9113. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9114. };
  9115. BaseTexture.prototype.scale = function (ratio) {
  9116. };
  9117. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9118. get: function () {
  9119. return false;
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9125. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9126. for (var index = 0; index < texturesCache.length; index++) {
  9127. var texturesCacheEntry = texturesCache[index];
  9128. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9129. texturesCache.splice(index, 1);
  9130. return;
  9131. }
  9132. }
  9133. };
  9134. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9135. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9136. for (var index = 0; index < texturesCache.length; index++) {
  9137. var texturesCacheEntry = texturesCache[index];
  9138. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9139. texturesCacheEntry.references++;
  9140. return texturesCacheEntry;
  9141. }
  9142. }
  9143. return null;
  9144. };
  9145. BaseTexture.prototype.delayLoad = function () {
  9146. };
  9147. BaseTexture.prototype.releaseInternalTexture = function () {
  9148. if (!this._texture) {
  9149. return;
  9150. }
  9151. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9152. this._texture.references--;
  9153. if (this._texture.references == 0) {
  9154. var index = texturesCache.indexOf(this._texture);
  9155. texturesCache.splice(index, 1);
  9156. this._scene.getEngine()._releaseTexture(this._texture);
  9157. delete this._texture;
  9158. }
  9159. };
  9160. BaseTexture.prototype.clone = function () {
  9161. return null;
  9162. };
  9163. BaseTexture.prototype.dispose = function () {
  9164. var index = this._scene.textures.indexOf(this);
  9165. if (index >= 0) {
  9166. this._scene.textures.splice(index, 1);
  9167. }
  9168. if (this._texture === undefined) {
  9169. return;
  9170. }
  9171. this.releaseInternalTexture();
  9172. if (this.onDispose) {
  9173. this.onDispose();
  9174. }
  9175. };
  9176. return BaseTexture;
  9177. })();
  9178. BABYLON.BaseTexture = BaseTexture;
  9179. })(BABYLON || (BABYLON = {}));
  9180. var BABYLON;
  9181. (function (BABYLON) {
  9182. var RenderingGroup = (function () {
  9183. function RenderingGroup(index, scene) {
  9184. this.index = index;
  9185. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9186. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9187. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9188. this._scene = scene;
  9189. }
  9190. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9191. if (customRenderFunction) {
  9192. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9193. return true;
  9194. }
  9195. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9196. return false;
  9197. }
  9198. var engine = this._scene.getEngine();
  9199. var subIndex;
  9200. var submesh;
  9201. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9202. submesh = this._opaqueSubMeshes.data[subIndex];
  9203. this._activeVertices += submesh.verticesCount;
  9204. submesh.render();
  9205. }
  9206. engine.setAlphaTesting(true);
  9207. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9208. submesh = this._alphaTestSubMeshes.data[subIndex];
  9209. this._activeVertices += submesh.verticesCount;
  9210. submesh.render();
  9211. }
  9212. engine.setAlphaTesting(false);
  9213. if (beforeTransparents) {
  9214. beforeTransparents();
  9215. }
  9216. if (this._transparentSubMeshes.length) {
  9217. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9218. submesh = this._transparentSubMeshes.data[subIndex];
  9219. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9220. }
  9221. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9222. sortedArray.sort(function (a, b) {
  9223. if (a._distanceToCamera < b._distanceToCamera) {
  9224. return 1;
  9225. }
  9226. if (a._distanceToCamera > b._distanceToCamera) {
  9227. return -1;
  9228. }
  9229. return 0;
  9230. });
  9231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9232. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9233. submesh = sortedArray[subIndex];
  9234. this._activeVertices += submesh.verticesCount;
  9235. submesh.render();
  9236. }
  9237. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9238. }
  9239. return true;
  9240. };
  9241. RenderingGroup.prototype.prepare = function () {
  9242. this._opaqueSubMeshes.reset();
  9243. this._transparentSubMeshes.reset();
  9244. this._alphaTestSubMeshes.reset();
  9245. };
  9246. RenderingGroup.prototype.dispatch = function (subMesh) {
  9247. var material = subMesh.getMaterial();
  9248. var mesh = subMesh.getMesh();
  9249. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9250. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9251. this._transparentSubMeshes.push(subMesh);
  9252. }
  9253. } else if (material.needAlphaTesting()) {
  9254. this._alphaTestSubMeshes.push(subMesh);
  9255. } else {
  9256. this._opaqueSubMeshes.push(subMesh);
  9257. }
  9258. };
  9259. return RenderingGroup;
  9260. })();
  9261. BABYLON.RenderingGroup = RenderingGroup;
  9262. })(BABYLON || (BABYLON = {}));
  9263. var BABYLON;
  9264. (function (BABYLON) {
  9265. var RenderingManager = (function () {
  9266. function RenderingManager(scene) {
  9267. this._renderingGroups = new Array();
  9268. this._scene = scene;
  9269. }
  9270. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9271. if (this._scene._activeParticleSystems.length === 0) {
  9272. return;
  9273. }
  9274. var beforeParticlesDate = BABYLON.Tools.Now;
  9275. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9276. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9277. if (particleSystem.renderingGroupId !== index) {
  9278. continue;
  9279. }
  9280. this._clearDepthBuffer();
  9281. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9282. this._scene._activeParticles += particleSystem.render();
  9283. }
  9284. }
  9285. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9286. };
  9287. RenderingManager.prototype._renderSprites = function (index) {
  9288. if (this._scene.spriteManagers.length === 0) {
  9289. return;
  9290. }
  9291. var beforeSpritessDate = BABYLON.Tools.Now;
  9292. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9293. var spriteManager = this._scene.spriteManagers[id];
  9294. if (spriteManager.renderingGroupId === index) {
  9295. this._clearDepthBuffer();
  9296. spriteManager.render();
  9297. }
  9298. }
  9299. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9300. };
  9301. RenderingManager.prototype._clearDepthBuffer = function () {
  9302. if (this._depthBufferAlreadyCleaned) {
  9303. return;
  9304. }
  9305. this._scene.getEngine().clear(0, false, true);
  9306. this._depthBufferAlreadyCleaned = true;
  9307. };
  9308. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9309. var _this = this;
  9310. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9311. this._depthBufferAlreadyCleaned = false;
  9312. var renderingGroup = this._renderingGroups[index];
  9313. if (renderingGroup) {
  9314. this._clearDepthBuffer();
  9315. if (!renderingGroup.render(customRenderFunction, function () {
  9316. if (renderSprites) {
  9317. _this._renderSprites(index);
  9318. }
  9319. })) {
  9320. this._renderingGroups.splice(index, 1);
  9321. }
  9322. } else if (renderSprites) {
  9323. this._renderSprites(index);
  9324. }
  9325. if (renderParticles) {
  9326. this._renderParticles(index, activeMeshes);
  9327. }
  9328. }
  9329. };
  9330. RenderingManager.prototype.reset = function () {
  9331. for (var index in this._renderingGroups) {
  9332. var renderingGroup = this._renderingGroups[index];
  9333. renderingGroup.prepare();
  9334. }
  9335. };
  9336. RenderingManager.prototype.dispatch = function (subMesh) {
  9337. var mesh = subMesh.getMesh();
  9338. var renderingGroupId = mesh.renderingGroupId || 0;
  9339. if (!this._renderingGroups[renderingGroupId]) {
  9340. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9341. }
  9342. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9343. };
  9344. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9345. return RenderingManager;
  9346. })();
  9347. BABYLON.RenderingManager = RenderingManager;
  9348. })(BABYLON || (BABYLON = {}));
  9349. var __extends = this.__extends || function (d, b) {
  9350. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9351. function __() { this.constructor = d; }
  9352. __.prototype = b.prototype;
  9353. d.prototype = new __();
  9354. };
  9355. var BABYLON;
  9356. (function (BABYLON) {
  9357. var Texture = (function (_super) {
  9358. __extends(Texture, _super);
  9359. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9360. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9361. if (typeof onLoad === "undefined") { onLoad = null; }
  9362. if (typeof onError === "undefined") { onError = null; }
  9363. if (typeof buffer === "undefined") { buffer = null; }
  9364. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9365. _super.call(this, scene);
  9366. this.uOffset = 0;
  9367. this.vOffset = 0;
  9368. this.uScale = 1.0;
  9369. this.vScale = 1.0;
  9370. this.uAng = 0;
  9371. this.vAng = 0;
  9372. this.wAng = 0;
  9373. this.name = url;
  9374. this.url = url;
  9375. this._noMipmap = noMipmap;
  9376. this._invertY = invertY;
  9377. this._samplingMode = samplingMode;
  9378. this._buffer = buffer;
  9379. this._deleteBuffer = deleteBuffer;
  9380. if (!url) {
  9381. return;
  9382. }
  9383. this._texture = this._getFromCache(url, noMipmap);
  9384. if (!this._texture) {
  9385. if (!scene.useDelayedTextureLoading) {
  9386. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9387. if (deleteBuffer) {
  9388. delete this._buffer;
  9389. }
  9390. } else {
  9391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9392. }
  9393. }
  9394. }
  9395. Texture.prototype.delayLoad = function () {
  9396. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9397. return;
  9398. }
  9399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9400. this._texture = this._getFromCache(this.url, this._noMipmap);
  9401. if (!this._texture) {
  9402. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9403. if (this._deleteBuffer) {
  9404. delete this._buffer;
  9405. }
  9406. }
  9407. };
  9408. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9409. x -= this.uOffset + 0.5;
  9410. y -= this.vOffset + 0.5;
  9411. z -= 0.5;
  9412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9413. t.x *= this.uScale;
  9414. t.y *= this.vScale;
  9415. t.x += 0.5;
  9416. t.y += 0.5;
  9417. t.z += 0.5;
  9418. };
  9419. Texture.prototype.getTextureMatrix = function () {
  9420. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  9421. return this._cachedTextureMatrix;
  9422. }
  9423. this._cachedUOffset = this.uOffset;
  9424. this._cachedVOffset = this.vOffset;
  9425. this._cachedUScale = this.uScale;
  9426. this._cachedVScale = this.vScale;
  9427. this._cachedUAng = this.uAng;
  9428. this._cachedVAng = this.vAng;
  9429. this._cachedWAng = this.wAng;
  9430. if (!this._cachedTextureMatrix) {
  9431. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9432. this._rowGenerationMatrix = new BABYLON.Matrix();
  9433. this._t0 = BABYLON.Vector3.Zero();
  9434. this._t1 = BABYLON.Vector3.Zero();
  9435. this._t2 = BABYLON.Vector3.Zero();
  9436. }
  9437. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9438. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9439. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9440. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9441. this._t1.subtractInPlace(this._t0);
  9442. this._t2.subtractInPlace(this._t0);
  9443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9444. this._cachedTextureMatrix.m[0] = this._t1.x;
  9445. this._cachedTextureMatrix.m[1] = this._t1.y;
  9446. this._cachedTextureMatrix.m[2] = this._t1.z;
  9447. this._cachedTextureMatrix.m[4] = this._t2.x;
  9448. this._cachedTextureMatrix.m[5] = this._t2.y;
  9449. this._cachedTextureMatrix.m[6] = this._t2.z;
  9450. this._cachedTextureMatrix.m[8] = this._t0.x;
  9451. this._cachedTextureMatrix.m[9] = this._t0.y;
  9452. this._cachedTextureMatrix.m[10] = this._t0.z;
  9453. return this._cachedTextureMatrix;
  9454. };
  9455. Texture.prototype.getReflectionTextureMatrix = function () {
  9456. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9457. return this._cachedTextureMatrix;
  9458. }
  9459. if (!this._cachedTextureMatrix) {
  9460. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9461. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9462. }
  9463. switch (this.coordinatesMode) {
  9464. case BABYLON.Texture.SPHERICAL_MODE:
  9465. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9466. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9467. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9468. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9469. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9470. break;
  9471. case BABYLON.Texture.PLANAR_MODE:
  9472. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9473. this._cachedTextureMatrix[0] = this.uScale;
  9474. this._cachedTextureMatrix[5] = this.vScale;
  9475. this._cachedTextureMatrix[12] = this.uOffset;
  9476. this._cachedTextureMatrix[13] = this.vOffset;
  9477. break;
  9478. case BABYLON.Texture.PROJECTION_MODE:
  9479. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9480. this._projectionModeMatrix.m[0] = 0.5;
  9481. this._projectionModeMatrix.m[5] = -0.5;
  9482. this._projectionModeMatrix.m[10] = 0.0;
  9483. this._projectionModeMatrix.m[12] = 0.5;
  9484. this._projectionModeMatrix.m[13] = 0.5;
  9485. this._projectionModeMatrix.m[14] = 1.0;
  9486. this._projectionModeMatrix.m[15] = 1.0;
  9487. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9488. break;
  9489. default:
  9490. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9491. break;
  9492. }
  9493. return this._cachedTextureMatrix;
  9494. };
  9495. Texture.prototype.clone = function () {
  9496. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9497. newTexture.hasAlpha = this.hasAlpha;
  9498. newTexture.level = this.level;
  9499. newTexture.wrapU = this.wrapU;
  9500. newTexture.wrapV = this.wrapV;
  9501. newTexture.coordinatesIndex = this.coordinatesIndex;
  9502. newTexture.coordinatesMode = this.coordinatesMode;
  9503. newTexture.uOffset = this.uOffset;
  9504. newTexture.vOffset = this.vOffset;
  9505. newTexture.uScale = this.uScale;
  9506. newTexture.vScale = this.vScale;
  9507. newTexture.uAng = this.uAng;
  9508. newTexture.vAng = this.vAng;
  9509. newTexture.wAng = this.wAng;
  9510. return newTexture;
  9511. };
  9512. Texture.NEAREST_SAMPLINGMODE = 1;
  9513. Texture.BILINEAR_SAMPLINGMODE = 2;
  9514. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9515. Texture.EXPLICIT_MODE = 0;
  9516. Texture.SPHERICAL_MODE = 1;
  9517. Texture.PLANAR_MODE = 2;
  9518. Texture.CUBIC_MODE = 3;
  9519. Texture.PROJECTION_MODE = 4;
  9520. Texture.SKYBOX_MODE = 5;
  9521. Texture.CLAMP_ADDRESSMODE = 0;
  9522. Texture.WRAP_ADDRESSMODE = 1;
  9523. Texture.MIRROR_ADDRESSMODE = 2;
  9524. return Texture;
  9525. })(BABYLON.BaseTexture);
  9526. BABYLON.Texture = Texture;
  9527. })(BABYLON || (BABYLON = {}));
  9528. var __extends = this.__extends || function (d, b) {
  9529. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9530. function __() { this.constructor = d; }
  9531. __.prototype = b.prototype;
  9532. d.prototype = new __();
  9533. };
  9534. var BABYLON;
  9535. (function (BABYLON) {
  9536. var CubeTexture = (function (_super) {
  9537. __extends(CubeTexture, _super);
  9538. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9539. _super.call(this, scene);
  9540. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9541. this.name = rootUrl;
  9542. this.url = rootUrl;
  9543. this._noMipmap = noMipmap;
  9544. this.hasAlpha = false;
  9545. this._texture = this._getFromCache(rootUrl, noMipmap);
  9546. if (!extensions) {
  9547. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9548. }
  9549. this._extensions = extensions;
  9550. if (!this._texture) {
  9551. if (!scene.useDelayedTextureLoading) {
  9552. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9553. } else {
  9554. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9555. }
  9556. }
  9557. this.isCube = true;
  9558. this._textureMatrix = BABYLON.Matrix.Identity();
  9559. }
  9560. CubeTexture.prototype.clone = function () {
  9561. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9562. newTexture.level = this.level;
  9563. newTexture.wrapU = this.wrapU;
  9564. newTexture.wrapV = this.wrapV;
  9565. newTexture.coordinatesIndex = this.coordinatesIndex;
  9566. newTexture.coordinatesMode = this.coordinatesMode;
  9567. return newTexture;
  9568. };
  9569. CubeTexture.prototype.delayLoad = function () {
  9570. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9571. return;
  9572. }
  9573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9574. this._texture = this._getFromCache(this.url, this._noMipmap);
  9575. if (!this._texture) {
  9576. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9577. }
  9578. };
  9579. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9580. return this._textureMatrix;
  9581. };
  9582. return CubeTexture;
  9583. })(BABYLON.BaseTexture);
  9584. BABYLON.CubeTexture = CubeTexture;
  9585. })(BABYLON || (BABYLON = {}));
  9586. var __extends = this.__extends || function (d, b) {
  9587. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9588. function __() { this.constructor = d; }
  9589. __.prototype = b.prototype;
  9590. d.prototype = new __();
  9591. };
  9592. var BABYLON;
  9593. (function (BABYLON) {
  9594. var RenderTargetTexture = (function (_super) {
  9595. __extends(RenderTargetTexture, _super);
  9596. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9597. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9598. _super.call(this, null, scene, !generateMipMaps);
  9599. this.renderList = new Array();
  9600. this.renderParticles = true;
  9601. this.renderSprites = false;
  9602. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9603. this._currentRefreshId = -1;
  9604. this._refreshRate = 1;
  9605. this.name = name;
  9606. this.isRenderTarget = true;
  9607. this._size = size;
  9608. this._generateMipMaps = generateMipMaps;
  9609. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9610. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9611. this._renderingManager = new BABYLON.RenderingManager(scene);
  9612. }
  9613. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9614. this._currentRefreshId = -1;
  9615. };
  9616. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9617. get: function () {
  9618. return this._refreshRate;
  9619. },
  9620. set: function (value) {
  9621. this._refreshRate = value;
  9622. this.resetRefreshCounter();
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. RenderTargetTexture.prototype._shouldRender = function () {
  9628. if (this._currentRefreshId === -1) {
  9629. this._currentRefreshId = 1;
  9630. return true;
  9631. }
  9632. if (this.refreshRate == this._currentRefreshId) {
  9633. this._currentRefreshId = 1;
  9634. return true;
  9635. }
  9636. this._currentRefreshId++;
  9637. return false;
  9638. };
  9639. RenderTargetTexture.prototype.getRenderSize = function () {
  9640. return this._size;
  9641. };
  9642. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  9643. get: function () {
  9644. return true;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. RenderTargetTexture.prototype.scale = function (ratio) {
  9650. var newSize = this._size * ratio;
  9651. this.resize(newSize, this._generateMipMaps);
  9652. };
  9653. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9654. this.releaseInternalTexture();
  9655. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9656. };
  9657. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9658. var scene = this.getScene();
  9659. var engine = scene.getEngine();
  9660. if (this._waitingRenderList) {
  9661. this.renderList = [];
  9662. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9663. var id = this._waitingRenderList[index];
  9664. this.renderList.push(scene.getMeshByID(id));
  9665. }
  9666. delete this._waitingRenderList;
  9667. }
  9668. if (!this.renderList) {
  9669. return;
  9670. }
  9671. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9672. engine.bindFramebuffer(this._texture);
  9673. }
  9674. engine.clear(scene.clearColor, true, true);
  9675. this._renderingManager.reset();
  9676. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9677. var mesh = this.renderList[meshIndex];
  9678. if (mesh) {
  9679. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9680. this.resetRefreshCounter();
  9681. continue;
  9682. }
  9683. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9684. mesh._activate(scene.getRenderId());
  9685. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9686. var subMesh = mesh.subMeshes[subIndex];
  9687. scene._activeVertices += subMesh.verticesCount;
  9688. this._renderingManager.dispatch(subMesh);
  9689. }
  9690. }
  9691. }
  9692. }
  9693. if (!this._doNotChangeAspectRatio) {
  9694. scene.updateTransformMatrix(true);
  9695. }
  9696. if (this.onBeforeRender) {
  9697. this.onBeforeRender();
  9698. }
  9699. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9700. if (useCameraPostProcess) {
  9701. scene.postProcessManager._finalizeFrame(false, this._texture);
  9702. }
  9703. if (this.onAfterRender) {
  9704. this.onAfterRender();
  9705. }
  9706. engine.unBindFramebuffer(this._texture);
  9707. if (!this._doNotChangeAspectRatio) {
  9708. scene.updateTransformMatrix(true);
  9709. }
  9710. };
  9711. RenderTargetTexture.prototype.clone = function () {
  9712. var textureSize = this.getSize();
  9713. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9714. newTexture.hasAlpha = this.hasAlpha;
  9715. newTexture.level = this.level;
  9716. newTexture.coordinatesMode = this.coordinatesMode;
  9717. newTexture.renderList = this.renderList.slice(0);
  9718. return newTexture;
  9719. };
  9720. return RenderTargetTexture;
  9721. })(BABYLON.Texture);
  9722. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9723. })(BABYLON || (BABYLON = {}));
  9724. var __extends = this.__extends || function (d, b) {
  9725. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9726. function __() { this.constructor = d; }
  9727. __.prototype = b.prototype;
  9728. d.prototype = new __();
  9729. };
  9730. var BABYLON;
  9731. (function (BABYLON) {
  9732. var ProceduralTexture = (function (_super) {
  9733. __extends(ProceduralTexture, _super);
  9734. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  9735. _super.call(this, null, scene, !generateMipMaps);
  9736. this._currentRefreshId = -1;
  9737. this._refreshRate = 1;
  9738. this._vertexDeclaration = [2];
  9739. this._vertexStrideSize = 2 * 4;
  9740. this._uniforms = new Array();
  9741. this._samplers = new Array();
  9742. this._textures = new Array();
  9743. this._floats = new Array();
  9744. this._floatsArrays = {};
  9745. this._colors3 = new Array();
  9746. this._colors4 = new Array();
  9747. this._vectors2 = new Array();
  9748. this._vectors3 = new Array();
  9749. this._matrices = new Array();
  9750. scene._proceduralTextures.push(this);
  9751. this.name = name;
  9752. this.isRenderTarget = true;
  9753. this._size = size;
  9754. this._generateMipMaps = generateMipMaps;
  9755. this._fragment = fragment;
  9756. this._fallbackTexture = fallbackTexture;
  9757. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9758. var vertices = [];
  9759. vertices.push(1, 1);
  9760. vertices.push(-1, 1);
  9761. vertices.push(-1, -1);
  9762. vertices.push(1, -1);
  9763. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  9764. var indices = [];
  9765. indices.push(0);
  9766. indices.push(1);
  9767. indices.push(2);
  9768. indices.push(0);
  9769. indices.push(2);
  9770. indices.push(3);
  9771. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  9772. }
  9773. ProceduralTexture.prototype.isReady = function () {
  9774. var _this = this;
  9775. var engine = this.getScene().getEngine();
  9776. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  9777. _this.releaseInternalTexture();
  9778. _this._texture = _this._fallbackTexture._texture;
  9779. _this._texture.references++;
  9780. });
  9781. return this._effect.isReady();
  9782. };
  9783. ProceduralTexture.prototype.resetRefreshCounter = function () {
  9784. this._currentRefreshId = -1;
  9785. };
  9786. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  9787. get: function () {
  9788. return this._refreshRate;
  9789. },
  9790. set: function (value) {
  9791. this._refreshRate = value;
  9792. this.resetRefreshCounter();
  9793. },
  9794. enumerable: true,
  9795. configurable: true
  9796. });
  9797. ProceduralTexture.prototype._shouldRender = function () {
  9798. if (!this.isReady() || !this._texture) {
  9799. return false;
  9800. }
  9801. if (this._currentRefreshId === -1) {
  9802. this._currentRefreshId = 1;
  9803. return true;
  9804. }
  9805. if (this.refreshRate == this._currentRefreshId) {
  9806. this._currentRefreshId = 1;
  9807. return true;
  9808. }
  9809. this._currentRefreshId++;
  9810. return false;
  9811. };
  9812. ProceduralTexture.prototype.getRenderSize = function () {
  9813. return this._size;
  9814. };
  9815. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  9816. this.releaseInternalTexture();
  9817. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9818. };
  9819. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  9820. if (this._uniforms.indexOf(uniformName) === -1) {
  9821. this._uniforms.push(uniformName);
  9822. }
  9823. };
  9824. ProceduralTexture.prototype.setTexture = function (name, texture) {
  9825. if (this._samplers.indexOf(name) === -1) {
  9826. this._samplers.push(name);
  9827. }
  9828. this._textures[name] = texture;
  9829. return this;
  9830. };
  9831. ProceduralTexture.prototype.setFloat = function (name, value) {
  9832. this._checkUniform(name);
  9833. this._floats[name] = value;
  9834. return this;
  9835. };
  9836. ProceduralTexture.prototype.setFloats = function (name, value) {
  9837. this._checkUniform(name);
  9838. this._floatsArrays[name] = value;
  9839. return this;
  9840. };
  9841. ProceduralTexture.prototype.setColor3 = function (name, value) {
  9842. this._checkUniform(name);
  9843. this._colors3[name] = value;
  9844. return this;
  9845. };
  9846. ProceduralTexture.prototype.setColor4 = function (name, value) {
  9847. this._checkUniform(name);
  9848. this._colors4[name] = value;
  9849. return this;
  9850. };
  9851. ProceduralTexture.prototype.setVector2 = function (name, value) {
  9852. this._checkUniform(name);
  9853. this._vectors2[name] = value;
  9854. return this;
  9855. };
  9856. ProceduralTexture.prototype.setVector3 = function (name, value) {
  9857. this._checkUniform(name);
  9858. this._vectors3[name] = value;
  9859. return this;
  9860. };
  9861. ProceduralTexture.prototype.setMatrix = function (name, value) {
  9862. this._checkUniform(name);
  9863. this._matrices[name] = value;
  9864. return this;
  9865. };
  9866. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9867. var scene = this.getScene();
  9868. var engine = scene.getEngine();
  9869. engine.bindFramebuffer(this._texture);
  9870. engine.clear(scene.clearColor, true, true);
  9871. engine.enableEffect(this._effect);
  9872. engine.setState(false);
  9873. for (var name in this._textures) {
  9874. this._effect.setTexture(name, this._textures[name]);
  9875. }
  9876. for (name in this._floats) {
  9877. this._effect.setFloat(name, this._floats[name]);
  9878. }
  9879. for (name in this._floatsArrays) {
  9880. this._effect.setArray(name, this._floatsArrays[name]);
  9881. }
  9882. for (name in this._colors3) {
  9883. this._effect.setColor3(name, this._colors3[name]);
  9884. }
  9885. for (name in this._colors4) {
  9886. var color = this._colors4[name];
  9887. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  9888. }
  9889. for (name in this._vectors2) {
  9890. this._effect.setVector2(name, this._vectors2[name]);
  9891. }
  9892. for (name in this._vectors3) {
  9893. this._effect.setVector3(name, this._vectors3[name]);
  9894. }
  9895. for (name in this._matrices) {
  9896. this._effect.setMatrix(name, this._matrices[name]);
  9897. }
  9898. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  9899. engine.draw(true, 0, 6);
  9900. engine.unBindFramebuffer(this._texture);
  9901. };
  9902. ProceduralTexture.prototype.clone = function () {
  9903. var textureSize = this.getSize();
  9904. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  9905. newTexture.hasAlpha = this.hasAlpha;
  9906. newTexture.level = this.level;
  9907. newTexture.coordinatesMode = this.coordinatesMode;
  9908. return newTexture;
  9909. };
  9910. ProceduralTexture.prototype.dispose = function () {
  9911. var index = this.getScene()._proceduralTextures.indexOf(this);
  9912. if (index >= 0) {
  9913. this.getScene()._proceduralTextures.splice(index, 1);
  9914. }
  9915. _super.prototype.dispose.call(this);
  9916. };
  9917. return ProceduralTexture;
  9918. })(BABYLON.Texture);
  9919. BABYLON.ProceduralTexture = ProceduralTexture;
  9920. })(BABYLON || (BABYLON = {}));
  9921. var __extends = this.__extends || function (d, b) {
  9922. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9923. function __() { this.constructor = d; }
  9924. __.prototype = b.prototype;
  9925. d.prototype = new __();
  9926. };
  9927. var BABYLON;
  9928. (function (BABYLON) {
  9929. var WoodProceduralTexture = (function (_super) {
  9930. __extends(WoodProceduralTexture, _super);
  9931. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9932. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  9933. this._ampScale = 0.03;
  9934. this._ringScale = 5;
  9935. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  9936. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  9937. this.updateShaderUniforms();
  9938. this.refreshRate = 0;
  9939. }
  9940. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  9941. this.setFloat("ampScale", this._ampScale);
  9942. this.setFloat("ringScale", this._ringScale);
  9943. this.setColor3("woodColor1", this._woodColor1);
  9944. this.setColor3("woodColor2", this._woodColor2);
  9945. };
  9946. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  9947. get: function () {
  9948. return this._ampScale;
  9949. },
  9950. set: function (value) {
  9951. this._ampScale = value;
  9952. this.updateShaderUniforms();
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  9958. get: function () {
  9959. return this._ringScale;
  9960. },
  9961. set: function (value) {
  9962. this._ringScale = value;
  9963. this.updateShaderUniforms();
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  9969. get: function () {
  9970. return this._woodColor1;
  9971. },
  9972. set: function (value) {
  9973. this._woodColor1 = value;
  9974. this.updateShaderUniforms();
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  9980. get: function () {
  9981. return this._woodColor2;
  9982. },
  9983. set: function (value) {
  9984. this._woodColor2 = value;
  9985. this.updateShaderUniforms();
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. return WoodProceduralTexture;
  9991. })(BABYLON.ProceduralTexture);
  9992. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  9993. var FireProceduralTexture = (function (_super) {
  9994. __extends(FireProceduralTexture, _super);
  9995. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9996. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  9997. this._time = 0.0;
  9998. this._speed = new BABYLON.Vector2(0.5, 0.3);
  9999. this._shift = 1.6;
  10000. this._alpha = 1.0;
  10001. this._autoGenerateTime = true;
  10002. this._fireColors = FireProceduralTexture.RedFireColors;
  10003. this.updateShaderUniforms();
  10004. this.refreshRate = 1;
  10005. }
  10006. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10007. this.setFloat("iGlobalTime", this._time);
  10008. this.setVector2("speed", this._speed);
  10009. this.setFloat("shift", this._shift);
  10010. this.setFloat("alpha", this._alpha);
  10011. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10012. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10013. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10014. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10015. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10016. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10017. };
  10018. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10019. if (this._autoGenerateTime) {
  10020. this._time += this.getScene().getAnimationRatio() * 0.03;
  10021. this.updateShaderUniforms();
  10022. }
  10023. _super.prototype.render.call(this, useCameraPostProcess);
  10024. };
  10025. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10026. get: function () {
  10027. return [
  10028. [0.5, 0.0, 1.0],
  10029. [0.9, 0.0, 1.0],
  10030. [0.2, 0.0, 1.0],
  10031. [1.0, 0.9, 1.0],
  10032. [0.1, 0.1, 1.0],
  10033. [0.9, 0.9, 1.0]
  10034. ];
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10040. get: function () {
  10041. return [
  10042. [0.5, 1.0, 0.0],
  10043. [0.5, 1.0, 0.0],
  10044. [0.3, 0.4, 0.0],
  10045. [0.5, 1.0, 0.0],
  10046. [0.2, 0.0, 0.0],
  10047. [0.5, 1.0, 0.0]
  10048. ];
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10054. get: function () {
  10055. return [
  10056. [0.5, 0.0, 0.1],
  10057. [0.9, 0.0, 0.0],
  10058. [0.2, 0.0, 0.0],
  10059. [1.0, 0.9, 0.0],
  10060. [0.1, 0.1, 0.1],
  10061. [0.9, 0.9, 0.9]
  10062. ];
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10068. get: function () {
  10069. return [
  10070. [0.1, 0.0, 0.5],
  10071. [0.0, 0.0, 0.5],
  10072. [0.1, 0.0, 0.2],
  10073. [0.0, 0.0, 1.0],
  10074. [0.1, 0.2, 0.3],
  10075. [0.0, 0.2, 0.9]
  10076. ];
  10077. },
  10078. enumerable: true,
  10079. configurable: true
  10080. });
  10081. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10082. get: function () {
  10083. return this._fireColors;
  10084. },
  10085. set: function (value) {
  10086. this._fireColors = value;
  10087. this.updateShaderUniforms();
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10093. get: function () {
  10094. return this._time;
  10095. },
  10096. set: function (value) {
  10097. this._time = value;
  10098. this.updateShaderUniforms();
  10099. },
  10100. enumerable: true,
  10101. configurable: true
  10102. });
  10103. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10104. get: function () {
  10105. return this._speed;
  10106. },
  10107. set: function (value) {
  10108. this._speed = value;
  10109. this.updateShaderUniforms();
  10110. },
  10111. enumerable: true,
  10112. configurable: true
  10113. });
  10114. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10115. get: function () {
  10116. return this._shift;
  10117. },
  10118. set: function (value) {
  10119. this._shift = value;
  10120. this.updateShaderUniforms();
  10121. },
  10122. enumerable: true,
  10123. configurable: true
  10124. });
  10125. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10126. get: function () {
  10127. return this._alpha;
  10128. },
  10129. set: function (value) {
  10130. this._alpha = value;
  10131. this.updateShaderUniforms();
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. return FireProceduralTexture;
  10137. })(BABYLON.ProceduralTexture);
  10138. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10139. })(BABYLON || (BABYLON = {}));
  10140. var __extends = this.__extends || function (d, b) {
  10141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10142. function __() { this.constructor = d; }
  10143. __.prototype = b.prototype;
  10144. d.prototype = new __();
  10145. };
  10146. var BABYLON;
  10147. (function (BABYLON) {
  10148. var MirrorTexture = (function (_super) {
  10149. __extends(MirrorTexture, _super);
  10150. function MirrorTexture(name, size, scene, generateMipMaps) {
  10151. var _this = this;
  10152. _super.call(this, name, size, scene, generateMipMaps, true);
  10153. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10154. this._transformMatrix = BABYLON.Matrix.Zero();
  10155. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10156. this.onBeforeRender = function () {
  10157. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10158. _this._savedViewMatrix = scene.getViewMatrix();
  10159. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10160. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10161. scene.clipPlane = _this.mirrorPlane;
  10162. scene.getEngine().cullBackFaces = false;
  10163. };
  10164. this.onAfterRender = function () {
  10165. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10166. scene.getEngine().cullBackFaces = true;
  10167. delete scene.clipPlane;
  10168. };
  10169. }
  10170. MirrorTexture.prototype.clone = function () {
  10171. var textureSize = this.getSize();
  10172. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10173. newTexture.hasAlpha = this.hasAlpha;
  10174. newTexture.level = this.level;
  10175. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10176. newTexture.renderList = this.renderList.slice(0);
  10177. return newTexture;
  10178. };
  10179. return MirrorTexture;
  10180. })(BABYLON.RenderTargetTexture);
  10181. BABYLON.MirrorTexture = MirrorTexture;
  10182. })(BABYLON || (BABYLON = {}));
  10183. var __extends = this.__extends || function (d, b) {
  10184. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10185. function __() { this.constructor = d; }
  10186. __.prototype = b.prototype;
  10187. d.prototype = new __();
  10188. };
  10189. var BABYLON;
  10190. (function (BABYLON) {
  10191. var DynamicTexture = (function (_super) {
  10192. __extends(DynamicTexture, _super);
  10193. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10194. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10195. _super.call(this, null, scene, !generateMipMaps);
  10196. this.name = name;
  10197. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10198. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10199. this._generateMipMaps = generateMipMaps;
  10200. if (options.getContext) {
  10201. this._canvas = options;
  10202. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10203. } else {
  10204. this._canvas = document.createElement("canvas");
  10205. if (options.width) {
  10206. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10207. } else {
  10208. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10209. }
  10210. }
  10211. var textureSize = this.getSize();
  10212. this._canvas.width = textureSize.width;
  10213. this._canvas.height = textureSize.height;
  10214. this._context = this._canvas.getContext("2d");
  10215. }
  10216. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10217. get: function () {
  10218. return true;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. DynamicTexture.prototype.scale = function (ratio) {
  10224. var textureSize = this.getSize();
  10225. textureSize.width *= ratio;
  10226. textureSize.height *= ratio;
  10227. this._canvas.width = textureSize.width;
  10228. this._canvas.height = textureSize.height;
  10229. this.releaseInternalTexture();
  10230. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10231. };
  10232. DynamicTexture.prototype.getContext = function () {
  10233. return this._context;
  10234. };
  10235. DynamicTexture.prototype.update = function (invertY) {
  10236. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10237. };
  10238. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10239. var size = this.getSize();
  10240. if (clearColor) {
  10241. this._context.fillStyle = clearColor;
  10242. this._context.fillRect(0, 0, size.width, size.height);
  10243. }
  10244. this._context.font = font;
  10245. if (x === null) {
  10246. var textSize = this._context.measureText(text);
  10247. x = (size.width - textSize.width) / 2;
  10248. }
  10249. this._context.fillStyle = color;
  10250. this._context.fillText(text, x, y);
  10251. this.update(invertY);
  10252. };
  10253. DynamicTexture.prototype.clone = function () {
  10254. var textureSize = this.getSize();
  10255. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10256. newTexture.hasAlpha = this.hasAlpha;
  10257. newTexture.level = this.level;
  10258. newTexture.wrapU = this.wrapU;
  10259. newTexture.wrapV = this.wrapV;
  10260. return newTexture;
  10261. };
  10262. return DynamicTexture;
  10263. })(BABYLON.Texture);
  10264. BABYLON.DynamicTexture = DynamicTexture;
  10265. })(BABYLON || (BABYLON = {}));
  10266. var __extends = this.__extends || function (d, b) {
  10267. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10268. function __() { this.constructor = d; }
  10269. __.prototype = b.prototype;
  10270. d.prototype = new __();
  10271. };
  10272. var BABYLON;
  10273. (function (BABYLON) {
  10274. var VideoTexture = (function (_super) {
  10275. __extends(VideoTexture, _super);
  10276. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10277. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10278. var _this = this;
  10279. _super.call(this, null, scene, !generateMipMaps, invertY);
  10280. this._autoLaunch = true;
  10281. this.name = name;
  10282. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10283. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10284. var requiredWidth = size.width || size;
  10285. var requiredHeight = size.height || size;
  10286. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10287. var textureSize = this.getSize();
  10288. this.video = document.createElement("video");
  10289. this.video.width = textureSize.width;
  10290. this.video.height = textureSize.height;
  10291. this.video.autoplay = false;
  10292. this.video.loop = true;
  10293. this.video.addEventListener("canplaythrough", function () {
  10294. if (_this._texture) {
  10295. _this._texture.isReady = true;
  10296. }
  10297. });
  10298. urls.forEach(function (url) {
  10299. var source = document.createElement("source");
  10300. source.src = url;
  10301. _this.video.appendChild(source);
  10302. });
  10303. this._lastUpdate = BABYLON.Tools.Now;
  10304. }
  10305. VideoTexture.prototype.update = function () {
  10306. if (this._autoLaunch) {
  10307. this._autoLaunch = false;
  10308. this.video.play();
  10309. }
  10310. var now = BABYLON.Tools.Now;
  10311. if (now - this._lastUpdate < 15) {
  10312. return false;
  10313. }
  10314. this._lastUpdate = now;
  10315. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10316. return true;
  10317. };
  10318. return VideoTexture;
  10319. })(BABYLON.Texture);
  10320. BABYLON.VideoTexture = VideoTexture;
  10321. })(BABYLON || (BABYLON = {}));
  10322. var BABYLON;
  10323. (function (BABYLON) {
  10324. var EffectFallbacks = (function () {
  10325. function EffectFallbacks() {
  10326. this._defines = {};
  10327. this._currentRank = 32;
  10328. this._maxRank = -1;
  10329. }
  10330. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10331. if (!this._defines[rank]) {
  10332. if (rank < this._currentRank) {
  10333. this._currentRank = rank;
  10334. }
  10335. if (rank > this._maxRank) {
  10336. this._maxRank = rank;
  10337. }
  10338. this._defines[rank] = new Array();
  10339. }
  10340. this._defines[rank].push(define);
  10341. };
  10342. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10343. get: function () {
  10344. return this._currentRank <= this._maxRank;
  10345. },
  10346. enumerable: true,
  10347. configurable: true
  10348. });
  10349. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10350. var currentFallbacks = this._defines[this._currentRank];
  10351. for (var index = 0; index < currentFallbacks.length; index++) {
  10352. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10353. }
  10354. this._currentRank++;
  10355. return currentDefines;
  10356. };
  10357. return EffectFallbacks;
  10358. })();
  10359. BABYLON.EffectFallbacks = EffectFallbacks;
  10360. var Effect = (function () {
  10361. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10362. var _this = this;
  10363. this._isReady = false;
  10364. this._compilationError = "";
  10365. this._valueCache = [];
  10366. this._engine = engine;
  10367. this.name = baseName;
  10368. this.defines = defines;
  10369. this._uniformsNames = uniformsNames.concat(samplers);
  10370. this._samplers = samplers;
  10371. this._attributesNames = attributesNames;
  10372. this.onError = onError;
  10373. this.onCompiled = onCompiled;
  10374. var vertexSource;
  10375. var fragmentSource;
  10376. if (baseName.vertexElement) {
  10377. vertexSource = document.getElementById(baseName.vertexElement);
  10378. if (!vertexSource) {
  10379. vertexSource = baseName.vertexElement;
  10380. }
  10381. } else {
  10382. vertexSource = baseName.vertex || baseName;
  10383. }
  10384. if (baseName.fragmentElement) {
  10385. fragmentSource = document.getElementById(baseName.fragmentElement);
  10386. if (!fragmentSource) {
  10387. fragmentSource = baseName.fragmentElement;
  10388. }
  10389. } else {
  10390. fragmentSource = baseName.fragment || baseName;
  10391. }
  10392. this._loadVertexShader(vertexSource, function (vertexCode) {
  10393. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10394. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10395. });
  10396. });
  10397. }
  10398. Effect.prototype.isReady = function () {
  10399. return this._isReady;
  10400. };
  10401. Effect.prototype.getProgram = function () {
  10402. return this._program;
  10403. };
  10404. Effect.prototype.getAttributesNames = function () {
  10405. return this._attributesNames;
  10406. };
  10407. Effect.prototype.getAttributeLocation = function (index) {
  10408. return this._attributes[index];
  10409. };
  10410. Effect.prototype.getAttributeLocationByName = function (name) {
  10411. var index = this._attributesNames.indexOf(name);
  10412. return this._attributes[index];
  10413. };
  10414. Effect.prototype.getAttributesCount = function () {
  10415. return this._attributes.length;
  10416. };
  10417. Effect.prototype.getUniformIndex = function (uniformName) {
  10418. return this._uniformsNames.indexOf(uniformName);
  10419. };
  10420. Effect.prototype.getUniform = function (uniformName) {
  10421. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10422. };
  10423. Effect.prototype.getSamplers = function () {
  10424. return this._samplers;
  10425. };
  10426. Effect.prototype.getCompilationError = function () {
  10427. return this._compilationError;
  10428. };
  10429. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10430. if (vertex instanceof HTMLElement) {
  10431. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10432. callback(vertexCode);
  10433. return;
  10434. }
  10435. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10436. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10437. return;
  10438. }
  10439. var vertexShaderUrl;
  10440. if (vertex[0] === ".") {
  10441. vertexShaderUrl = vertex;
  10442. } else {
  10443. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10444. }
  10445. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10446. };
  10447. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10448. if (fragment instanceof HTMLElement) {
  10449. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10450. callback(fragmentCode);
  10451. return;
  10452. }
  10453. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10454. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10455. return;
  10456. }
  10457. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10458. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10459. return;
  10460. }
  10461. var fragmentShaderUrl;
  10462. if (fragment[0] === ".") {
  10463. fragmentShaderUrl = fragment;
  10464. } else {
  10465. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10466. }
  10467. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10468. };
  10469. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10470. try {
  10471. var engine = this._engine;
  10472. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10473. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10474. this._attributes = engine.getAttributes(this._program, attributesNames);
  10475. for (var index = 0; index < this._samplers.length; index++) {
  10476. var sampler = this.getUniform(this._samplers[index]);
  10477. if (sampler == null) {
  10478. this._samplers.splice(index, 1);
  10479. index--;
  10480. }
  10481. }
  10482. engine.bindSamplers(this);
  10483. this._isReady = true;
  10484. if (this.onCompiled) {
  10485. this.onCompiled(this);
  10486. }
  10487. } catch (e) {
  10488. if (fallbacks && fallbacks.isMoreFallbacks) {
  10489. defines = fallbacks.reduce(defines);
  10490. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10491. } else {
  10492. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10493. BABYLON.Tools.Error("Defines: " + defines);
  10494. BABYLON.Tools.Error("Error: " + e.message);
  10495. this._compilationError = e.message;
  10496. if (this.onError) {
  10497. this.onError(this, this._compilationError);
  10498. }
  10499. }
  10500. }
  10501. };
  10502. Effect.prototype._bindTexture = function (channel, texture) {
  10503. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10504. };
  10505. Effect.prototype.setTexture = function (channel, texture) {
  10506. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10507. };
  10508. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10509. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10510. };
  10511. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10512. if (!this._valueCache[uniformName]) {
  10513. this._valueCache[uniformName] = [x, y];
  10514. return;
  10515. }
  10516. this._valueCache[uniformName][0] = x;
  10517. this._valueCache[uniformName][1] = y;
  10518. };
  10519. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10520. if (!this._valueCache[uniformName]) {
  10521. this._valueCache[uniformName] = [x, y, z];
  10522. return;
  10523. }
  10524. this._valueCache[uniformName][0] = x;
  10525. this._valueCache[uniformName][1] = y;
  10526. this._valueCache[uniformName][2] = z;
  10527. };
  10528. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10529. if (!this._valueCache[uniformName]) {
  10530. this._valueCache[uniformName] = [x, y, z, w];
  10531. return;
  10532. }
  10533. this._valueCache[uniformName][0] = x;
  10534. this._valueCache[uniformName][1] = y;
  10535. this._valueCache[uniformName][2] = z;
  10536. this._valueCache[uniformName][3] = w;
  10537. };
  10538. Effect.prototype.setArray = function (uniformName, array) {
  10539. this._engine.setArray(this.getUniform(uniformName), array);
  10540. return this;
  10541. };
  10542. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10543. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10544. return this;
  10545. };
  10546. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10547. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10548. return this;
  10549. };
  10550. Effect.prototype.setFloat = function (uniformName, value) {
  10551. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10552. return this;
  10553. this._valueCache[uniformName] = value;
  10554. this._engine.setFloat(this.getUniform(uniformName), value);
  10555. return this;
  10556. };
  10557. Effect.prototype.setBool = function (uniformName, bool) {
  10558. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10559. return this;
  10560. this._valueCache[uniformName] = bool;
  10561. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10562. return this;
  10563. };
  10564. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10565. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10566. return this;
  10567. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10568. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10569. return this;
  10570. };
  10571. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10572. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10573. return this;
  10574. this._cacheFloat2(uniformName, x, y);
  10575. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10576. return this;
  10577. };
  10578. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10579. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10580. return this;
  10581. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10582. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10583. return this;
  10584. };
  10585. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10586. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10587. return this;
  10588. this._cacheFloat3(uniformName, x, y, z);
  10589. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10590. return this;
  10591. };
  10592. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10593. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10594. return this;
  10595. this._cacheFloat4(uniformName, x, y, z, w);
  10596. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10597. return this;
  10598. };
  10599. Effect.prototype.setColor3 = function (uniformName, color3) {
  10600. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10601. return this;
  10602. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10603. this._engine.setColor3(this.getUniform(uniformName), color3);
  10604. return this;
  10605. };
  10606. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10607. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b && this._valueCache[uniformName][3] == alpha)
  10608. return this;
  10609. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10610. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10611. return this;
  10612. };
  10613. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  10614. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  10615. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  10616. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10617. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  10618. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  10619. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  10620. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  10621. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  10622. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  10623. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alpha;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 8.0;\n float q = fbm(p - iGlobalTime * 0.1);\n vec2 r = vec2(fbm(p + q + iGlobalTime * speed.x - p.x - p.y), fbm(p + q - iGlobalTime * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n gl_FragColor = vec4(c * cos(shift * vUV.y), alpha);\n\n}",
  10624. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  10625. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  10626. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  10627. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  10628. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  10629. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  10630. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  10631. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  10632. outlinePixelShader:"precision highp float;\n\nuniform vec3 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = vec4(color, 1.);\n}",
  10633. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\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\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  10634. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  10635. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  10636. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  10637. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  10638. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  10639. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  10640. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  10641. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\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\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  10642. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  10643. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  10644. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition; \nvarying vec2 vUV; \n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n\n vec2 positionWood = vPosition;\n float r = ringScale * sqrt(dot(positionWood.xy, positionWood.xy));\n r = r + fbm(vPosition);\n r = r - floor(r);\n r = smoothstep(0.0, 0.8, r) - smoothstep(0.8, 1.0, r);\n\n gl_FragColor = vec4(mix(woodColor1, woodColor2, r), 1.0);\n}",
  10645. };
  10646. return Effect;
  10647. })();
  10648. BABYLON.Effect = Effect;
  10649. })(BABYLON || (BABYLON = {}));
  10650. var BABYLON;
  10651. (function (BABYLON) {
  10652. var Material = (function () {
  10653. function Material(name, scene, doNotAdd) {
  10654. this.name = name;
  10655. this.checkReadyOnEveryCall = true;
  10656. this.checkReadyOnlyOnce = false;
  10657. this.state = "";
  10658. this.alpha = 1.0;
  10659. this.wireframe = false;
  10660. this.backFaceCulling = true;
  10661. this._wasPreviouslyReady = false;
  10662. this.id = name;
  10663. this._scene = scene;
  10664. if (!doNotAdd) {
  10665. scene.materials.push(this);
  10666. }
  10667. }
  10668. Material.prototype.isReady = function (mesh, useInstances) {
  10669. return true;
  10670. };
  10671. Material.prototype.getEffect = function () {
  10672. return this._effect;
  10673. };
  10674. Material.prototype.getScene = function () {
  10675. return this._scene;
  10676. };
  10677. Material.prototype.needAlphaBlending = function () {
  10678. return (this.alpha < 1.0);
  10679. };
  10680. Material.prototype.needAlphaTesting = function () {
  10681. return false;
  10682. };
  10683. Material.prototype.getAlphaTestTexture = function () {
  10684. return null;
  10685. };
  10686. Material.prototype.trackCreation = function (onCompiled, onError) {
  10687. };
  10688. Material.prototype._preBind = function () {
  10689. var engine = this._scene.getEngine();
  10690. engine.enableEffect(this._effect);
  10691. engine.setState(this.backFaceCulling);
  10692. };
  10693. Material.prototype.bind = function (world, mesh) {
  10694. };
  10695. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10696. };
  10697. Material.prototype.unbind = function () {
  10698. };
  10699. Material.prototype.dispose = function (forceDisposeEffect) {
  10700. var index = this._scene.materials.indexOf(this);
  10701. this._scene.materials.splice(index, 1);
  10702. if (forceDisposeEffect && this._effect) {
  10703. this._scene.getEngine()._releaseEffect(this._effect);
  10704. this._effect = null;
  10705. }
  10706. if (this.onDispose) {
  10707. this.onDispose();
  10708. }
  10709. };
  10710. return Material;
  10711. })();
  10712. BABYLON.Material = Material;
  10713. })(BABYLON || (BABYLON = {}));
  10714. var __extends = this.__extends || function (d, b) {
  10715. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10716. function __() { this.constructor = d; }
  10717. __.prototype = b.prototype;
  10718. d.prototype = new __();
  10719. };
  10720. var BABYLON;
  10721. (function (BABYLON) {
  10722. var maxSimultaneousLights = 4;
  10723. var FresnelParameters = (function () {
  10724. function FresnelParameters() {
  10725. this.isEnabled = true;
  10726. this.leftColor = BABYLON.Color3.White();
  10727. this.rightColor = BABYLON.Color3.Black();
  10728. this.bias = 0;
  10729. this.power = 1;
  10730. }
  10731. return FresnelParameters;
  10732. })();
  10733. BABYLON.FresnelParameters = FresnelParameters;
  10734. var StandardMaterial = (function (_super) {
  10735. __extends(StandardMaterial, _super);
  10736. function StandardMaterial(name, scene) {
  10737. var _this = this;
  10738. _super.call(this, name, scene);
  10739. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10740. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10741. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10742. this.specularPower = 64;
  10743. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10744. this.useAlphaFromDiffuseTexture = false;
  10745. this.useSpecularOverAlpha = true;
  10746. this.fogEnabled = true;
  10747. this._cachedDefines = null;
  10748. this._renderTargets = new BABYLON.SmartArray(16);
  10749. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10750. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10751. this._scaledDiffuse = new BABYLON.Color3();
  10752. this._scaledSpecular = new BABYLON.Color3();
  10753. this.getRenderTargetTextures = function () {
  10754. _this._renderTargets.reset();
  10755. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10756. _this._renderTargets.push(_this.reflectionTexture);
  10757. }
  10758. return _this._renderTargets;
  10759. };
  10760. }
  10761. StandardMaterial.prototype.needAlphaBlending = function () {
  10762. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10763. };
  10764. StandardMaterial.prototype.needAlphaTesting = function () {
  10765. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10766. };
  10767. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10768. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10769. };
  10770. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10771. return this.diffuseTexture;
  10772. };
  10773. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10774. if (this.checkReadyOnlyOnce) {
  10775. if (this._wasPreviouslyReady) {
  10776. return true;
  10777. }
  10778. }
  10779. var scene = this.getScene();
  10780. if (!this.checkReadyOnEveryCall) {
  10781. if (this._renderId === scene.getRenderId()) {
  10782. return true;
  10783. }
  10784. }
  10785. var engine = scene.getEngine();
  10786. var defines = [];
  10787. var fallbacks = new BABYLON.EffectFallbacks();
  10788. if (scene.texturesEnabled) {
  10789. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10790. if (!this.diffuseTexture.isReady()) {
  10791. return false;
  10792. } else {
  10793. defines.push("#define DIFFUSE");
  10794. }
  10795. }
  10796. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10797. if (!this.ambientTexture.isReady()) {
  10798. return false;
  10799. } else {
  10800. defines.push("#define AMBIENT");
  10801. }
  10802. }
  10803. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10804. if (!this.opacityTexture.isReady()) {
  10805. return false;
  10806. } else {
  10807. defines.push("#define OPACITY");
  10808. if (this.opacityTexture.getAlphaFromRGB) {
  10809. defines.push("#define OPACITYRGB");
  10810. }
  10811. }
  10812. }
  10813. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10814. if (!this.reflectionTexture.isReady()) {
  10815. return false;
  10816. } else {
  10817. defines.push("#define REFLECTION");
  10818. fallbacks.addFallback(0, "REFLECTION");
  10819. }
  10820. }
  10821. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10822. if (!this.emissiveTexture.isReady()) {
  10823. return false;
  10824. } else {
  10825. defines.push("#define EMISSIVE");
  10826. }
  10827. }
  10828. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10829. if (!this.specularTexture.isReady()) {
  10830. return false;
  10831. } else {
  10832. defines.push("#define SPECULAR");
  10833. fallbacks.addFallback(0, "SPECULAR");
  10834. }
  10835. }
  10836. }
  10837. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10838. if (!this.bumpTexture.isReady()) {
  10839. return false;
  10840. } else {
  10841. defines.push("#define BUMP");
  10842. fallbacks.addFallback(0, "BUMP");
  10843. }
  10844. }
  10845. if (this.useSpecularOverAlpha) {
  10846. defines.push("#define SPECULAROVERALPHA");
  10847. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10848. }
  10849. if (scene.clipPlane) {
  10850. defines.push("#define CLIPPLANE");
  10851. }
  10852. if (engine.getAlphaTesting()) {
  10853. defines.push("#define ALPHATEST");
  10854. }
  10855. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10856. defines.push("#define ALPHAFROMDIFFUSE");
  10857. }
  10858. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  10859. defines.push("#define FOG");
  10860. fallbacks.addFallback(1, "FOG");
  10861. }
  10862. var shadowsActivated = false;
  10863. var lightIndex = 0;
  10864. if (scene.lightsEnabled) {
  10865. for (var index = 0; index < scene.lights.length; index++) {
  10866. var light = scene.lights[index];
  10867. if (!light.isEnabled()) {
  10868. continue;
  10869. }
  10870. if (light._excludedMeshesIds.length > 0) {
  10871. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10872. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10873. if (excludedMesh) {
  10874. light.excludedMeshes.push(excludedMesh);
  10875. }
  10876. }
  10877. light._excludedMeshesIds = [];
  10878. }
  10879. if (light._includedOnlyMeshesIds.length > 0) {
  10880. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10881. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10882. if (includedOnlyMesh) {
  10883. light.includedOnlyMeshes.push(includedOnlyMesh);
  10884. }
  10885. }
  10886. light._includedOnlyMeshesIds = [];
  10887. }
  10888. if (!light.canAffectMesh(mesh)) {
  10889. continue;
  10890. }
  10891. defines.push("#define LIGHT" + lightIndex);
  10892. if (lightIndex > 0) {
  10893. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10894. }
  10895. var type;
  10896. if (light instanceof BABYLON.SpotLight) {
  10897. type = "#define SPOTLIGHT" + lightIndex;
  10898. } else if (light instanceof BABYLON.HemisphericLight) {
  10899. type = "#define HEMILIGHT" + lightIndex;
  10900. } else {
  10901. type = "#define POINTDIRLIGHT" + lightIndex;
  10902. }
  10903. defines.push(type);
  10904. if (lightIndex > 0) {
  10905. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10906. }
  10907. if (scene.shadowsEnabled) {
  10908. var shadowGenerator = light.getShadowGenerator();
  10909. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10910. defines.push("#define SHADOW" + lightIndex);
  10911. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10912. if (!shadowsActivated) {
  10913. defines.push("#define SHADOWS");
  10914. shadowsActivated = true;
  10915. }
  10916. if (shadowGenerator.useVarianceShadowMap) {
  10917. defines.push("#define SHADOWVSM" + lightIndex);
  10918. if (lightIndex > 0) {
  10919. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10920. }
  10921. }
  10922. if (shadowGenerator.usePoissonSampling) {
  10923. defines.push("#define SHADOWPCF" + lightIndex);
  10924. if (lightIndex > 0) {
  10925. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10926. }
  10927. }
  10928. }
  10929. }
  10930. lightIndex++;
  10931. if (lightIndex == maxSimultaneousLights)
  10932. break;
  10933. }
  10934. }
  10935. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10936. var fresnelRank = 1;
  10937. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10938. defines.push("#define DIFFUSEFRESNEL");
  10939. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10940. fresnelRank++;
  10941. }
  10942. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10943. defines.push("#define OPACITYFRESNEL");
  10944. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10945. fresnelRank++;
  10946. }
  10947. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10948. defines.push("#define REFLECTIONFRESNEL");
  10949. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10950. fresnelRank++;
  10951. }
  10952. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10953. defines.push("#define EMISSIVEFRESNEL");
  10954. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10955. fresnelRank++;
  10956. }
  10957. defines.push("#define FRESNEL");
  10958. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10959. }
  10960. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10961. if (mesh) {
  10962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10963. attribs.push(BABYLON.VertexBuffer.UVKind);
  10964. defines.push("#define UV1");
  10965. }
  10966. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10967. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10968. defines.push("#define UV2");
  10969. }
  10970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10971. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10972. defines.push("#define VERTEXCOLOR");
  10973. }
  10974. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10975. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10976. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10977. defines.push("#define BONES");
  10978. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10979. defines.push("#define BONES4");
  10980. fallbacks.addFallback(0, "BONES4");
  10981. }
  10982. if (useInstances) {
  10983. defines.push("#define INSTANCES");
  10984. attribs.push("world0");
  10985. attribs.push("world1");
  10986. attribs.push("world2");
  10987. attribs.push("world3");
  10988. }
  10989. }
  10990. var join = defines.join("\n");
  10991. if (this._cachedDefines != join) {
  10992. this._cachedDefines = join;
  10993. var shaderName = "default";
  10994. if (!scene.getEngine().getCaps().standardDerivatives) {
  10995. shaderName = "legacydefault";
  10996. }
  10997. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10998. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10999. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11000. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11001. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11002. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11003. "vFogInfos", "vFogColor",
  11004. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11005. "mBones",
  11006. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11007. "darkness0", "darkness1", "darkness2", "darkness3",
  11008. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11009. ], [
  11010. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11011. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11012. ], join, fallbacks, this.onCompiled, this.onError);
  11013. }
  11014. if (!this._effect.isReady()) {
  11015. return false;
  11016. }
  11017. this._renderId = scene.getRenderId();
  11018. this._wasPreviouslyReady = true;
  11019. return true;
  11020. };
  11021. StandardMaterial.prototype.unbind = function () {
  11022. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11023. this._effect.setTexture("reflection2DSampler", null);
  11024. }
  11025. };
  11026. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11027. this._effect.setMatrix("world", world);
  11028. };
  11029. StandardMaterial.prototype.bind = function (world, mesh) {
  11030. var scene = this.getScene();
  11031. this.bindOnlyWorldMatrix(world);
  11032. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11033. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11034. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11035. }
  11036. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11037. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11038. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11039. }
  11040. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11041. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11042. }
  11043. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11044. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11045. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11046. }
  11047. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11048. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11049. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11050. }
  11051. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11052. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11053. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11054. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11055. }
  11056. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11057. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11058. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11059. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11060. }
  11061. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11062. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11063. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11064. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11065. }
  11066. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11067. if (this.reflectionTexture.isCube) {
  11068. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11069. } else {
  11070. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11071. }
  11072. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11073. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11074. }
  11075. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11076. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11077. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11078. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11079. }
  11080. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11081. this._effect.setTexture("specularSampler", this.specularTexture);
  11082. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11083. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11084. }
  11085. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11086. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11087. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11088. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11089. }
  11090. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11091. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11092. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11093. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11094. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11095. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11096. if (scene.lightsEnabled) {
  11097. var lightIndex = 0;
  11098. for (var index = 0; index < scene.lights.length; index++) {
  11099. var light = scene.lights[index];
  11100. if (!light.isEnabled()) {
  11101. continue;
  11102. }
  11103. if (!light.canAffectMesh(mesh)) {
  11104. continue;
  11105. }
  11106. if (light instanceof BABYLON.PointLight) {
  11107. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11108. } else if (light instanceof BABYLON.DirectionalLight) {
  11109. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11110. } else if (light instanceof BABYLON.SpotLight) {
  11111. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11112. } else if (light instanceof BABYLON.HemisphericLight) {
  11113. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11114. }
  11115. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11116. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11117. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11118. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11119. if (scene.shadowsEnabled) {
  11120. var shadowGenerator = light.getShadowGenerator();
  11121. if (mesh.receiveShadows && shadowGenerator) {
  11122. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11123. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11124. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11125. }
  11126. }
  11127. lightIndex++;
  11128. if (lightIndex == maxSimultaneousLights)
  11129. break;
  11130. }
  11131. }
  11132. if (scene.clipPlane) {
  11133. var clipPlane = scene.clipPlane;
  11134. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11135. }
  11136. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11137. this._effect.setMatrix("view", scene.getViewMatrix());
  11138. }
  11139. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11140. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11141. this._effect.setColor3("vFogColor", scene.fogColor);
  11142. }
  11143. };
  11144. StandardMaterial.prototype.getAnimatables = function () {
  11145. var results = [];
  11146. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11147. results.push(this.diffuseTexture);
  11148. }
  11149. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11150. results.push(this.ambientTexture);
  11151. }
  11152. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11153. results.push(this.opacityTexture);
  11154. }
  11155. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11156. results.push(this.reflectionTexture);
  11157. }
  11158. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11159. results.push(this.emissiveTexture);
  11160. }
  11161. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11162. results.push(this.specularTexture);
  11163. }
  11164. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11165. results.push(this.bumpTexture);
  11166. }
  11167. return results;
  11168. };
  11169. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11170. if (this.diffuseTexture) {
  11171. this.diffuseTexture.dispose();
  11172. }
  11173. if (this.ambientTexture) {
  11174. this.ambientTexture.dispose();
  11175. }
  11176. if (this.opacityTexture) {
  11177. this.opacityTexture.dispose();
  11178. }
  11179. if (this.reflectionTexture) {
  11180. this.reflectionTexture.dispose();
  11181. }
  11182. if (this.emissiveTexture) {
  11183. this.emissiveTexture.dispose();
  11184. }
  11185. if (this.specularTexture) {
  11186. this.specularTexture.dispose();
  11187. }
  11188. if (this.bumpTexture) {
  11189. this.bumpTexture.dispose();
  11190. }
  11191. _super.prototype.dispose.call(this, forceDisposeEffect);
  11192. };
  11193. StandardMaterial.prototype.clone = function (name) {
  11194. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11195. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11196. newStandardMaterial.alpha = this.alpha;
  11197. newStandardMaterial.wireframe = this.wireframe;
  11198. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11199. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11200. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11201. }
  11202. if (this.ambientTexture && this.ambientTexture.clone) {
  11203. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11204. }
  11205. if (this.opacityTexture && this.opacityTexture.clone) {
  11206. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11207. }
  11208. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11209. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11210. }
  11211. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11212. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11213. }
  11214. if (this.specularTexture && this.specularTexture.clone) {
  11215. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11216. }
  11217. if (this.bumpTexture && this.bumpTexture.clone) {
  11218. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11219. }
  11220. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11221. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11222. newStandardMaterial.specularColor = this.specularColor.clone();
  11223. newStandardMaterial.specularPower = this.specularPower;
  11224. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11225. return newStandardMaterial;
  11226. };
  11227. StandardMaterial.DiffuseTextureEnabled = true;
  11228. StandardMaterial.AmbientTextureEnabled = true;
  11229. StandardMaterial.OpacityTextureEnabled = true;
  11230. StandardMaterial.ReflectionTextureEnabled = true;
  11231. StandardMaterial.EmissiveTextureEnabled = true;
  11232. StandardMaterial.SpecularTextureEnabled = true;
  11233. StandardMaterial.BumpTextureEnabled = true;
  11234. return StandardMaterial;
  11235. })(BABYLON.Material);
  11236. BABYLON.StandardMaterial = StandardMaterial;
  11237. })(BABYLON || (BABYLON = {}));
  11238. var __extends = this.__extends || function (d, b) {
  11239. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11240. function __() { this.constructor = d; }
  11241. __.prototype = b.prototype;
  11242. d.prototype = new __();
  11243. };
  11244. var BABYLON;
  11245. (function (BABYLON) {
  11246. var MultiMaterial = (function (_super) {
  11247. __extends(MultiMaterial, _super);
  11248. function MultiMaterial(name, scene) {
  11249. _super.call(this, name, scene, true);
  11250. this.subMaterials = new Array();
  11251. scene.multiMaterials.push(this);
  11252. }
  11253. MultiMaterial.prototype.getSubMaterial = function (index) {
  11254. if (index < 0 || index >= this.subMaterials.length) {
  11255. return this.getScene().defaultMaterial;
  11256. }
  11257. return this.subMaterials[index];
  11258. };
  11259. MultiMaterial.prototype.isReady = function (mesh) {
  11260. for (var index = 0; index < this.subMaterials.length; index++) {
  11261. var subMaterial = this.subMaterials[index];
  11262. if (subMaterial) {
  11263. if (!this.subMaterials[index].isReady(mesh)) {
  11264. return false;
  11265. }
  11266. }
  11267. }
  11268. return true;
  11269. };
  11270. return MultiMaterial;
  11271. })(BABYLON.Material);
  11272. BABYLON.MultiMaterial = MultiMaterial;
  11273. })(BABYLON || (BABYLON = {}));
  11274. var BABYLON;
  11275. (function (BABYLON) {
  11276. var Database = (function () {
  11277. function Database(urlToScene, callbackManifestChecked) {
  11278. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11279. this.callbackManifestChecked = callbackManifestChecked;
  11280. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11281. this.db = null;
  11282. this.enableSceneOffline = false;
  11283. this.enableTexturesOffline = false;
  11284. this.manifestVersionFound = 0;
  11285. this.mustUpdateRessources = false;
  11286. this.hasReachedQuota = false;
  11287. this.checkManifestFile();
  11288. }
  11289. Database.prototype.checkManifestFile = function () {
  11290. var _this = this;
  11291. function noManifestFile() {
  11292. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11293. that.enableSceneOffline = false;
  11294. that.enableTexturesOffline = false;
  11295. that.callbackManifestChecked(false);
  11296. }
  11297. var that = this;
  11298. var manifestURL = this.currentSceneUrl + ".manifest";
  11299. var xhr = new XMLHttpRequest();
  11300. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11301. xhr.open("GET", manifestURLTimeStamped, true);
  11302. xhr.addEventListener("load", function () {
  11303. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11304. try {
  11305. var manifestFile = JSON.parse(xhr.response);
  11306. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11307. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11308. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11309. _this.manifestVersionFound = manifestFile.version;
  11310. }
  11311. if (_this.callbackManifestChecked) {
  11312. _this.callbackManifestChecked(true);
  11313. }
  11314. } catch (ex) {
  11315. noManifestFile();
  11316. }
  11317. } else {
  11318. noManifestFile();
  11319. }
  11320. }, false);
  11321. xhr.addEventListener("error", function (event) {
  11322. noManifestFile();
  11323. }, false);
  11324. try {
  11325. xhr.send();
  11326. } catch (ex) {
  11327. BABYLON.Tools.Error("Error on XHR send request.");
  11328. that.callbackManifestChecked(false);
  11329. }
  11330. };
  11331. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11332. var _this = this;
  11333. function handleError() {
  11334. that.isSupported = false;
  11335. if (errorCallback)
  11336. errorCallback();
  11337. }
  11338. var that = this;
  11339. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11340. this.isSupported = false;
  11341. if (errorCallback)
  11342. errorCallback();
  11343. } else {
  11344. if (!this.db) {
  11345. this.hasReachedQuota = false;
  11346. this.isSupported = true;
  11347. var request = this.idbFactory.open("babylonjs", 1);
  11348. request.onerror = function (event) {
  11349. handleError();
  11350. };
  11351. request.onblocked = function (event) {
  11352. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11353. handleError();
  11354. };
  11355. request.onsuccess = function (event) {
  11356. _this.db = request.result;
  11357. successCallback();
  11358. };
  11359. request.onupgradeneeded = function (event) {
  11360. _this.db = (event.target).result;
  11361. try {
  11362. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11363. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11364. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11365. } catch (ex) {
  11366. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11367. handleError();
  11368. }
  11369. };
  11370. } else {
  11371. if (successCallback)
  11372. successCallback();
  11373. }
  11374. }
  11375. };
  11376. Database.prototype.loadImageFromDB = function (url, image) {
  11377. var _this = this;
  11378. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11379. var saveAndLoadImage = function () {
  11380. if (!_this.hasReachedQuota && _this.db !== null) {
  11381. _this._saveImageIntoDBAsync(completeURL, image);
  11382. } else {
  11383. image.src = url;
  11384. }
  11385. };
  11386. if (!this.mustUpdateRessources) {
  11387. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11388. } else {
  11389. saveAndLoadImage();
  11390. }
  11391. };
  11392. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11393. if (this.isSupported && this.db !== null) {
  11394. var texture;
  11395. var transaction = this.db.transaction(["textures"]);
  11396. transaction.onabort = function (event) {
  11397. image.src = url;
  11398. };
  11399. transaction.oncomplete = function (event) {
  11400. var blobTextureURL;
  11401. if (texture) {
  11402. var URL = window.URL || window.webkitURL;
  11403. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11404. image.onerror = function () {
  11405. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11406. image.src = url;
  11407. };
  11408. image.src = blobTextureURL;
  11409. } else {
  11410. notInDBCallback();
  11411. }
  11412. };
  11413. var getRequest = transaction.objectStore("textures").get(url);
  11414. getRequest.onsuccess = function (event) {
  11415. texture = (event.target).result;
  11416. };
  11417. getRequest.onerror = function (event) {
  11418. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11419. image.src = url;
  11420. };
  11421. } else {
  11422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11423. image.src = url;
  11424. }
  11425. };
  11426. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11427. var _this = this;
  11428. if (this.isSupported) {
  11429. var generateBlobUrl = function () {
  11430. var blobTextureURL;
  11431. if (blob) {
  11432. var URL = window.URL || window.webkitURL;
  11433. try {
  11434. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11435. } catch (ex) {
  11436. blobTextureURL = URL.createObjectURL(blob);
  11437. }
  11438. }
  11439. image.src = blobTextureURL;
  11440. };
  11441. if (BABYLON.Database.isUASupportingBlobStorage) {
  11442. var xhr = new XMLHttpRequest(), blob;
  11443. xhr.open("GET", url, true);
  11444. xhr.responseType = "blob";
  11445. xhr.addEventListener("load", function () {
  11446. if (xhr.status === 200) {
  11447. blob = xhr.response;
  11448. var transaction = _this.db.transaction(["textures"], "readwrite");
  11449. transaction.onabort = function (event) {
  11450. try {
  11451. if (event.srcElement.error.name === "QuotaExceededError") {
  11452. this.hasReachedQuota = true;
  11453. }
  11454. } catch (ex) {
  11455. }
  11456. generateBlobUrl();
  11457. };
  11458. transaction.oncomplete = function (event) {
  11459. generateBlobUrl();
  11460. };
  11461. var newTexture = { textureUrl: url, data: blob };
  11462. try {
  11463. var addRequest = transaction.objectStore("textures").put(newTexture);
  11464. addRequest.onsuccess = function (event) {
  11465. };
  11466. addRequest.onerror = function (event) {
  11467. generateBlobUrl();
  11468. };
  11469. } catch (ex) {
  11470. if (ex.code === 25) {
  11471. BABYLON.Database.isUASupportingBlobStorage = false;
  11472. }
  11473. image.src = url;
  11474. }
  11475. } else {
  11476. image.src = url;
  11477. }
  11478. }, false);
  11479. xhr.addEventListener("error", function (event) {
  11480. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11481. image.src = url;
  11482. }, false);
  11483. xhr.send();
  11484. } else {
  11485. image.src = url;
  11486. }
  11487. } else {
  11488. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11489. image.src = url;
  11490. }
  11491. };
  11492. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11493. var _this = this;
  11494. var updateVersion = function (event) {
  11495. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11496. };
  11497. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11498. };
  11499. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11500. var _this = this;
  11501. if (this.isSupported) {
  11502. var version;
  11503. try {
  11504. var transaction = this.db.transaction(["versions"]);
  11505. transaction.oncomplete = function (event) {
  11506. if (version) {
  11507. if (_this.manifestVersionFound > version.data) {
  11508. _this.mustUpdateRessources = true;
  11509. updateInDBCallback();
  11510. } else {
  11511. callback(version.data);
  11512. }
  11513. } else {
  11514. _this.mustUpdateRessources = true;
  11515. updateInDBCallback();
  11516. }
  11517. };
  11518. transaction.onabort = function (event) {
  11519. callback(-1);
  11520. };
  11521. var getRequest = transaction.objectStore("versions").get(url);
  11522. getRequest.onsuccess = function (event) {
  11523. version = (event.target).result;
  11524. };
  11525. getRequest.onerror = function (event) {
  11526. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11527. callback(-1);
  11528. };
  11529. } catch (ex) {
  11530. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11531. callback(-1);
  11532. }
  11533. } else {
  11534. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11535. callback(-1);
  11536. }
  11537. };
  11538. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11539. var _this = this;
  11540. if (this.isSupported && !this.hasReachedQuota) {
  11541. try {
  11542. var transaction = this.db.transaction(["versions"], "readwrite");
  11543. transaction.onabort = function (event) {
  11544. try {
  11545. if (event.srcElement.error.name === "QuotaExceededError") {
  11546. _this.hasReachedQuota = true;
  11547. }
  11548. } catch (ex) {
  11549. }
  11550. callback(-1);
  11551. };
  11552. transaction.oncomplete = function (event) {
  11553. callback(_this.manifestVersionFound);
  11554. };
  11555. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11556. var addRequest = transaction.objectStore("versions").put(newVersion);
  11557. addRequest.onsuccess = function (event) {
  11558. };
  11559. addRequest.onerror = function (event) {
  11560. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11561. };
  11562. } catch (ex) {
  11563. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11564. callback(-1);
  11565. }
  11566. } else {
  11567. callback(-1);
  11568. }
  11569. };
  11570. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  11571. var _this = this;
  11572. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  11573. var saveAndLoadFile = function (event) {
  11574. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  11575. };
  11576. this._checkVersionFromDB(completeUrl, function (version) {
  11577. if (version !== -1) {
  11578. if (!_this.mustUpdateRessources) {
  11579. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  11580. } else {
  11581. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  11582. }
  11583. } else {
  11584. errorCallback();
  11585. }
  11586. });
  11587. };
  11588. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  11589. if (this.isSupported) {
  11590. var targetStore;
  11591. if (url.indexOf(".babylon") !== -1) {
  11592. targetStore = "scenes";
  11593. } else {
  11594. targetStore = "textures";
  11595. }
  11596. var file;
  11597. var transaction = this.db.transaction([targetStore]);
  11598. transaction.oncomplete = function (event) {
  11599. if (file) {
  11600. callback(file.data);
  11601. } else {
  11602. notInDBCallback();
  11603. }
  11604. };
  11605. transaction.onabort = function (event) {
  11606. notInDBCallback();
  11607. };
  11608. var getRequest = transaction.objectStore(targetStore).get(url);
  11609. getRequest.onsuccess = function (event) {
  11610. file = (event.target).result;
  11611. };
  11612. getRequest.onerror = function (event) {
  11613. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  11614. notInDBCallback();
  11615. };
  11616. } else {
  11617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11618. callback();
  11619. }
  11620. };
  11621. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  11622. var _this = this;
  11623. if (this.isSupported) {
  11624. var targetStore;
  11625. if (url.indexOf(".babylon") !== -1) {
  11626. targetStore = "scenes";
  11627. } else {
  11628. targetStore = "textures";
  11629. }
  11630. var xhr = new XMLHttpRequest(), fileData;
  11631. xhr.open("GET", url, true);
  11632. if (useArrayBuffer) {
  11633. xhr.responseType = "arraybuffer";
  11634. }
  11635. xhr.onprogress = progressCallback;
  11636. xhr.addEventListener("load", function () {
  11637. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11638. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11639. if (!_this.hasReachedQuota) {
  11640. var transaction = _this.db.transaction([targetStore], "readwrite");
  11641. transaction.onabort = function (event) {
  11642. try {
  11643. if (event.srcElement.error.name === "QuotaExceededError") {
  11644. this.hasReachedQuota = true;
  11645. }
  11646. } catch (ex) {
  11647. }
  11648. callback(fileData);
  11649. };
  11650. transaction.oncomplete = function (event) {
  11651. callback(fileData);
  11652. };
  11653. var newFile;
  11654. if (targetStore === "scenes") {
  11655. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11656. } else {
  11657. newFile = { textureUrl: url, data: fileData };
  11658. }
  11659. try {
  11660. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11661. addRequest.onsuccess = function (event) {
  11662. };
  11663. addRequest.onerror = function (event) {
  11664. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11665. };
  11666. } catch (ex) {
  11667. callback(fileData);
  11668. }
  11669. } else {
  11670. callback(fileData);
  11671. }
  11672. } else {
  11673. callback();
  11674. }
  11675. }, false);
  11676. xhr.addEventListener("error", function (event) {
  11677. BABYLON.Tools.Error("error on XHR request.");
  11678. callback();
  11679. }, false);
  11680. xhr.send();
  11681. } else {
  11682. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11683. callback();
  11684. }
  11685. };
  11686. Database.isUASupportingBlobStorage = true;
  11687. Database.parseURL = function (url) {
  11688. var a = document.createElement('a');
  11689. a.href = url;
  11690. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11691. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11692. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11693. return absLocation;
  11694. };
  11695. Database.ReturnFullUrlLocation = function (url) {
  11696. if (url.indexOf("http:/") === -1) {
  11697. return (BABYLON.Database.parseURL(window.location.href) + url);
  11698. } else {
  11699. return url;
  11700. }
  11701. };
  11702. return Database;
  11703. })();
  11704. BABYLON.Database = Database;
  11705. })(BABYLON || (BABYLON = {}));
  11706. var BABYLON;
  11707. (function (BABYLON) {
  11708. var SpriteManager = (function () {
  11709. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11710. this.name = name;
  11711. this.cellSize = cellSize;
  11712. this.sprites = new Array();
  11713. this.renderingGroupId = 0;
  11714. this._vertexDeclaration = [3, 4, 4, 4];
  11715. this._vertexStrideSize = 15 * 4;
  11716. this._capacity = capacity;
  11717. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11718. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11719. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11720. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11721. this._scene = scene;
  11722. this._scene.spriteManagers.push(this);
  11723. this._vertexDeclaration = [3, 4, 4, 4];
  11724. this._vertexStrideSize = 15 * 4;
  11725. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11726. var indices = [];
  11727. var index = 0;
  11728. for (var count = 0; count < capacity; count++) {
  11729. indices.push(index);
  11730. indices.push(index + 1);
  11731. indices.push(index + 2);
  11732. indices.push(index);
  11733. indices.push(index + 2);
  11734. indices.push(index + 3);
  11735. index += 4;
  11736. }
  11737. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11738. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11739. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11740. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11741. }
  11742. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11743. var arrayOffset = index * 15;
  11744. if (offsetX == 0)
  11745. offsetX = this._epsilon;
  11746. else if (offsetX == 1)
  11747. offsetX = 1 - this._epsilon;
  11748. if (offsetY == 0)
  11749. offsetY = this._epsilon;
  11750. else if (offsetY == 1)
  11751. offsetY = 1 - this._epsilon;
  11752. this._vertices[arrayOffset] = sprite.position.x;
  11753. this._vertices[arrayOffset + 1] = sprite.position.y;
  11754. this._vertices[arrayOffset + 2] = sprite.position.z;
  11755. this._vertices[arrayOffset + 3] = sprite.angle;
  11756. this._vertices[arrayOffset + 4] = sprite.size;
  11757. this._vertices[arrayOffset + 5] = offsetX;
  11758. this._vertices[arrayOffset + 6] = offsetY;
  11759. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11760. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11761. var offset = (sprite.cellIndex / rowSize) >> 0;
  11762. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11763. this._vertices[arrayOffset + 10] = offset;
  11764. this._vertices[arrayOffset + 11] = sprite.color.r;
  11765. this._vertices[arrayOffset + 12] = sprite.color.g;
  11766. this._vertices[arrayOffset + 13] = sprite.color.b;
  11767. this._vertices[arrayOffset + 14] = sprite.color.a;
  11768. };
  11769. SpriteManager.prototype.render = function () {
  11770. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11771. return;
  11772. var engine = this._scene.getEngine();
  11773. var baseSize = this._spriteTexture.getBaseSize();
  11774. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11775. var max = Math.min(this._capacity, this.sprites.length);
  11776. var rowSize = baseSize.width / this.cellSize;
  11777. var offset = 0;
  11778. for (var index = 0; index < max; index++) {
  11779. var sprite = this.sprites[index];
  11780. if (!sprite) {
  11781. continue;
  11782. }
  11783. sprite._animate(deltaTime);
  11784. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11785. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11786. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11787. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11788. }
  11789. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11790. var effect = this._effectBase;
  11791. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11792. effect = this._effectFog;
  11793. }
  11794. engine.enableEffect(effect);
  11795. var viewMatrix = this._scene.getViewMatrix();
  11796. effect.setTexture("diffuseSampler", this._spriteTexture);
  11797. effect.setMatrix("view", viewMatrix);
  11798. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11799. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11800. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11801. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11802. effect.setColor3("vFogColor", this._scene.fogColor);
  11803. }
  11804. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11805. effect.setBool("alphaTest", true);
  11806. engine.setColorWrite(false);
  11807. engine.draw(true, 0, max * 6);
  11808. engine.setColorWrite(true);
  11809. effect.setBool("alphaTest", false);
  11810. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11811. engine.draw(true, 0, max * 6);
  11812. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11813. };
  11814. SpriteManager.prototype.dispose = function () {
  11815. if (this._vertexBuffer) {
  11816. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11817. this._vertexBuffer = null;
  11818. }
  11819. if (this._indexBuffer) {
  11820. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11821. this._indexBuffer = null;
  11822. }
  11823. if (this._spriteTexture) {
  11824. this._spriteTexture.dispose();
  11825. this._spriteTexture = null;
  11826. }
  11827. var index = this._scene.spriteManagers.indexOf(this);
  11828. this._scene.spriteManagers.splice(index, 1);
  11829. if (this.onDispose) {
  11830. this.onDispose();
  11831. }
  11832. };
  11833. return SpriteManager;
  11834. })();
  11835. BABYLON.SpriteManager = SpriteManager;
  11836. })(BABYLON || (BABYLON = {}));
  11837. var BABYLON;
  11838. (function (BABYLON) {
  11839. var Sprite = (function () {
  11840. function Sprite(name, manager) {
  11841. this.name = name;
  11842. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11843. this.size = 1.0;
  11844. this.angle = 0;
  11845. this.cellIndex = 0;
  11846. this.invertU = 0;
  11847. this.invertV = 0;
  11848. this.animations = new Array();
  11849. this._animationStarted = false;
  11850. this._loopAnimation = false;
  11851. this._fromIndex = 0;
  11852. this._toIndex = 0;
  11853. this._delay = 0;
  11854. this._direction = 1;
  11855. this._frameCount = 0;
  11856. this._time = 0;
  11857. this._manager = manager;
  11858. this._manager.sprites.push(this);
  11859. this.position = BABYLON.Vector3.Zero();
  11860. }
  11861. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11862. this._fromIndex = from;
  11863. this._toIndex = to;
  11864. this._loopAnimation = loop;
  11865. this._delay = delay;
  11866. this._animationStarted = true;
  11867. this._direction = from < to ? 1 : -1;
  11868. this.cellIndex = from;
  11869. this._time = 0;
  11870. };
  11871. Sprite.prototype.stopAnimation = function () {
  11872. this._animationStarted = false;
  11873. };
  11874. Sprite.prototype._animate = function (deltaTime) {
  11875. if (!this._animationStarted)
  11876. return;
  11877. this._time += deltaTime;
  11878. if (this._time > this._delay) {
  11879. this._time = this._time % this._delay;
  11880. this.cellIndex += this._direction;
  11881. if (this.cellIndex == this._toIndex) {
  11882. if (this._loopAnimation) {
  11883. this.cellIndex = this._fromIndex;
  11884. } else {
  11885. this._animationStarted = false;
  11886. if (this.disposeWhenFinishedAnimating) {
  11887. this.dispose();
  11888. }
  11889. }
  11890. }
  11891. }
  11892. };
  11893. Sprite.prototype.dispose = function () {
  11894. for (var i = 0; i < this._manager.sprites.length; i++) {
  11895. if (this._manager.sprites[i] == this) {
  11896. this._manager.sprites.splice(i, 1);
  11897. }
  11898. }
  11899. };
  11900. return Sprite;
  11901. })();
  11902. BABYLON.Sprite = Sprite;
  11903. })(BABYLON || (BABYLON = {}));
  11904. var BABYLON;
  11905. (function (BABYLON) {
  11906. var Layer = (function () {
  11907. function Layer(name, imgUrl, scene, isBackground, color) {
  11908. this.name = name;
  11909. this._vertexDeclaration = [2];
  11910. this._vertexStrideSize = 2 * 4;
  11911. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11912. this.isBackground = isBackground === undefined ? true : isBackground;
  11913. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11914. this._scene = scene;
  11915. this._scene.layers.push(this);
  11916. var vertices = [];
  11917. vertices.push(1, 1);
  11918. vertices.push(-1, 1);
  11919. vertices.push(-1, -1);
  11920. vertices.push(1, -1);
  11921. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11922. var indices = [];
  11923. indices.push(0);
  11924. indices.push(1);
  11925. indices.push(2);
  11926. indices.push(0);
  11927. indices.push(2);
  11928. indices.push(3);
  11929. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11930. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11931. }
  11932. Layer.prototype.render = function () {
  11933. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11934. return;
  11935. var engine = this._scene.getEngine();
  11936. engine.enableEffect(this._effect);
  11937. engine.setState(false);
  11938. this._effect.setTexture("textureSampler", this.texture);
  11939. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11940. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11941. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11942. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11943. engine.draw(true, 0, 6);
  11944. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11945. };
  11946. Layer.prototype.dispose = function () {
  11947. if (this._vertexBuffer) {
  11948. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11949. this._vertexBuffer = null;
  11950. }
  11951. if (this._indexBuffer) {
  11952. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11953. this._indexBuffer = null;
  11954. }
  11955. if (this.texture) {
  11956. this.texture.dispose();
  11957. this.texture = null;
  11958. }
  11959. var index = this._scene.layers.indexOf(this);
  11960. this._scene.layers.splice(index, 1);
  11961. if (this.onDispose) {
  11962. this.onDispose();
  11963. }
  11964. };
  11965. return Layer;
  11966. })();
  11967. BABYLON.Layer = Layer;
  11968. })(BABYLON || (BABYLON = {}));
  11969. var BABYLON;
  11970. (function (BABYLON) {
  11971. var Particle = (function () {
  11972. function Particle() {
  11973. this.position = BABYLON.Vector3.Zero();
  11974. this.direction = BABYLON.Vector3.Zero();
  11975. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11976. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11977. this.lifeTime = 1.0;
  11978. this.age = 0;
  11979. this.size = 0;
  11980. this.angle = 0;
  11981. this.angularSpeed = 0;
  11982. }
  11983. return Particle;
  11984. })();
  11985. BABYLON.Particle = Particle;
  11986. })(BABYLON || (BABYLON = {}));
  11987. var BABYLON;
  11988. (function (BABYLON) {
  11989. var randomNumber = function (min, max) {
  11990. if (min == max) {
  11991. return (min);
  11992. }
  11993. var random = Math.random();
  11994. return ((random * (max - min)) + min);
  11995. };
  11996. var ParticleSystem = (function () {
  11997. function ParticleSystem(name, capacity, scene, customEffect) {
  11998. var _this = this;
  11999. this.name = name;
  12000. this.renderingGroupId = 0;
  12001. this.emitter = null;
  12002. this.emitRate = 10;
  12003. this.manualEmitCount = -1;
  12004. this.updateSpeed = 0.01;
  12005. this.targetStopDuration = 0;
  12006. this.disposeOnStop = false;
  12007. this.minEmitPower = 1;
  12008. this.maxEmitPower = 1;
  12009. this.minLifeTime = 1;
  12010. this.maxLifeTime = 1;
  12011. this.minSize = 1;
  12012. this.maxSize = 1;
  12013. this.minAngularSpeed = 0;
  12014. this.maxAngularSpeed = 0;
  12015. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12016. this.forceDepthWrite = false;
  12017. this.gravity = BABYLON.Vector3.Zero();
  12018. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12019. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12020. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12021. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12022. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12023. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12024. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12025. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12026. this.particles = new Array();
  12027. this._vertexDeclaration = [3, 4, 4];
  12028. this._vertexStrideSize = 11 * 4;
  12029. this._stockParticles = new Array();
  12030. this._newPartsExcess = 0;
  12031. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12032. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12033. this._scaledDirection = BABYLON.Vector3.Zero();
  12034. this._scaledGravity = BABYLON.Vector3.Zero();
  12035. this._currentRenderId = -1;
  12036. this._started = false;
  12037. this._stopped = false;
  12038. this._actualFrame = 0;
  12039. this.id = name;
  12040. this._capacity = capacity;
  12041. this._scene = scene;
  12042. this._customEffect = customEffect;
  12043. scene.particleSystems.push(this);
  12044. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12045. var indices = [];
  12046. var index = 0;
  12047. for (var count = 0; count < capacity; count++) {
  12048. indices.push(index);
  12049. indices.push(index + 1);
  12050. indices.push(index + 2);
  12051. indices.push(index);
  12052. indices.push(index + 2);
  12053. indices.push(index + 3);
  12054. index += 4;
  12055. }
  12056. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12057. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12058. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12059. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12060. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12061. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12062. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12063. };
  12064. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12065. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12066. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12067. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12068. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12069. };
  12070. }
  12071. ParticleSystem.prototype.getCapacity = function () {
  12072. return this._capacity;
  12073. };
  12074. ParticleSystem.prototype.isAlive = function () {
  12075. return this._alive;
  12076. };
  12077. ParticleSystem.prototype.isStarted = function () {
  12078. return this._started;
  12079. };
  12080. ParticleSystem.prototype.start = function () {
  12081. this._started = true;
  12082. this._stopped = false;
  12083. this._actualFrame = 0;
  12084. };
  12085. ParticleSystem.prototype.stop = function () {
  12086. this._stopped = true;
  12087. };
  12088. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12089. var offset = index * 11;
  12090. this._vertices[offset] = particle.position.x;
  12091. this._vertices[offset + 1] = particle.position.y;
  12092. this._vertices[offset + 2] = particle.position.z;
  12093. this._vertices[offset + 3] = particle.color.r;
  12094. this._vertices[offset + 4] = particle.color.g;
  12095. this._vertices[offset + 5] = particle.color.b;
  12096. this._vertices[offset + 6] = particle.color.a;
  12097. this._vertices[offset + 7] = particle.angle;
  12098. this._vertices[offset + 8] = particle.size;
  12099. this._vertices[offset + 9] = offsetX;
  12100. this._vertices[offset + 10] = offsetY;
  12101. };
  12102. ParticleSystem.prototype._update = function (newParticles) {
  12103. this._alive = this.particles.length > 0;
  12104. for (var index = 0; index < this.particles.length; index++) {
  12105. var particle = this.particles[index];
  12106. particle.age += this._scaledUpdateSpeed;
  12107. if (particle.age >= particle.lifeTime) {
  12108. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12109. index--;
  12110. continue;
  12111. } else {
  12112. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12113. particle.color.addInPlace(this._scaledColorStep);
  12114. if (particle.color.a < 0)
  12115. particle.color.a = 0;
  12116. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12117. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12118. particle.position.addInPlace(this._scaledDirection);
  12119. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12120. particle.direction.addInPlace(this._scaledGravity);
  12121. }
  12122. }
  12123. var worldMatrix;
  12124. if (this.emitter.position) {
  12125. worldMatrix = this.emitter.getWorldMatrix();
  12126. } else {
  12127. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12128. }
  12129. for (index = 0; index < newParticles; index++) {
  12130. if (this.particles.length == this._capacity) {
  12131. break;
  12132. }
  12133. if (this._stockParticles.length !== 0) {
  12134. particle = this._stockParticles.pop();
  12135. particle.age = 0;
  12136. } else {
  12137. particle = new BABYLON.Particle();
  12138. }
  12139. this.particles.push(particle);
  12140. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12141. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12142. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12143. particle.size = randomNumber(this.minSize, this.maxSize);
  12144. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12145. this.startPositionFunction(worldMatrix, particle.position);
  12146. var step = randomNumber(0, 1.0);
  12147. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12148. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12149. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12150. }
  12151. };
  12152. ParticleSystem.prototype._getEffect = function () {
  12153. if (this._customEffect) {
  12154. return this._customEffect;
  12155. }
  12156. ;
  12157. var defines = [];
  12158. if (this._scene.clipPlane) {
  12159. defines.push("#define CLIPPLANE");
  12160. }
  12161. var join = defines.join("\n");
  12162. if (this._cachedDefines != join) {
  12163. this._cachedDefines = join;
  12164. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12165. }
  12166. return this._effect;
  12167. };
  12168. ParticleSystem.prototype.animate = function () {
  12169. if (!this._started)
  12170. return;
  12171. var effect = this._getEffect();
  12172. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12173. return;
  12174. if (this._currentRenderId === this._scene.getRenderId()) {
  12175. return;
  12176. }
  12177. this._currentRenderId = this._scene.getRenderId();
  12178. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12179. var emitCout;
  12180. if (this.manualEmitCount > -1) {
  12181. emitCout = this.manualEmitCount;
  12182. this.manualEmitCount = 0;
  12183. } else {
  12184. emitCout = this.emitRate;
  12185. }
  12186. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12187. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12188. if (this._newPartsExcess > 1.0) {
  12189. newParticles += this._newPartsExcess >> 0;
  12190. this._newPartsExcess -= this._newPartsExcess >> 0;
  12191. }
  12192. this._alive = false;
  12193. if (!this._stopped) {
  12194. this._actualFrame += this._scaledUpdateSpeed;
  12195. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12196. this.stop();
  12197. } else {
  12198. newParticles = 0;
  12199. }
  12200. this._update(newParticles);
  12201. if (this._stopped) {
  12202. if (!this._alive) {
  12203. this._started = false;
  12204. if (this.disposeOnStop) {
  12205. this._scene._toBeDisposed.push(this);
  12206. }
  12207. }
  12208. }
  12209. var offset = 0;
  12210. for (var index = 0; index < this.particles.length; index++) {
  12211. var particle = this.particles[index];
  12212. this._appendParticleVertex(offset++, particle, 0, 0);
  12213. this._appendParticleVertex(offset++, particle, 1, 0);
  12214. this._appendParticleVertex(offset++, particle, 1, 1);
  12215. this._appendParticleVertex(offset++, particle, 0, 1);
  12216. }
  12217. var engine = this._scene.getEngine();
  12218. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12219. };
  12220. ParticleSystem.prototype.render = function () {
  12221. var effect = this._getEffect();
  12222. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12223. return 0;
  12224. var engine = this._scene.getEngine();
  12225. engine.enableEffect(effect);
  12226. var viewMatrix = this._scene.getViewMatrix();
  12227. effect.setTexture("diffuseSampler", this.particleTexture);
  12228. effect.setMatrix("view", viewMatrix);
  12229. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12230. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12231. if (this._scene.clipPlane) {
  12232. var clipPlane = this._scene.clipPlane;
  12233. var invView = viewMatrix.clone();
  12234. invView.invert();
  12235. effect.setMatrix("invView", invView);
  12236. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12237. }
  12238. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12239. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12240. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12241. } else {
  12242. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12243. }
  12244. if (this.forceDepthWrite) {
  12245. engine.setDepthWrite(true);
  12246. }
  12247. engine.draw(true, 0, this.particles.length * 6);
  12248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12249. return this.particles.length;
  12250. };
  12251. ParticleSystem.prototype.dispose = function () {
  12252. if (this._vertexBuffer) {
  12253. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12254. this._vertexBuffer = null;
  12255. }
  12256. if (this._indexBuffer) {
  12257. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12258. this._indexBuffer = null;
  12259. }
  12260. if (this.particleTexture) {
  12261. this.particleTexture.dispose();
  12262. this.particleTexture = null;
  12263. }
  12264. var index = this._scene.particleSystems.indexOf(this);
  12265. this._scene.particleSystems.splice(index, 1);
  12266. if (this.onDispose) {
  12267. this.onDispose();
  12268. }
  12269. };
  12270. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12271. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12272. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12273. if (newEmitter === undefined) {
  12274. newEmitter = this.emitter;
  12275. }
  12276. result.emitter = newEmitter;
  12277. if (this.particleTexture) {
  12278. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12279. }
  12280. result.start();
  12281. return result;
  12282. };
  12283. ParticleSystem.BLENDMODE_ONEONE = 0;
  12284. ParticleSystem.BLENDMODE_STANDARD = 1;
  12285. return ParticleSystem;
  12286. })();
  12287. BABYLON.ParticleSystem = ParticleSystem;
  12288. })(BABYLON || (BABYLON = {}));
  12289. var BABYLON;
  12290. (function (BABYLON) {
  12291. var Animation = (function () {
  12292. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12293. this.name = name;
  12294. this.targetProperty = targetProperty;
  12295. this.framePerSecond = framePerSecond;
  12296. this.dataType = dataType;
  12297. this.loopMode = loopMode;
  12298. this._offsetsCache = {};
  12299. this._highLimitsCache = {};
  12300. this._stopped = false;
  12301. this.targetPropertyPath = targetProperty.split(".");
  12302. this.dataType = dataType;
  12303. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12304. }
  12305. Animation.prototype.isStopped = function () {
  12306. return this._stopped;
  12307. };
  12308. Animation.prototype.getKeys = function () {
  12309. return this._keys;
  12310. };
  12311. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12312. return startValue + (endValue - startValue) * gradient;
  12313. };
  12314. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12315. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12316. };
  12317. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12318. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12319. };
  12320. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12321. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12322. };
  12323. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12324. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12325. };
  12326. Animation.prototype.clone = function () {
  12327. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12328. clone.setKeys(this._keys);
  12329. return clone;
  12330. };
  12331. Animation.prototype.setKeys = function (values) {
  12332. this._keys = values.slice(0);
  12333. this._offsetsCache = {};
  12334. this._highLimitsCache = {};
  12335. };
  12336. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12337. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12338. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12339. }
  12340. this.currentFrame = currentFrame;
  12341. for (var key = 0; key < this._keys.length; key++) {
  12342. if (this._keys[key + 1].frame >= currentFrame) {
  12343. var startValue = this._keys[key].value;
  12344. var endValue = this._keys[key + 1].value;
  12345. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12346. switch (this.dataType) {
  12347. case Animation.ANIMATIONTYPE_FLOAT:
  12348. switch (loopMode) {
  12349. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12350. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12351. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12352. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12353. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12354. }
  12355. break;
  12356. case Animation.ANIMATIONTYPE_QUATERNION:
  12357. var quaternion = null;
  12358. switch (loopMode) {
  12359. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12360. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12361. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12362. break;
  12363. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12364. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12365. break;
  12366. }
  12367. return quaternion;
  12368. case Animation.ANIMATIONTYPE_VECTOR3:
  12369. switch (loopMode) {
  12370. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12371. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12372. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12373. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12374. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12375. }
  12376. case Animation.ANIMATIONTYPE_VECTOR2:
  12377. switch (loopMode) {
  12378. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12379. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12380. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12381. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12382. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12383. }
  12384. case Animation.ANIMATIONTYPE_COLOR3:
  12385. switch (loopMode) {
  12386. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12387. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12388. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12389. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12390. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12391. }
  12392. case Animation.ANIMATIONTYPE_MATRIX:
  12393. switch (loopMode) {
  12394. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12395. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12396. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12397. return startValue;
  12398. }
  12399. default:
  12400. break;
  12401. }
  12402. break;
  12403. }
  12404. }
  12405. return this._keys[this._keys.length - 1].value;
  12406. };
  12407. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12408. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12409. this._stopped = true;
  12410. return false;
  12411. }
  12412. var returnValue = true;
  12413. if (this._keys[0].frame != 0) {
  12414. var newKey = {
  12415. frame: 0,
  12416. value: this._keys[0].value
  12417. };
  12418. this._keys.splice(0, 0, newKey);
  12419. }
  12420. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12421. from = this._keys[0].frame;
  12422. }
  12423. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12424. to = this._keys[this._keys.length - 1].frame;
  12425. }
  12426. var range = to - from;
  12427. var offsetValue;
  12428. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12429. if (ratio > range && !loop) {
  12430. returnValue = false;
  12431. highLimitValue = this._keys[this._keys.length - 1].value;
  12432. } else {
  12433. var highLimitValue = 0;
  12434. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12435. var keyOffset = to.toString() + from.toString();
  12436. if (!this._offsetsCache[keyOffset]) {
  12437. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12438. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12439. switch (this.dataType) {
  12440. case Animation.ANIMATIONTYPE_FLOAT:
  12441. this._offsetsCache[keyOffset] = toValue - fromValue;
  12442. break;
  12443. case Animation.ANIMATIONTYPE_QUATERNION:
  12444. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12445. break;
  12446. case Animation.ANIMATIONTYPE_VECTOR3:
  12447. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12448. case Animation.ANIMATIONTYPE_VECTOR2:
  12449. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12450. case Animation.ANIMATIONTYPE_COLOR3:
  12451. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12452. default:
  12453. break;
  12454. }
  12455. this._highLimitsCache[keyOffset] = toValue;
  12456. }
  12457. highLimitValue = this._highLimitsCache[keyOffset];
  12458. offsetValue = this._offsetsCache[keyOffset];
  12459. }
  12460. }
  12461. if (offsetValue === undefined) {
  12462. switch (this.dataType) {
  12463. case Animation.ANIMATIONTYPE_FLOAT:
  12464. offsetValue = 0;
  12465. break;
  12466. case Animation.ANIMATIONTYPE_QUATERNION:
  12467. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12468. break;
  12469. case Animation.ANIMATIONTYPE_VECTOR3:
  12470. offsetValue = BABYLON.Vector3.Zero();
  12471. break;
  12472. case Animation.ANIMATIONTYPE_VECTOR2:
  12473. offsetValue = BABYLON.Vector2.Zero();
  12474. break;
  12475. case Animation.ANIMATIONTYPE_COLOR3:
  12476. offsetValue = BABYLON.Color3.Black();
  12477. }
  12478. }
  12479. var repeatCount = (ratio / range) >> 0;
  12480. var currentFrame = returnValue ? from + ratio % range : to;
  12481. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12482. if (this.targetPropertyPath.length > 1) {
  12483. var property = this._target[this.targetPropertyPath[0]];
  12484. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12485. property = property[this.targetPropertyPath[index]];
  12486. }
  12487. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12488. } else {
  12489. this._target[this.targetPropertyPath[0]] = currentValue;
  12490. }
  12491. if (this._target.markAsDirty) {
  12492. this._target.markAsDirty(this.targetProperty);
  12493. }
  12494. if (!returnValue) {
  12495. this._stopped = true;
  12496. }
  12497. return returnValue;
  12498. };
  12499. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12500. get: function () {
  12501. return Animation._ANIMATIONTYPE_FLOAT;
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12507. get: function () {
  12508. return Animation._ANIMATIONTYPE_VECTOR3;
  12509. },
  12510. enumerable: true,
  12511. configurable: true
  12512. });
  12513. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12514. get: function () {
  12515. return Animation._ANIMATIONTYPE_VECTOR2;
  12516. },
  12517. enumerable: true,
  12518. configurable: true
  12519. });
  12520. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12521. get: function () {
  12522. return Animation._ANIMATIONTYPE_QUATERNION;
  12523. },
  12524. enumerable: true,
  12525. configurable: true
  12526. });
  12527. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12528. get: function () {
  12529. return Animation._ANIMATIONTYPE_MATRIX;
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12535. get: function () {
  12536. return Animation._ANIMATIONTYPE_COLOR3;
  12537. },
  12538. enumerable: true,
  12539. configurable: true
  12540. });
  12541. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12542. get: function () {
  12543. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12549. get: function () {
  12550. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12551. },
  12552. enumerable: true,
  12553. configurable: true
  12554. });
  12555. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12556. get: function () {
  12557. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12558. },
  12559. enumerable: true,
  12560. configurable: true
  12561. });
  12562. Animation._ANIMATIONTYPE_FLOAT = 0;
  12563. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12564. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12565. Animation._ANIMATIONTYPE_MATRIX = 3;
  12566. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12567. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12568. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12569. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12570. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12571. return Animation;
  12572. })();
  12573. BABYLON.Animation = Animation;
  12574. })(BABYLON || (BABYLON = {}));
  12575. var BABYLON;
  12576. (function (BABYLON) {
  12577. var Animatable = (function () {
  12578. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12579. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12580. if (typeof toFrame === "undefined") { toFrame = 100; }
  12581. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12582. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12583. this.target = target;
  12584. this.fromFrame = fromFrame;
  12585. this.toFrame = toFrame;
  12586. this.loopAnimation = loopAnimation;
  12587. this.speedRatio = speedRatio;
  12588. this.onAnimationEnd = onAnimationEnd;
  12589. this._animations = new Array();
  12590. this._paused = false;
  12591. this.animationStarted = false;
  12592. if (animations) {
  12593. this.appendAnimations(target, animations);
  12594. }
  12595. this._scene = scene;
  12596. scene._activeAnimatables.push(this);
  12597. }
  12598. Animatable.prototype.appendAnimations = function (target, animations) {
  12599. for (var index = 0; index < animations.length; index++) {
  12600. var animation = animations[index];
  12601. animation._target = target;
  12602. this._animations.push(animation);
  12603. }
  12604. };
  12605. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12606. var animations = this._animations;
  12607. for (var index = 0; index < animations.length; index++) {
  12608. if (animations[index].targetProperty === property) {
  12609. return animations[index];
  12610. }
  12611. }
  12612. return null;
  12613. };
  12614. Animatable.prototype.pause = function () {
  12615. this._paused = true;
  12616. };
  12617. Animatable.prototype.restart = function () {
  12618. this._paused = false;
  12619. };
  12620. Animatable.prototype.stop = function () {
  12621. var index = this._scene._activeAnimatables.indexOf(this);
  12622. if (index > -1) {
  12623. this._scene._activeAnimatables.splice(index, 1);
  12624. }
  12625. if (this.onAnimationEnd) {
  12626. this.onAnimationEnd();
  12627. }
  12628. };
  12629. Animatable.prototype._animate = function (delay) {
  12630. if (this._paused) {
  12631. return true;
  12632. }
  12633. if (!this._localDelayOffset) {
  12634. this._localDelayOffset = delay;
  12635. }
  12636. var running = false;
  12637. var animations = this._animations;
  12638. for (var index = 0; index < animations.length; index++) {
  12639. var animation = animations[index];
  12640. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12641. running = running || isRunning;
  12642. }
  12643. if (!running && this.onAnimationEnd) {
  12644. this.onAnimationEnd();
  12645. }
  12646. return running;
  12647. };
  12648. return Animatable;
  12649. })();
  12650. BABYLON.Animatable = Animatable;
  12651. })(BABYLON || (BABYLON = {}));
  12652. var BABYLON;
  12653. (function (BABYLON) {
  12654. var Octree = (function () {
  12655. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  12656. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  12657. this.maxDepth = maxDepth;
  12658. this.dynamicContent = new Array();
  12659. this._maxBlockCapacity = maxBlockCapacity || 64;
  12660. this._selectionContent = new BABYLON.SmartArray(1024);
  12661. this._creationFunc = creationFunc;
  12662. }
  12663. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12664. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12665. };
  12666. Octree.prototype.addMesh = function (entry) {
  12667. for (var index = 0; index < this.blocks.length; index++) {
  12668. var block = this.blocks[index];
  12669. block.addEntry(entry);
  12670. }
  12671. };
  12672. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12673. this._selectionContent.reset();
  12674. for (var index = 0; index < this.blocks.length; index++) {
  12675. var block = this.blocks[index];
  12676. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12677. }
  12678. if (allowDuplicate) {
  12679. this._selectionContent.concat(this.dynamicContent);
  12680. } else {
  12681. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12682. }
  12683. return this._selectionContent;
  12684. };
  12685. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12686. this._selectionContent.reset();
  12687. for (var index = 0; index < this.blocks.length; index++) {
  12688. var block = this.blocks[index];
  12689. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12690. }
  12691. if (allowDuplicate) {
  12692. this._selectionContent.concat(this.dynamicContent);
  12693. } else {
  12694. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12695. }
  12696. return this._selectionContent;
  12697. };
  12698. Octree.prototype.intersectsRay = function (ray) {
  12699. this._selectionContent.reset();
  12700. for (var index = 0; index < this.blocks.length; index++) {
  12701. var block = this.blocks[index];
  12702. block.intersectsRay(ray, this._selectionContent);
  12703. }
  12704. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12705. return this._selectionContent;
  12706. };
  12707. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12708. target.blocks = new Array();
  12709. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12710. for (var x = 0; x < 2; x++) {
  12711. for (var y = 0; y < 2; y++) {
  12712. for (var z = 0; z < 2; z++) {
  12713. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12714. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12715. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12716. block.addEntries(entries);
  12717. target.blocks.push(block);
  12718. }
  12719. }
  12720. }
  12721. };
  12722. Octree.CreationFuncForMeshes = function (entry, block) {
  12723. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12724. block.entries.push(entry);
  12725. }
  12726. };
  12727. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12728. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12729. block.entries.push(entry);
  12730. }
  12731. };
  12732. return Octree;
  12733. })();
  12734. BABYLON.Octree = Octree;
  12735. })(BABYLON || (BABYLON = {}));
  12736. var BABYLON;
  12737. (function (BABYLON) {
  12738. var OctreeBlock = (function () {
  12739. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12740. this.entries = new Array();
  12741. this._boundingVectors = new Array();
  12742. this._capacity = capacity;
  12743. this._depth = depth;
  12744. this._maxDepth = maxDepth;
  12745. this._creationFunc = creationFunc;
  12746. this._minPoint = minPoint;
  12747. this._maxPoint = maxPoint;
  12748. this._boundingVectors.push(minPoint.clone());
  12749. this._boundingVectors.push(maxPoint.clone());
  12750. this._boundingVectors.push(minPoint.clone());
  12751. this._boundingVectors[2].x = maxPoint.x;
  12752. this._boundingVectors.push(minPoint.clone());
  12753. this._boundingVectors[3].y = maxPoint.y;
  12754. this._boundingVectors.push(minPoint.clone());
  12755. this._boundingVectors[4].z = maxPoint.z;
  12756. this._boundingVectors.push(maxPoint.clone());
  12757. this._boundingVectors[5].z = minPoint.z;
  12758. this._boundingVectors.push(maxPoint.clone());
  12759. this._boundingVectors[6].x = minPoint.x;
  12760. this._boundingVectors.push(maxPoint.clone());
  12761. this._boundingVectors[7].y = minPoint.y;
  12762. }
  12763. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12764. get: function () {
  12765. return this._capacity;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12771. get: function () {
  12772. return this._minPoint;
  12773. },
  12774. enumerable: true,
  12775. configurable: true
  12776. });
  12777. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12778. get: function () {
  12779. return this._maxPoint;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. OctreeBlock.prototype.addEntry = function (entry) {
  12785. if (this.blocks) {
  12786. for (var index = 0; index < this.blocks.length; index++) {
  12787. var block = this.blocks[index];
  12788. block.addEntry(entry);
  12789. }
  12790. return;
  12791. }
  12792. this._creationFunc(entry, this);
  12793. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12794. this.createInnerBlocks();
  12795. }
  12796. };
  12797. OctreeBlock.prototype.addEntries = function (entries) {
  12798. for (var index = 0; index < entries.length; index++) {
  12799. var mesh = entries[index];
  12800. this.addEntry(mesh);
  12801. }
  12802. };
  12803. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12804. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12805. if (this.blocks) {
  12806. for (var index = 0; index < this.blocks.length; index++) {
  12807. var block = this.blocks[index];
  12808. block.select(frustumPlanes, selection, allowDuplicate);
  12809. }
  12810. return;
  12811. }
  12812. if (allowDuplicate) {
  12813. selection.concat(this.entries);
  12814. } else {
  12815. selection.concatWithNoDuplicate(this.entries);
  12816. }
  12817. }
  12818. };
  12819. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12820. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12821. if (this.blocks) {
  12822. for (var index = 0; index < this.blocks.length; index++) {
  12823. var block = this.blocks[index];
  12824. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12825. }
  12826. return;
  12827. }
  12828. if (allowDuplicate) {
  12829. selection.concat(this.entries);
  12830. } else {
  12831. selection.concatWithNoDuplicate(this.entries);
  12832. }
  12833. }
  12834. };
  12835. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12836. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12837. if (this.blocks) {
  12838. for (var index = 0; index < this.blocks.length; index++) {
  12839. var block = this.blocks[index];
  12840. block.intersectsRay(ray, selection);
  12841. }
  12842. return;
  12843. }
  12844. selection.concatWithNoDuplicate(this.entries);
  12845. }
  12846. };
  12847. OctreeBlock.prototype.createInnerBlocks = function () {
  12848. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12849. };
  12850. return OctreeBlock;
  12851. })();
  12852. BABYLON.OctreeBlock = OctreeBlock;
  12853. })(BABYLON || (BABYLON = {}));
  12854. var BABYLON;
  12855. (function (BABYLON) {
  12856. var Bone = (function () {
  12857. function Bone(name, skeleton, parentBone, matrix) {
  12858. this.name = name;
  12859. this.children = new Array();
  12860. this.animations = new Array();
  12861. this._worldTransform = new BABYLON.Matrix();
  12862. this._absoluteTransform = new BABYLON.Matrix();
  12863. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12864. this._skeleton = skeleton;
  12865. this._matrix = matrix;
  12866. this._baseMatrix = matrix;
  12867. skeleton.bones.push(this);
  12868. if (parentBone) {
  12869. this._parent = parentBone;
  12870. parentBone.children.push(this);
  12871. } else {
  12872. this._parent = null;
  12873. }
  12874. this._updateDifferenceMatrix();
  12875. }
  12876. Bone.prototype.getParent = function () {
  12877. return this._parent;
  12878. };
  12879. Bone.prototype.getLocalMatrix = function () {
  12880. return this._matrix;
  12881. };
  12882. Bone.prototype.getBaseMatrix = function () {
  12883. return this._baseMatrix;
  12884. };
  12885. Bone.prototype.getWorldMatrix = function () {
  12886. return this._worldTransform;
  12887. };
  12888. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12889. return this._invertedAbsoluteTransform;
  12890. };
  12891. Bone.prototype.getAbsoluteMatrix = function () {
  12892. var matrix = this._matrix.clone();
  12893. var parent = this._parent;
  12894. while (parent) {
  12895. matrix = matrix.multiply(parent.getLocalMatrix());
  12896. parent = parent.getParent();
  12897. }
  12898. return matrix;
  12899. };
  12900. Bone.prototype.updateMatrix = function (matrix) {
  12901. this._matrix = matrix;
  12902. this._skeleton._markAsDirty();
  12903. this._updateDifferenceMatrix();
  12904. };
  12905. Bone.prototype._updateDifferenceMatrix = function () {
  12906. if (this._parent) {
  12907. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12908. } else {
  12909. this._absoluteTransform.copyFrom(this._matrix);
  12910. }
  12911. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12912. for (var index = 0; index < this.children.length; index++) {
  12913. this.children[index]._updateDifferenceMatrix();
  12914. }
  12915. };
  12916. Bone.prototype.markAsDirty = function () {
  12917. this._skeleton._markAsDirty();
  12918. };
  12919. return Bone;
  12920. })();
  12921. BABYLON.Bone = Bone;
  12922. })(BABYLON || (BABYLON = {}));
  12923. var BABYLON;
  12924. (function (BABYLON) {
  12925. var Skeleton = (function () {
  12926. function Skeleton(name, id, scene) {
  12927. this.name = name;
  12928. this.id = id;
  12929. this.bones = new Array();
  12930. this._isDirty = true;
  12931. this._identity = BABYLON.Matrix.Identity();
  12932. this.bones = [];
  12933. this._scene = scene;
  12934. scene.skeletons.push(this);
  12935. }
  12936. Skeleton.prototype.getTransformMatrices = function () {
  12937. return this._transformMatrices;
  12938. };
  12939. Skeleton.prototype._markAsDirty = function () {
  12940. this._isDirty = true;
  12941. };
  12942. Skeleton.prototype.prepare = function () {
  12943. if (!this._isDirty) {
  12944. return;
  12945. }
  12946. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12947. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12948. }
  12949. for (var index = 0; index < this.bones.length; index++) {
  12950. var bone = this.bones[index];
  12951. var parentBone = bone.getParent();
  12952. if (parentBone) {
  12953. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12954. } else {
  12955. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12956. }
  12957. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12958. }
  12959. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12960. this._isDirty = false;
  12961. };
  12962. Skeleton.prototype.getAnimatables = function () {
  12963. if (!this._animatables || this._animatables.length != this.bones.length) {
  12964. this._animatables = [];
  12965. for (var index = 0; index < this.bones.length; index++) {
  12966. this._animatables.push(this.bones[index]);
  12967. }
  12968. }
  12969. return this._animatables;
  12970. };
  12971. Skeleton.prototype.clone = function (name, id) {
  12972. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12973. for (var index = 0; index < this.bones.length; index++) {
  12974. var source = this.bones[index];
  12975. var parentBone = null;
  12976. if (source.getParent()) {
  12977. var parentIndex = this.bones.indexOf(source.getParent());
  12978. parentBone = result.bones[parentIndex];
  12979. }
  12980. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12981. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12982. }
  12983. return result;
  12984. };
  12985. return Skeleton;
  12986. })();
  12987. BABYLON.Skeleton = Skeleton;
  12988. })(BABYLON || (BABYLON = {}));
  12989. var BABYLON;
  12990. (function (BABYLON) {
  12991. var PostProcess = (function () {
  12992. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12993. this.name = name;
  12994. this.width = -1;
  12995. this.height = -1;
  12996. this._reusable = false;
  12997. this._textures = new BABYLON.SmartArray(2);
  12998. this._currentRenderTextureInd = 0;
  12999. if (camera != null) {
  13000. this._camera = camera;
  13001. this._scene = camera.getScene();
  13002. camera.attachPostProcess(this);
  13003. this._engine = this._scene.getEngine();
  13004. } else {
  13005. this._engine = engine;
  13006. }
  13007. this._renderRatio = ratio;
  13008. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13009. this._reusable = reusable || false;
  13010. samplers = samplers || [];
  13011. samplers.push("textureSampler");
  13012. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13013. }
  13014. PostProcess.prototype.isReusable = function () {
  13015. return this._reusable;
  13016. };
  13017. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13018. camera = camera || this._camera;
  13019. var scene = camera.getScene();
  13020. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13021. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13022. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13023. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13024. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13025. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13026. if (this._textures.length > 0) {
  13027. for (var i = 0; i < this._textures.length; i++) {
  13028. this._engine._releaseTexture(this._textures.data[i]);
  13029. }
  13030. this._textures.reset();
  13031. }
  13032. this.width = desiredWidth;
  13033. this.height = desiredHeight;
  13034. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  13035. if (this._reusable) {
  13036. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  13037. }
  13038. if (this.onSizeChanged) {
  13039. this.onSizeChanged();
  13040. }
  13041. }
  13042. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13043. if (this.onActivate) {
  13044. this.onActivate(camera);
  13045. }
  13046. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13047. if (this._reusable) {
  13048. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13049. }
  13050. };
  13051. PostProcess.prototype.apply = function () {
  13052. if (!this._effect.isReady())
  13053. return null;
  13054. this._engine.enableEffect(this._effect);
  13055. this._engine.setState(false);
  13056. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13057. this._engine.setDepthBuffer(false);
  13058. this._engine.setDepthWrite(false);
  13059. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13060. if (this.onApply) {
  13061. this.onApply(this._effect);
  13062. }
  13063. return this._effect;
  13064. };
  13065. PostProcess.prototype.dispose = function (camera) {
  13066. camera = camera || this._camera;
  13067. if (this._textures.length > 0) {
  13068. for (var i = 0; i < this._textures.length; i++) {
  13069. this._engine._releaseTexture(this._textures.data[i]);
  13070. }
  13071. this._textures.reset();
  13072. }
  13073. camera.detachPostProcess(this);
  13074. var index = camera._postProcesses.indexOf(this);
  13075. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13076. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13077. }
  13078. };
  13079. return PostProcess;
  13080. })();
  13081. BABYLON.PostProcess = PostProcess;
  13082. })(BABYLON || (BABYLON = {}));
  13083. var BABYLON;
  13084. (function (BABYLON) {
  13085. var PostProcessManager = (function () {
  13086. function PostProcessManager(scene) {
  13087. this._vertexDeclaration = [2];
  13088. this._vertexStrideSize = 2 * 4;
  13089. this._scene = scene;
  13090. var vertices = [];
  13091. vertices.push(1, 1);
  13092. vertices.push(-1, 1);
  13093. vertices.push(-1, -1);
  13094. vertices.push(1, -1);
  13095. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13096. var indices = [];
  13097. indices.push(0);
  13098. indices.push(1);
  13099. indices.push(2);
  13100. indices.push(0);
  13101. indices.push(2);
  13102. indices.push(3);
  13103. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13104. }
  13105. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13106. var postProcesses = this._scene.activeCamera._postProcesses;
  13107. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13108. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13109. return false;
  13110. }
  13111. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13112. return true;
  13113. };
  13114. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13115. var postProcesses = this._scene.activeCamera._postProcesses;
  13116. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13117. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13118. return;
  13119. }
  13120. var engine = this._scene.getEngine();
  13121. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13122. if (index < postProcessesTakenIndices.length - 1) {
  13123. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13124. } else {
  13125. if (targetTexture) {
  13126. engine.bindFramebuffer(targetTexture);
  13127. } else {
  13128. engine.restoreDefaultFramebuffer();
  13129. }
  13130. }
  13131. if (doNotPresent) {
  13132. break;
  13133. }
  13134. var pp = postProcesses[postProcessesTakenIndices[index]];
  13135. var effect = pp.apply();
  13136. if (effect) {
  13137. if (pp.onBeforeRender) {
  13138. pp.onBeforeRender(effect);
  13139. }
  13140. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13141. engine.draw(true, 0, 6);
  13142. }
  13143. }
  13144. engine.setDepthBuffer(true);
  13145. engine.setDepthWrite(true);
  13146. };
  13147. PostProcessManager.prototype.dispose = function () {
  13148. if (this._vertexBuffer) {
  13149. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13150. this._vertexBuffer = null;
  13151. }
  13152. if (this._indexBuffer) {
  13153. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13154. this._indexBuffer = null;
  13155. }
  13156. };
  13157. return PostProcessManager;
  13158. })();
  13159. BABYLON.PostProcessManager = PostProcessManager;
  13160. })(BABYLON || (BABYLON = {}));
  13161. var __extends = this.__extends || function (d, b) {
  13162. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13163. function __() { this.constructor = d; }
  13164. __.prototype = b.prototype;
  13165. d.prototype = new __();
  13166. };
  13167. var BABYLON;
  13168. (function (BABYLON) {
  13169. var PassPostProcess = (function (_super) {
  13170. __extends(PassPostProcess, _super);
  13171. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13172. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13173. }
  13174. return PassPostProcess;
  13175. })(BABYLON.PostProcess);
  13176. BABYLON.PassPostProcess = PassPostProcess;
  13177. })(BABYLON || (BABYLON = {}));
  13178. var __extends = this.__extends || function (d, b) {
  13179. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13180. function __() { this.constructor = d; }
  13181. __.prototype = b.prototype;
  13182. d.prototype = new __();
  13183. };
  13184. var BABYLON;
  13185. (function (BABYLON) {
  13186. var BlurPostProcess = (function (_super) {
  13187. __extends(BlurPostProcess, _super);
  13188. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13189. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13190. var _this = this;
  13191. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13192. this.direction = direction;
  13193. this.blurWidth = blurWidth;
  13194. this.onApply = function (effect) {
  13195. effect.setFloat2("screenSize", _this.width, _this.height);
  13196. effect.setVector2("direction", _this.direction);
  13197. effect.setFloat("blurWidth", _this.blurWidth);
  13198. };
  13199. }
  13200. return BlurPostProcess;
  13201. })(BABYLON.PostProcess);
  13202. BABYLON.BlurPostProcess = BlurPostProcess;
  13203. })(BABYLON || (BABYLON = {}));
  13204. var __extends = this.__extends || function (d, b) {
  13205. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13206. function __() { this.constructor = d; }
  13207. __.prototype = b.prototype;
  13208. d.prototype = new __();
  13209. };
  13210. var BABYLON;
  13211. (function (BABYLON) {
  13212. var FilterPostProcess = (function (_super) {
  13213. __extends(FilterPostProcess, _super);
  13214. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13215. var _this = this;
  13216. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13217. this.kernelMatrix = kernelMatrix;
  13218. this.onApply = function (effect) {
  13219. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13220. };
  13221. }
  13222. return FilterPostProcess;
  13223. })(BABYLON.PostProcess);
  13224. BABYLON.FilterPostProcess = FilterPostProcess;
  13225. })(BABYLON || (BABYLON = {}));
  13226. var __extends = this.__extends || function (d, b) {
  13227. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13228. function __() { this.constructor = d; }
  13229. __.prototype = b.prototype;
  13230. d.prototype = new __();
  13231. };
  13232. var BABYLON;
  13233. (function (BABYLON) {
  13234. var RefractionPostProcess = (function (_super) {
  13235. __extends(RefractionPostProcess, _super);
  13236. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13237. var _this = this;
  13238. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13239. this.color = color;
  13240. this.depth = depth;
  13241. this.colorLevel = colorLevel;
  13242. this.onActivate = function (cam) {
  13243. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13244. };
  13245. this.onApply = function (effect) {
  13246. effect.setColor3("baseColor", _this.color);
  13247. effect.setFloat("depth", _this.depth);
  13248. effect.setFloat("colorLevel", _this.colorLevel);
  13249. effect.setTexture("refractionSampler", _this._refRexture);
  13250. };
  13251. }
  13252. RefractionPostProcess.prototype.dispose = function (camera) {
  13253. if (this._refRexture) {
  13254. this._refRexture.dispose();
  13255. }
  13256. _super.prototype.dispose.call(this, camera);
  13257. };
  13258. return RefractionPostProcess;
  13259. })(BABYLON.PostProcess);
  13260. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13261. })(BABYLON || (BABYLON = {}));
  13262. var __extends = this.__extends || function (d, b) {
  13263. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13264. function __() { this.constructor = d; }
  13265. __.prototype = b.prototype;
  13266. d.prototype = new __();
  13267. };
  13268. var BABYLON;
  13269. (function (BABYLON) {
  13270. var BlackAndWhitePostProcess = (function (_super) {
  13271. __extends(BlackAndWhitePostProcess, _super);
  13272. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13273. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13274. }
  13275. return BlackAndWhitePostProcess;
  13276. })(BABYLON.PostProcess);
  13277. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13278. })(BABYLON || (BABYLON = {}));
  13279. var __extends = this.__extends || function (d, b) {
  13280. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13281. function __() { this.constructor = d; }
  13282. __.prototype = b.prototype;
  13283. d.prototype = new __();
  13284. };
  13285. var BABYLON;
  13286. (function (BABYLON) {
  13287. var ConvolutionPostProcess = (function (_super) {
  13288. __extends(ConvolutionPostProcess, _super);
  13289. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13290. var _this = this;
  13291. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13292. this.kernel = kernel;
  13293. this.onApply = function (effect) {
  13294. effect.setFloat2("screenSize", _this.width, _this.height);
  13295. effect.setArray("kernel", _this.kernel);
  13296. };
  13297. }
  13298. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13299. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13300. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13301. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13302. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13303. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13304. return ConvolutionPostProcess;
  13305. })(BABYLON.PostProcess);
  13306. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13307. })(BABYLON || (BABYLON = {}));
  13308. var __extends = this.__extends || function (d, b) {
  13309. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13310. function __() { this.constructor = d; }
  13311. __.prototype = b.prototype;
  13312. d.prototype = new __();
  13313. };
  13314. var BABYLON;
  13315. (function (BABYLON) {
  13316. var FxaaPostProcess = (function (_super) {
  13317. __extends(FxaaPostProcess, _super);
  13318. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13319. var _this = this;
  13320. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13321. this.onSizeChanged = function () {
  13322. _this.texelWidth = 1.0 / _this.width;
  13323. _this.texelHeight = 1.0 / _this.height;
  13324. };
  13325. this.onApply = function (effect) {
  13326. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13327. };
  13328. }
  13329. return FxaaPostProcess;
  13330. })(BABYLON.PostProcess);
  13331. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13332. })(BABYLON || (BABYLON = {}));
  13333. var BABYLON;
  13334. (function (BABYLON) {
  13335. var LensFlare = (function () {
  13336. function LensFlare(size, position, color, imgUrl, system) {
  13337. this.size = size;
  13338. this.position = position;
  13339. this.dispose = function () {
  13340. if (this.texture) {
  13341. this.texture.dispose();
  13342. }
  13343. var index = this._system.lensFlares.indexOf(this);
  13344. this._system.lensFlares.splice(index, 1);
  13345. };
  13346. this.color = color || new BABYLON.Color3(1, 1, 1);
  13347. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13348. this._system = system;
  13349. system.lensFlares.push(this);
  13350. }
  13351. return LensFlare;
  13352. })();
  13353. BABYLON.LensFlare = LensFlare;
  13354. })(BABYLON || (BABYLON = {}));
  13355. var BABYLON;
  13356. (function (BABYLON) {
  13357. var LensFlareSystem = (function () {
  13358. function LensFlareSystem(name, emitter, scene) {
  13359. this.name = name;
  13360. this.lensFlares = new Array();
  13361. this.borderLimit = 300;
  13362. this._vertexDeclaration = [2];
  13363. this._vertexStrideSize = 2 * 4;
  13364. this._isEnabled = true;
  13365. this._scene = scene;
  13366. this._emitter = emitter;
  13367. scene.lensFlareSystems.push(this);
  13368. this.meshesSelectionPredicate = function (m) {
  13369. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13370. };
  13371. var vertices = [];
  13372. vertices.push(1, 1);
  13373. vertices.push(-1, 1);
  13374. vertices.push(-1, -1);
  13375. vertices.push(1, -1);
  13376. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13377. var indices = [];
  13378. indices.push(0);
  13379. indices.push(1);
  13380. indices.push(2);
  13381. indices.push(0);
  13382. indices.push(2);
  13383. indices.push(3);
  13384. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13385. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13386. }
  13387. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13388. get: function () {
  13389. return this._isEnabled;
  13390. },
  13391. set: function (value) {
  13392. this._isEnabled = value;
  13393. },
  13394. enumerable: true,
  13395. configurable: true
  13396. });
  13397. LensFlareSystem.prototype.getScene = function () {
  13398. return this._scene;
  13399. };
  13400. LensFlareSystem.prototype.getEmitter = function () {
  13401. return this._emitter;
  13402. };
  13403. LensFlareSystem.prototype.getEmitterPosition = function () {
  13404. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13405. };
  13406. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13407. var position = this.getEmitterPosition();
  13408. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13409. this._positionX = position.x;
  13410. this._positionY = position.y;
  13411. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13412. if (position.z > 0) {
  13413. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13414. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13415. return true;
  13416. }
  13417. }
  13418. return false;
  13419. };
  13420. LensFlareSystem.prototype._isVisible = function () {
  13421. if (!this._isEnabled) {
  13422. return false;
  13423. }
  13424. var emitterPosition = this.getEmitterPosition();
  13425. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13426. var distance = direction.length();
  13427. direction.normalize();
  13428. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13429. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13430. return !pickInfo.hit || pickInfo.distance > distance;
  13431. };
  13432. LensFlareSystem.prototype.render = function () {
  13433. if (!this._effect.isReady())
  13434. return false;
  13435. var engine = this._scene.getEngine();
  13436. var viewport = this._scene.activeCamera.viewport;
  13437. var globalViewport = viewport.toGlobal(engine);
  13438. if (!this.computeEffectivePosition(globalViewport)) {
  13439. return false;
  13440. }
  13441. if (!this._isVisible()) {
  13442. return false;
  13443. }
  13444. var awayX;
  13445. var awayY;
  13446. if (this._positionX < this.borderLimit + globalViewport.x) {
  13447. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13448. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13449. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13450. } else {
  13451. awayX = 0;
  13452. }
  13453. if (this._positionY < this.borderLimit + globalViewport.y) {
  13454. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13455. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13456. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13457. } else {
  13458. awayY = 0;
  13459. }
  13460. var away = (awayX > awayY) ? awayX : awayY;
  13461. if (away > this.borderLimit) {
  13462. away = this.borderLimit;
  13463. }
  13464. var intensity = 1.0 - (away / this.borderLimit);
  13465. if (intensity < 0) {
  13466. return false;
  13467. }
  13468. if (intensity > 1.0) {
  13469. intensity = 1.0;
  13470. }
  13471. var centerX = globalViewport.x + globalViewport.width / 2;
  13472. var centerY = globalViewport.y + globalViewport.height / 2;
  13473. var distX = centerX - this._positionX;
  13474. var distY = centerY - this._positionY;
  13475. engine.enableEffect(this._effect);
  13476. engine.setState(false);
  13477. engine.setDepthBuffer(false);
  13478. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13479. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13480. for (var index = 0; index < this.lensFlares.length; index++) {
  13481. var flare = this.lensFlares[index];
  13482. var x = centerX - (distX * flare.position);
  13483. var y = centerY - (distY * flare.position);
  13484. var cw = flare.size;
  13485. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13486. var cx = 2 * (x / globalViewport.width) - 1.0;
  13487. var cy = 1.0 - 2 * (y / globalViewport.height);
  13488. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13489. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13490. this._effect.setTexture("textureSampler", flare.texture);
  13491. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13492. engine.draw(true, 0, 6);
  13493. }
  13494. engine.setDepthBuffer(true);
  13495. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13496. return true;
  13497. };
  13498. LensFlareSystem.prototype.dispose = function () {
  13499. if (this._vertexBuffer) {
  13500. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13501. this._vertexBuffer = null;
  13502. }
  13503. if (this._indexBuffer) {
  13504. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13505. this._indexBuffer = null;
  13506. }
  13507. while (this.lensFlares.length) {
  13508. this.lensFlares[0].dispose();
  13509. }
  13510. var index = this._scene.lensFlareSystems.indexOf(this);
  13511. this._scene.lensFlareSystems.splice(index, 1);
  13512. };
  13513. return LensFlareSystem;
  13514. })();
  13515. BABYLON.LensFlareSystem = LensFlareSystem;
  13516. })(BABYLON || (BABYLON = {}));
  13517. var BABYLON;
  13518. (function (BABYLON) {
  13519. var IntersectionInfo = (function () {
  13520. function IntersectionInfo(bu, bv, distance) {
  13521. this.bu = bu;
  13522. this.bv = bv;
  13523. this.distance = distance;
  13524. this.faceId = 0;
  13525. }
  13526. return IntersectionInfo;
  13527. })();
  13528. BABYLON.IntersectionInfo = IntersectionInfo;
  13529. var PickingInfo = (function () {
  13530. function PickingInfo() {
  13531. this.hit = false;
  13532. this.distance = 0;
  13533. this.pickedPoint = null;
  13534. this.pickedMesh = null;
  13535. this.bu = 0;
  13536. this.bv = 0;
  13537. this.faceId = -1;
  13538. }
  13539. PickingInfo.prototype.getNormal = function () {
  13540. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13541. return null;
  13542. }
  13543. var indices = this.pickedMesh.getIndices();
  13544. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13545. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13546. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13547. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13548. normal0 = normal0.scale(this.bu);
  13549. normal1 = normal1.scale(this.bv);
  13550. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13551. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13552. };
  13553. PickingInfo.prototype.getTextureCoordinates = function () {
  13554. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13555. return null;
  13556. }
  13557. var indices = this.pickedMesh.getIndices();
  13558. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13559. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13560. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13561. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13562. uv0 = uv0.scale(this.bu);
  13563. uv1 = uv1.scale(this.bv);
  13564. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13565. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13566. };
  13567. return PickingInfo;
  13568. })();
  13569. BABYLON.PickingInfo = PickingInfo;
  13570. })(BABYLON || (BABYLON = {}));
  13571. var BABYLON;
  13572. (function (BABYLON) {
  13573. var FilesInput = (function () {
  13574. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13575. this.engine = p_engine;
  13576. this.canvas = p_canvas;
  13577. this.currentScene = p_scene;
  13578. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13579. this.progressCallback = p_progressCallback;
  13580. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13581. this.textureLoadingCallback = p_textureLoadingCallback;
  13582. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13583. }
  13584. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13585. var _this = this;
  13586. if (p_elementToMonitor) {
  13587. this.elementToMonitor = p_elementToMonitor;
  13588. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13589. _this.drag(e);
  13590. }, false);
  13591. this.elementToMonitor.addEventListener("dragover", function (e) {
  13592. _this.drag(e);
  13593. }, false);
  13594. this.elementToMonitor.addEventListener("drop", function (e) {
  13595. _this.drop(e);
  13596. }, false);
  13597. }
  13598. };
  13599. FilesInput.prototype.renderFunction = function () {
  13600. if (this.additionnalRenderLoopLogicCallback) {
  13601. this.additionnalRenderLoopLogicCallback();
  13602. }
  13603. if (this.currentScene) {
  13604. if (this.textureLoadingCallback) {
  13605. var remaining = this.currentScene.getWaitingItemsCount();
  13606. if (remaining > 0) {
  13607. this.textureLoadingCallback(remaining);
  13608. }
  13609. }
  13610. this.currentScene.render();
  13611. }
  13612. };
  13613. FilesInput.prototype.drag = function (e) {
  13614. e.stopPropagation();
  13615. e.preventDefault();
  13616. };
  13617. FilesInput.prototype.drop = function (eventDrop) {
  13618. eventDrop.stopPropagation();
  13619. eventDrop.preventDefault();
  13620. this.loadFiles(eventDrop);
  13621. };
  13622. FilesInput.prototype.loadFiles = function (event) {
  13623. var _this = this;
  13624. var that = this;
  13625. if (this.startingProcessingFilesCallback)
  13626. this.startingProcessingFilesCallback();
  13627. var sceneFileToLoad;
  13628. var filesToLoad;
  13629. if (event && event.dataTransfer && event.dataTransfer.files) {
  13630. filesToLoad = event.dataTransfer.files;
  13631. }
  13632. if (event && event.target && event.target.files) {
  13633. filesToLoad = event.target.files;
  13634. }
  13635. if (filesToLoad && filesToLoad.length > 0) {
  13636. for (var i = 0; i < filesToLoad.length; i++) {
  13637. switch (filesToLoad[i].type) {
  13638. case "image/jpeg":
  13639. case "image/png":
  13640. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13641. break;
  13642. case "image/targa":
  13643. case "image/vnd.ms-dds":
  13644. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13645. break;
  13646. default:
  13647. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  13648. sceneFileToLoad = filesToLoad[i];
  13649. }
  13650. break;
  13651. }
  13652. }
  13653. if (sceneFileToLoad) {
  13654. if (this.currentScene) {
  13655. this.engine.stopRenderLoop();
  13656. this.currentScene.dispose();
  13657. }
  13658. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  13659. that.currentScene = newScene;
  13660. that.currentScene.executeWhenReady(function () {
  13661. if (that.currentScene.activeCamera) {
  13662. that.currentScene.activeCamera.attachControl(that.canvas);
  13663. }
  13664. if (that.sceneLoadedCallback) {
  13665. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13666. }
  13667. that.engine.runRenderLoop(function () {
  13668. that.renderFunction();
  13669. });
  13670. });
  13671. }, function (progress) {
  13672. if (_this.progressCallback) {
  13673. _this.progressCallback(progress);
  13674. }
  13675. });
  13676. } else {
  13677. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13678. }
  13679. }
  13680. };
  13681. FilesInput.FilesTextures = new Array();
  13682. FilesInput.FilesToLoad = new Array();
  13683. return FilesInput;
  13684. })();
  13685. BABYLON.FilesInput = FilesInput;
  13686. })(BABYLON || (BABYLON = {}));
  13687. var BABYLON;
  13688. (function (BABYLON) {
  13689. var OimoJSPlugin = (function () {
  13690. function OimoJSPlugin() {
  13691. this._registeredMeshes = [];
  13692. /**
  13693. * Update the body position according to the mesh position
  13694. * @param mesh
  13695. */
  13696. this.updateBodyPosition = function (mesh) {
  13697. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13698. var registeredMesh = this._registeredMeshes[index];
  13699. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13700. var body = registeredMesh.body.body;
  13701. mesh.computeWorldMatrix(true);
  13702. var center = mesh.getBoundingInfo().boundingBox.center;
  13703. body.setPosition(center.x, center.y, center.z);
  13704. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13705. return;
  13706. }
  13707. if (registeredMesh.mesh.parent === mesh) {
  13708. mesh.computeWorldMatrix(true);
  13709. registeredMesh.mesh.computeWorldMatrix(true);
  13710. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13711. var absoluteRotation = mesh.rotation;
  13712. body = registeredMesh.body.body;
  13713. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13714. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13715. return;
  13716. }
  13717. }
  13718. };
  13719. }
  13720. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13721. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13722. };
  13723. OimoJSPlugin.prototype.initialize = function (iterations) {
  13724. this._world = new OIMO.World();
  13725. this._world.clear();
  13726. };
  13727. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13728. this._world.gravity = gravity;
  13729. };
  13730. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13731. var body = null;
  13732. this.unregisterMesh(mesh);
  13733. mesh.computeWorldMatrix(true);
  13734. switch (impostor) {
  13735. case BABYLON.PhysicsEngine.SphereImpostor:
  13736. var bbox = mesh.getBoundingInfo().boundingBox;
  13737. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13738. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13739. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13740. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13741. var deltaPosition = mesh.position.subtract(bbox.center);
  13742. body = new OIMO.Body({
  13743. type: 'sphere',
  13744. size: [size],
  13745. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13746. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13747. move: options.mass != 0,
  13748. config: [options.mass, options.friction, options.restitution],
  13749. world: this._world
  13750. });
  13751. this._registeredMeshes.push({
  13752. mesh: mesh,
  13753. body: body,
  13754. delta: deltaPosition
  13755. });
  13756. break;
  13757. case BABYLON.PhysicsEngine.PlaneImpostor:
  13758. case BABYLON.PhysicsEngine.BoxImpostor:
  13759. bbox = mesh.getBoundingInfo().boundingBox;
  13760. var min = bbox.minimumWorld;
  13761. var max = bbox.maximumWorld;
  13762. var box = max.subtract(min);
  13763. var sizeX = this._checkWithEpsilon(box.x);
  13764. var sizeY = this._checkWithEpsilon(box.y);
  13765. var sizeZ = this._checkWithEpsilon(box.z);
  13766. var deltaPosition = mesh.position.subtract(bbox.center);
  13767. body = new OIMO.Body({
  13768. type: 'box',
  13769. size: [sizeX, sizeY, sizeZ],
  13770. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13771. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13772. move: options.mass != 0,
  13773. config: [options.mass, options.friction, options.restitution],
  13774. world: this._world
  13775. });
  13776. this._registeredMeshes.push({
  13777. mesh: mesh,
  13778. body: body,
  13779. delta: deltaPosition
  13780. });
  13781. break;
  13782. }
  13783. return body;
  13784. };
  13785. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13786. var types = [], sizes = [], positions = [], rotations = [];
  13787. var initialMesh = parts[0].mesh;
  13788. for (var index = 0; index < parts.length; index++) {
  13789. var part = parts[index];
  13790. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13791. types.push(bodyParameters.type);
  13792. sizes.push.apply(sizes, bodyParameters.size);
  13793. positions.push.apply(positions, bodyParameters.pos);
  13794. rotations.push.apply(rotations, bodyParameters.rot);
  13795. }
  13796. var body = new OIMO.Body({
  13797. type: types,
  13798. size: sizes,
  13799. pos: positions,
  13800. rot: rotations,
  13801. move: options.mass != 0,
  13802. config: [options.mass, options.friction, options.restitution],
  13803. world: this._world
  13804. });
  13805. this._registeredMeshes.push({
  13806. mesh: initialMesh,
  13807. body: body
  13808. });
  13809. return body;
  13810. };
  13811. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13812. var bodyParameters = null;
  13813. var mesh = part.mesh;
  13814. switch (part.impostor) {
  13815. case BABYLON.PhysicsEngine.SphereImpostor:
  13816. var bbox = mesh.getBoundingInfo().boundingBox;
  13817. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13818. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13819. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13820. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13821. bodyParameters = {
  13822. type: 'sphere',
  13823. /* bug with oimo : sphere needs 3 sizes in this case */
  13824. size: [size, -1, -1],
  13825. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13826. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13827. };
  13828. break;
  13829. case BABYLON.PhysicsEngine.PlaneImpostor:
  13830. case BABYLON.PhysicsEngine.BoxImpostor:
  13831. bbox = mesh.getBoundingInfo().boundingBox;
  13832. var min = bbox.minimumWorld;
  13833. var max = bbox.maximumWorld;
  13834. var box = max.subtract(min);
  13835. var sizeX = this._checkWithEpsilon(box.x);
  13836. var sizeY = this._checkWithEpsilon(box.y);
  13837. var sizeZ = this._checkWithEpsilon(box.z);
  13838. var relativePosition = mesh.position;
  13839. bodyParameters = {
  13840. type: 'box',
  13841. size: [sizeX, sizeY, sizeZ],
  13842. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13843. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13844. };
  13845. break;
  13846. }
  13847. return bodyParameters;
  13848. };
  13849. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13850. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13851. var registeredMesh = this._registeredMeshes[index];
  13852. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13853. if (registeredMesh.body) {
  13854. this._world.removeRigidBody(registeredMesh.body.body);
  13855. this._unbindBody(registeredMesh.body);
  13856. }
  13857. this._registeredMeshes.splice(index, 1);
  13858. return;
  13859. }
  13860. }
  13861. };
  13862. OimoJSPlugin.prototype._unbindBody = function (body) {
  13863. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13864. var registeredMesh = this._registeredMeshes[index];
  13865. if (registeredMesh.body === body) {
  13866. registeredMesh.body = null;
  13867. }
  13868. }
  13869. };
  13870. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13871. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13872. var registeredMesh = this._registeredMeshes[index];
  13873. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13874. var mass = registeredMesh.body.body.massInfo.mass;
  13875. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13876. return;
  13877. }
  13878. }
  13879. };
  13880. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13881. var body1 = null, body2 = null;
  13882. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13883. var registeredMesh = this._registeredMeshes[index];
  13884. if (registeredMesh.mesh === mesh1) {
  13885. body1 = registeredMesh.body.body;
  13886. } else if (registeredMesh.mesh === mesh2) {
  13887. body2 = registeredMesh.body.body;
  13888. }
  13889. }
  13890. if (!body1 || !body2) {
  13891. return false;
  13892. }
  13893. if (!options) {
  13894. options = {};
  13895. }
  13896. new OIMO.Link({
  13897. type: options.type,
  13898. body1: body1,
  13899. body2: body2,
  13900. min: options.min,
  13901. max: options.max,
  13902. axe1: options.axe1,
  13903. axe2: options.axe2,
  13904. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13905. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13906. collision: options.collision,
  13907. spring: options.spring,
  13908. world: this._world
  13909. });
  13910. return true;
  13911. };
  13912. OimoJSPlugin.prototype.dispose = function () {
  13913. this._world.clear();
  13914. while (this._registeredMeshes.length) {
  13915. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13916. }
  13917. };
  13918. OimoJSPlugin.prototype.isSupported = function () {
  13919. return OIMO !== undefined;
  13920. };
  13921. OimoJSPlugin.prototype._getLastShape = function (body) {
  13922. var lastShape = body.shapes;
  13923. while (lastShape.next) {
  13924. lastShape = lastShape.next;
  13925. }
  13926. return lastShape;
  13927. };
  13928. OimoJSPlugin.prototype.runOneStep = function (time) {
  13929. this._world.step();
  13930. var i = this._registeredMeshes.length;
  13931. var m;
  13932. while (i--) {
  13933. var body = this._registeredMeshes[i].body.body;
  13934. var mesh = this._registeredMeshes[i].mesh;
  13935. var delta = this._registeredMeshes[i].delta;
  13936. if (!body.sleeping) {
  13937. if (body.shapes.next) {
  13938. var parentShape = this._getLastShape(body);
  13939. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13940. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13941. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13942. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13943. if (!mesh.rotationQuaternion) {
  13944. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13945. }
  13946. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13947. } else {
  13948. m = body.getMatrix();
  13949. mtx = BABYLON.Matrix.FromArray(m);
  13950. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13951. if (!delta) {
  13952. mesh.position.x = bodyX;
  13953. mesh.position.y = bodyY;
  13954. mesh.position.z = bodyZ;
  13955. } else {
  13956. mesh.position.x = bodyX + delta.x;
  13957. mesh.position.y = bodyY + delta.y;
  13958. mesh.position.z = bodyZ + delta.z;
  13959. }
  13960. if (!mesh.rotationQuaternion) {
  13961. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13962. }
  13963. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13964. }
  13965. }
  13966. }
  13967. };
  13968. return OimoJSPlugin;
  13969. })();
  13970. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13971. })(BABYLON || (BABYLON = {}));
  13972. var BABYLON;
  13973. (function (BABYLON) {
  13974. var PhysicsEngine = (function () {
  13975. function PhysicsEngine(plugin) {
  13976. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13977. }
  13978. PhysicsEngine.prototype._initialize = function (gravity) {
  13979. this._currentPlugin.initialize();
  13980. this._setGravity(gravity);
  13981. };
  13982. PhysicsEngine.prototype._runOneStep = function (delta) {
  13983. if (delta > 0.1) {
  13984. delta = 0.1;
  13985. } else if (delta <= 0) {
  13986. delta = 1.0 / 60.0;
  13987. }
  13988. this._currentPlugin.runOneStep(delta);
  13989. };
  13990. PhysicsEngine.prototype._setGravity = function (gravity) {
  13991. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13992. this._currentPlugin.setGravity(this.gravity);
  13993. };
  13994. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13995. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13996. };
  13997. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13998. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13999. };
  14000. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14001. this._currentPlugin.unregisterMesh(mesh);
  14002. };
  14003. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14004. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14005. };
  14006. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14007. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14008. };
  14009. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14010. this._currentPlugin.updateBodyPosition(mesh);
  14011. };
  14012. PhysicsEngine.prototype.dispose = function () {
  14013. this._currentPlugin.dispose();
  14014. };
  14015. PhysicsEngine.prototype.isSupported = function () {
  14016. return this._currentPlugin.isSupported();
  14017. };
  14018. PhysicsEngine.NoImpostor = 0;
  14019. PhysicsEngine.SphereImpostor = 1;
  14020. PhysicsEngine.BoxImpostor = 2;
  14021. PhysicsEngine.PlaneImpostor = 3;
  14022. PhysicsEngine.MeshImpostor = 4;
  14023. PhysicsEngine.CapsuleImpostor = 5;
  14024. PhysicsEngine.ConeImpostor = 6;
  14025. PhysicsEngine.CylinderImpostor = 7;
  14026. PhysicsEngine.ConvexHullImpostor = 8;
  14027. PhysicsEngine.Epsilon = 0.001;
  14028. return PhysicsEngine;
  14029. })();
  14030. BABYLON.PhysicsEngine = PhysicsEngine;
  14031. })(BABYLON || (BABYLON = {}));
  14032. var BABYLON;
  14033. (function (BABYLON) {
  14034. var serializeLight = function (light) {
  14035. var serializationObject = {};
  14036. serializationObject.name = light.name;
  14037. serializationObject.id = light.id;
  14038. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14039. if (light instanceof BABYLON.PointLight) {
  14040. serializationObject.type = 0;
  14041. serializationObject.position = light.position.asArray();
  14042. } else if (light instanceof BABYLON.DirectionalLight) {
  14043. serializationObject.type = 1;
  14044. var directionalLight = light;
  14045. serializationObject.position = directionalLight.position.asArray();
  14046. serializationObject.direction = directionalLight.direction.asArray();
  14047. } else if (light instanceof BABYLON.SpotLight) {
  14048. serializationObject.type = 2;
  14049. var spotLight = light;
  14050. serializationObject.position = spotLight.position.asArray();
  14051. serializationObject.direction = spotLight.position.asArray();
  14052. serializationObject.angle = spotLight.angle;
  14053. serializationObject.exponent = spotLight.exponent;
  14054. } else if (light instanceof BABYLON.HemisphericLight) {
  14055. serializationObject.type = 3;
  14056. var hemisphericLight = light;
  14057. serializationObject.direction = hemisphericLight.direction.asArray();
  14058. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14059. }
  14060. if (light.intensity) {
  14061. serializationObject.intensity = light.intensity;
  14062. }
  14063. serializationObject.range = light.range;
  14064. serializationObject.diffuse = light.diffuse.asArray();
  14065. serializationObject.specular = light.specular.asArray();
  14066. return serializationObject;
  14067. };
  14068. var serializeFresnelParameter = function (fresnelParameter) {
  14069. var serializationObject = {};
  14070. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14071. serializationObject.leftColor = fresnelParameter.leftColor;
  14072. serializationObject.rightColor = fresnelParameter.rightColor;
  14073. serializationObject.bias = fresnelParameter.bias;
  14074. serializationObject.power = fresnelParameter.power;
  14075. return serializationObject;
  14076. };
  14077. var serializeCamera = function (camera) {
  14078. var serializationObject = {};
  14079. serializationObject.name = camera.name;
  14080. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14081. serializationObject.id = camera.id;
  14082. serializationObject.position = camera.position.asArray();
  14083. if (camera.parent) {
  14084. serializationObject.parentId = camera.parent.id;
  14085. }
  14086. serializationObject.rotation = camera.rotation.asArray();
  14087. if (camera.lockedTarget && camera.lockedTarget.id) {
  14088. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14089. }
  14090. serializationObject.fov = camera.fov;
  14091. serializationObject.minZ = camera.minZ;
  14092. serializationObject.maxZ = camera.maxZ;
  14093. serializationObject.speed = camera.speed;
  14094. serializationObject.inertia = camera.inertia;
  14095. serializationObject.checkCollisions = camera.checkCollisions;
  14096. serializationObject.applyGravity = camera.applyGravity;
  14097. if (camera.ellipsoid) {
  14098. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14099. }
  14100. appendAnimations(camera, serializationObject);
  14101. serializationObject.layerMask = camera.layerMask;
  14102. return serializationObject;
  14103. };
  14104. var appendAnimations = function (source, destination) {
  14105. if (source.animations) {
  14106. destination.animations = [];
  14107. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14108. var animation = source.animations[animationIndex];
  14109. destination.animations.push(serializeAnimation(animation));
  14110. }
  14111. }
  14112. };
  14113. var serializeAnimation = function (animation) {
  14114. var serializationObject = {};
  14115. serializationObject.name = animation.name;
  14116. serializationObject.property = animation.targetProperty;
  14117. serializationObject.framePerSecond = animation.framePerSecond;
  14118. serializationObject.dataType = animation.dataType;
  14119. serializationObject.loopBehavior = animation.loopMode;
  14120. var dataType = animation.dataType;
  14121. serializationObject.keys = [];
  14122. var keys = animation.getKeys();
  14123. for (var index = 0; index < keys.length; index++) {
  14124. var animationKey = keys[index];
  14125. var key = {};
  14126. key.frame = animationKey.frame;
  14127. switch (dataType) {
  14128. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14129. key.values = [animationKey.value];
  14130. break;
  14131. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14132. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14133. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14134. key.values = animationKey.value.asArray();
  14135. break;
  14136. }
  14137. serializationObject.keys.push(key);
  14138. }
  14139. return serializationObject;
  14140. };
  14141. var serializeMultiMaterial = function (material) {
  14142. var serializationObject = {};
  14143. serializationObject.name = material.name;
  14144. serializationObject.id = material.id;
  14145. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14146. serializationObject.materials = [];
  14147. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14148. var subMat = material.subMaterials[matIndex];
  14149. if (subMat) {
  14150. serializationObject.materials.push(subMat.id);
  14151. } else {
  14152. serializationObject.materials.push(null);
  14153. }
  14154. }
  14155. return serializationObject;
  14156. };
  14157. var serializeMaterial = function (material) {
  14158. var serializationObject = {};
  14159. serializationObject.name = material.name;
  14160. serializationObject.ambient = material.ambientColor.asArray();
  14161. serializationObject.diffuse = material.diffuseColor.asArray();
  14162. serializationObject.specular = material.specularColor.asArray();
  14163. serializationObject.specularPower = material.specularPower;
  14164. serializationObject.emissive = material.emissiveColor.asArray();
  14165. serializationObject.alpha = material.alpha;
  14166. serializationObject.id = material.id;
  14167. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14168. serializationObject.backFaceCulling = material.backFaceCulling;
  14169. if (material.diffuseTexture) {
  14170. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14171. }
  14172. if (material.diffuseFresnelParameters) {
  14173. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14174. }
  14175. if (material.ambientTexture) {
  14176. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14177. }
  14178. if (material.opacityTexture) {
  14179. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14180. }
  14181. if (material.opacityFresnelParameters) {
  14182. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14183. }
  14184. if (material.reflectionTexture) {
  14185. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14186. }
  14187. if (material.reflectionFresnelParameters) {
  14188. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14189. }
  14190. if (material.emissiveTexture) {
  14191. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14192. }
  14193. if (material.emissiveFresnelParameters) {
  14194. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14195. }
  14196. if (material.specularTexture) {
  14197. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14198. }
  14199. if (material.bumpTexture) {
  14200. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14201. }
  14202. return serializationObject;
  14203. };
  14204. var serializeTexture = function (texture) {
  14205. var serializationObject = {};
  14206. if (!texture.name) {
  14207. return null;
  14208. }
  14209. if (texture instanceof BABYLON.CubeTexture) {
  14210. serializationObject.name = texture.name;
  14211. serializationObject.hasAlpha = texture.hasAlpha;
  14212. serializationObject.level = texture.level;
  14213. serializationObject.coordinatesMode = texture.coordinatesMode;
  14214. return serializationObject;
  14215. }
  14216. if (texture instanceof BABYLON.MirrorTexture) {
  14217. var mirrorTexture = texture;
  14218. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14219. serializationObject.renderList = [];
  14220. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14221. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14222. }
  14223. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14224. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14225. var renderTargetTexture = texture;
  14226. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14227. serializationObject.renderList = [];
  14228. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14229. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14230. }
  14231. }
  14232. var regularTexture = texture;
  14233. serializationObject.name = texture.name;
  14234. serializationObject.hasAlpha = texture.hasAlpha;
  14235. serializationObject.level = texture.level;
  14236. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14237. serializationObject.coordinatesMode = texture.coordinatesMode;
  14238. serializationObject.uOffset = regularTexture.uOffset;
  14239. serializationObject.vOffset = regularTexture.vOffset;
  14240. serializationObject.uScale = regularTexture.uScale;
  14241. serializationObject.vScale = regularTexture.vScale;
  14242. serializationObject.uAng = regularTexture.uAng;
  14243. serializationObject.vAng = regularTexture.vAng;
  14244. serializationObject.wAng = regularTexture.wAng;
  14245. serializationObject.wrapU = texture.wrapU;
  14246. serializationObject.wrapV = texture.wrapV;
  14247. appendAnimations(texture, serializationObject);
  14248. return serializationObject;
  14249. };
  14250. var serializeSkeleton = function (skeleton) {
  14251. var serializationObject = {};
  14252. serializationObject.name = skeleton.name;
  14253. serializationObject.id = skeleton.id;
  14254. serializationObject.bones = [];
  14255. for (var index = 0; index < skeleton.bones.length; index++) {
  14256. var bone = skeleton.bones[index];
  14257. var serializedBone = {
  14258. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14259. name: bone.name,
  14260. matrix: bone.getLocalMatrix().toArray()
  14261. };
  14262. serializationObject.bones.push(serializedBone);
  14263. if (bone.animations && bone.animations.length > 0) {
  14264. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14265. }
  14266. }
  14267. return serializationObject;
  14268. };
  14269. var serializeParticleSystem = function (particleSystem) {
  14270. var serializationObject = {};
  14271. serializationObject.emitterId = particleSystem.emitter.id;
  14272. serializationObject.capacity = particleSystem.getCapacity();
  14273. if (particleSystem.particleTexture) {
  14274. serializationObject.textureName = particleSystem.particleTexture.name;
  14275. }
  14276. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14277. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14278. serializationObject.minSize = particleSystem.minSize;
  14279. serializationObject.maxSize = particleSystem.maxSize;
  14280. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14281. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14282. serializationObject.emitRate = particleSystem.emitRate;
  14283. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14284. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14285. serializationObject.gravity = particleSystem.gravity.asArray();
  14286. serializationObject.direction1 = particleSystem.direction1.asArray();
  14287. serializationObject.direction2 = particleSystem.direction2.asArray();
  14288. serializationObject.color1 = particleSystem.color1.asArray();
  14289. serializationObject.color2 = particleSystem.color2.asArray();
  14290. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14291. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14292. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14293. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14294. serializationObject.blendMode = particleSystem.blendMode;
  14295. return serializationObject;
  14296. };
  14297. var serializeLensFlareSystem = function (lensFlareSystem) {
  14298. var serializationObject = {};
  14299. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14300. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14301. serializationObject.flares = [];
  14302. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14303. var flare = lensFlareSystem.lensFlares[index];
  14304. serializationObject.flares.push({
  14305. size: flare.size,
  14306. position: flare.position,
  14307. color: flare.color.asArray(),
  14308. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14309. });
  14310. }
  14311. return serializationObject;
  14312. };
  14313. var serializeShadowGenerator = function (light) {
  14314. var serializationObject = {};
  14315. var shadowGenerator = light.getShadowGenerator();
  14316. serializationObject.lightId = light.id;
  14317. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14318. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14319. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14320. serializationObject.renderList = [];
  14321. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14322. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14323. serializationObject.renderList.push(mesh.id);
  14324. }
  14325. return serializationObject;
  14326. };
  14327. var serializedGeometries = [];
  14328. var serializeGeometry = function (geometry, serializationGeometries) {
  14329. if (serializedGeometries[geometry.id]) {
  14330. return;
  14331. }
  14332. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14333. serializationGeometries.boxes.push(serializeBox(geometry));
  14334. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14335. serializationGeometries.spheres.push(serializeSphere(geometry));
  14336. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14337. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14338. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14339. serializationGeometries.toruses.push(serializeTorus(geometry));
  14340. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14341. serializationGeometries.grounds.push(serializeGround(geometry));
  14342. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14343. serializationGeometries.planes.push(serializePlane(geometry));
  14344. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14345. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14346. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14347. throw new Error("Unknow primitive type");
  14348. } else {
  14349. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14350. }
  14351. serializedGeometries[geometry.id] = true;
  14352. };
  14353. var serializeGeometryBase = function (geometry) {
  14354. var serializationObject = {};
  14355. serializationObject.id = geometry.id;
  14356. if (BABYLON.Tags.HasTags(geometry)) {
  14357. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14358. }
  14359. return serializationObject;
  14360. };
  14361. var serializeVertexData = function (vertexData) {
  14362. var serializationObject = serializeGeometryBase(vertexData);
  14363. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14364. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14365. }
  14366. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14367. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14368. }
  14369. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14370. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14371. }
  14372. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14373. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14374. }
  14375. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14376. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14377. }
  14378. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14379. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14380. serializationObject.matricesIndices._isExpanded = true;
  14381. }
  14382. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14383. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14384. }
  14385. serializationObject.indices = vertexData.getIndices();
  14386. return serializationObject;
  14387. };
  14388. var serializePrimitive = function (primitive) {
  14389. var serializationObject = serializeGeometryBase(primitive);
  14390. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14391. return serializationObject;
  14392. };
  14393. var serializeBox = function (box) {
  14394. var serializationObject = serializePrimitive(box);
  14395. serializationObject.size = box.size;
  14396. return serializationObject;
  14397. };
  14398. var serializeSphere = function (sphere) {
  14399. var serializationObject = serializePrimitive(sphere);
  14400. serializationObject.segments = sphere.segments;
  14401. serializationObject.diameter = sphere.diameter;
  14402. return serializationObject;
  14403. };
  14404. var serializeCylinder = function (cylinder) {
  14405. var serializationObject = serializePrimitive(cylinder);
  14406. serializationObject.height = cylinder.height;
  14407. serializationObject.diameterTop = cylinder.diameterTop;
  14408. serializationObject.diameterBottom = cylinder.diameterBottom;
  14409. serializationObject.tessellation = cylinder.tessellation;
  14410. return serializationObject;
  14411. };
  14412. var serializeTorus = function (torus) {
  14413. var serializationObject = serializePrimitive(torus);
  14414. serializationObject.diameter = torus.diameter;
  14415. serializationObject.thickness = torus.thickness;
  14416. serializationObject.tessellation = torus.tessellation;
  14417. return serializationObject;
  14418. };
  14419. var serializeGround = function (ground) {
  14420. var serializationObject = serializePrimitive(ground);
  14421. serializationObject.width = ground.width;
  14422. serializationObject.height = ground.height;
  14423. serializationObject.subdivisions = ground.subdivisions;
  14424. return serializationObject;
  14425. };
  14426. var serializePlane = function (plane) {
  14427. var serializationObject = serializePrimitive(plane);
  14428. serializationObject.size = plane.size;
  14429. return serializationObject;
  14430. };
  14431. var serializeTorusKnot = function (torusKnot) {
  14432. var serializationObject = serializePrimitive(torusKnot);
  14433. serializationObject.radius = torusKnot.radius;
  14434. serializationObject.tube = torusKnot.tube;
  14435. serializationObject.radialSegments = torusKnot.radialSegments;
  14436. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14437. serializationObject.p = torusKnot.p;
  14438. serializationObject.q = torusKnot.q;
  14439. return serializationObject;
  14440. };
  14441. var serializeMesh = function (mesh, serializationScene) {
  14442. var serializationObject = {};
  14443. serializationObject.name = mesh.name;
  14444. serializationObject.id = mesh.id;
  14445. if (BABYLON.Tags.HasTags(mesh)) {
  14446. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14447. }
  14448. serializationObject.position = mesh.position.asArray();
  14449. if (mesh.rotationQuaternion) {
  14450. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14451. } else if (mesh.rotation) {
  14452. serializationObject.rotation = mesh.rotation.asArray();
  14453. }
  14454. serializationObject.scaling = mesh.scaling.asArray();
  14455. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14456. serializationObject.isEnabled = mesh.isEnabled();
  14457. serializationObject.isVisible = mesh.isVisible;
  14458. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14459. serializationObject.pickable = mesh.isPickable;
  14460. serializationObject.receiveShadows = mesh.receiveShadows;
  14461. serializationObject.billboardMode = mesh.billboardMode;
  14462. serializationObject.visibility = mesh.visibility;
  14463. serializationObject.checkCollisions = mesh.checkCollisions;
  14464. if (mesh.parent) {
  14465. serializationObject.parentId = mesh.parent.id;
  14466. }
  14467. var geometry = mesh._geometry;
  14468. if (geometry) {
  14469. var geometryId = geometry.id;
  14470. serializationObject.geometryId = geometryId;
  14471. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14472. serializeGeometry(geometry, serializationScene.geometries);
  14473. }
  14474. serializationObject.subMeshes = [];
  14475. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14476. var subMesh = mesh.subMeshes[subIndex];
  14477. serializationObject.subMeshes.push({
  14478. materialIndex: subMesh.materialIndex,
  14479. verticesStart: subMesh.verticesStart,
  14480. verticesCount: subMesh.verticesCount,
  14481. indexStart: subMesh.indexStart,
  14482. indexCount: subMesh.indexCount
  14483. });
  14484. }
  14485. }
  14486. if (mesh.material) {
  14487. serializationObject.materialId = mesh.material.id;
  14488. } else {
  14489. mesh.material = null;
  14490. }
  14491. if (mesh.skeleton) {
  14492. serializationObject.skeletonId = mesh.skeleton.id;
  14493. }
  14494. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14495. serializationObject.physicsMass = mesh.getPhysicsMass();
  14496. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14497. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14498. switch (mesh.getPhysicsImpostor()) {
  14499. case BABYLON.PhysicsEngine.BoxImpostor:
  14500. serializationObject.physicsImpostor = 1;
  14501. break;
  14502. case BABYLON.PhysicsEngine.SphereImpostor:
  14503. serializationObject.physicsImpostor = 2;
  14504. break;
  14505. }
  14506. }
  14507. serializationObject.instances = [];
  14508. for (var index = 0; index < mesh.instances.length; index++) {
  14509. var instance = mesh.instances[index];
  14510. var serializationInstance = {
  14511. name: instance.name,
  14512. position: instance.position,
  14513. rotation: instance.rotation,
  14514. rotationQuaternion: instance.rotationQuaternion,
  14515. scaling: instance.scaling
  14516. };
  14517. serializationObject.instances.push(serializationInstance);
  14518. appendAnimations(instance, serializationInstance);
  14519. }
  14520. appendAnimations(mesh, serializationObject);
  14521. serializationObject.layerMask = mesh.layerMask;
  14522. return serializationObject;
  14523. };
  14524. var SceneSerializer = (function () {
  14525. function SceneSerializer() {
  14526. }
  14527. SceneSerializer.Serialize = function (scene) {
  14528. var serializationObject = {};
  14529. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14530. serializationObject.autoClear = scene.autoClear;
  14531. serializationObject.clearColor = scene.clearColor.asArray();
  14532. serializationObject.ambientColor = scene.ambientColor.asArray();
  14533. serializationObject.gravity = scene.gravity.asArray();
  14534. if (scene.fogMode && scene.fogMode !== 0) {
  14535. serializationObject.fogMode = scene.fogMode;
  14536. serializationObject.fogColor = scene.fogColor.asArray();
  14537. serializationObject.fogStart = scene.fogStart;
  14538. serializationObject.fogEnd = scene.fogEnd;
  14539. serializationObject.fogDensity = scene.fogDensity;
  14540. }
  14541. serializationObject.lights = [];
  14542. for (var index = 0; index < scene.lights.length; index++) {
  14543. var light = scene.lights[index];
  14544. serializationObject.lights.push(serializeLight(light));
  14545. }
  14546. serializationObject.cameras = [];
  14547. for (index = 0; index < scene.cameras.length; index++) {
  14548. var camera = scene.cameras[index];
  14549. if (camera instanceof BABYLON.FreeCamera) {
  14550. serializationObject.cameras.push(serializeCamera(camera));
  14551. }
  14552. }
  14553. if (scene.activeCamera) {
  14554. serializationObject.activeCameraID = scene.activeCamera.id;
  14555. }
  14556. serializationObject.materials = [];
  14557. serializationObject.multiMaterials = [];
  14558. for (index = 0; index < scene.materials.length; index++) {
  14559. var material = scene.materials[index];
  14560. if (material instanceof BABYLON.StandardMaterial) {
  14561. serializationObject.materials.push(serializeMaterial(material));
  14562. } else if (material instanceof BABYLON.MultiMaterial) {
  14563. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14564. }
  14565. }
  14566. serializationObject.skeletons = [];
  14567. for (index = 0; index < scene.skeletons.length; index++) {
  14568. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14569. }
  14570. serializationObject.geometries = {};
  14571. serializationObject.geometries.boxes = [];
  14572. serializationObject.geometries.spheres = [];
  14573. serializationObject.geometries.cylinders = [];
  14574. serializationObject.geometries.toruses = [];
  14575. serializationObject.geometries.grounds = [];
  14576. serializationObject.geometries.planes = [];
  14577. serializationObject.geometries.torusKnots = [];
  14578. serializationObject.geometries.vertexData = [];
  14579. serializedGeometries = [];
  14580. var geometries = scene.getGeometries();
  14581. for (var index = 0; index < geometries.length; index++) {
  14582. var geometry = geometries[index];
  14583. if (geometry.isReady()) {
  14584. serializeGeometry(geometry, serializationObject.geometries);
  14585. }
  14586. }
  14587. serializationObject.meshes = [];
  14588. for (index = 0; index < scene.meshes.length; index++) {
  14589. var abstractMesh = scene.meshes[index];
  14590. if (abstractMesh instanceof BABYLON.Mesh) {
  14591. var mesh = abstractMesh;
  14592. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14593. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14594. }
  14595. }
  14596. }
  14597. serializationObject.particleSystems = [];
  14598. for (index = 0; index < scene.particleSystems.length; index++) {
  14599. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14600. }
  14601. serializationObject.lensFlareSystems = [];
  14602. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14603. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14604. }
  14605. serializationObject.shadowGenerators = [];
  14606. for (index = 0; index < scene.lights.length; index++) {
  14607. light = scene.lights[index];
  14608. if (light.getShadowGenerator()) {
  14609. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14610. }
  14611. }
  14612. return serializationObject;
  14613. };
  14614. return SceneSerializer;
  14615. })();
  14616. BABYLON.SceneSerializer = SceneSerializer;
  14617. })(BABYLON || (BABYLON = {}));
  14618. var BABYLON;
  14619. (function (BABYLON) {
  14620. var SceneLoader = (function () {
  14621. function SceneLoader() {
  14622. }
  14623. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14624. get: function () {
  14625. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14626. },
  14627. set: function (value) {
  14628. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14629. },
  14630. enumerable: true,
  14631. configurable: true
  14632. });
  14633. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14634. get: function () {
  14635. return SceneLoader._ShowLoadingScreen;
  14636. },
  14637. set: function (value) {
  14638. SceneLoader._ShowLoadingScreen = value;
  14639. },
  14640. enumerable: true,
  14641. configurable: true
  14642. });
  14643. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14644. var dotPosition = sceneFilename.lastIndexOf(".");
  14645. var queryStringPosition = sceneFilename.indexOf("?");
  14646. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  14647. for (var index = 0; index < this._registeredPlugins.length; index++) {
  14648. var plugin = this._registeredPlugins[index];
  14649. if (plugin.extensions.indexOf(extension) !== -1) {
  14650. return plugin;
  14651. }
  14652. }
  14653. return this._registeredPlugins[this._registeredPlugins.length - 1];
  14654. };
  14655. SceneLoader.RegisterPlugin = function (plugin) {
  14656. plugin.extensions = plugin.extensions.toLowerCase();
  14657. SceneLoader._registeredPlugins.push(plugin);
  14658. };
  14659. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14660. var _this = this;
  14661. var manifestChecked = function (success) {
  14662. scene.database = database;
  14663. var plugin = _this._getPluginForFilename(sceneFilename);
  14664. var importMeshFromData = function (data) {
  14665. var meshes = [];
  14666. var particleSystems = [];
  14667. var skeletons = [];
  14668. try {
  14669. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14670. if (onerror) {
  14671. onerror(scene);
  14672. }
  14673. return;
  14674. }
  14675. } catch (e) {
  14676. if (onerror) {
  14677. onerror(scene);
  14678. }
  14679. return;
  14680. }
  14681. if (onsuccess) {
  14682. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14683. onsuccess(meshes, particleSystems, skeletons);
  14684. }
  14685. };
  14686. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14687. importMeshFromData(sceneFilename.substr(5));
  14688. return;
  14689. }
  14690. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14691. importMeshFromData(data);
  14692. }, progressCallBack, database);
  14693. };
  14694. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14695. };
  14696. /**
  14697. * Load a scene
  14698. * @param rootUrl a string that defines the root url for scene and resources
  14699. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14700. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14701. */
  14702. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14703. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14704. };
  14705. /**
  14706. * Append a scene
  14707. * @param rootUrl a string that defines the root url for scene and resources
  14708. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14709. * @param scene is the instance of BABYLON.Scene to append to
  14710. */
  14711. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14712. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14713. var database;
  14714. if (SceneLoader.ShowLoadingScreen) {
  14715. scene.getEngine().displayLoadingUI();
  14716. }
  14717. var loadSceneFromData = function (data) {
  14718. scene.database = database;
  14719. if (!plugin.load(scene, data, rootUrl)) {
  14720. if (onerror) {
  14721. onerror(scene);
  14722. }
  14723. scene.getEngine().hideLoadingUI();
  14724. return;
  14725. }
  14726. if (onsuccess) {
  14727. onsuccess(scene);
  14728. }
  14729. if (SceneLoader.ShowLoadingScreen) {
  14730. scene.executeWhenReady(function () {
  14731. scene.getEngine().hideLoadingUI();
  14732. });
  14733. }
  14734. };
  14735. var manifestChecked = function (success) {
  14736. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14737. };
  14738. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14739. loadSceneFromData(sceneFilename.substr(5));
  14740. return;
  14741. }
  14742. if (rootUrl.indexOf("file:") === -1) {
  14743. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14744. } else {
  14745. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14746. }
  14747. };
  14748. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14749. SceneLoader._ShowLoadingScreen = true;
  14750. SceneLoader._registeredPlugins = new Array();
  14751. return SceneLoader;
  14752. })();
  14753. BABYLON.SceneLoader = SceneLoader;
  14754. ;
  14755. })(BABYLON || (BABYLON = {}));
  14756. var BABYLON;
  14757. (function (BABYLON) {
  14758. (function (Internals) {
  14759. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14760. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14761. texture.name = parsedTexture.name;
  14762. texture.hasAlpha = parsedTexture.hasAlpha;
  14763. texture.level = parsedTexture.level;
  14764. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14765. return texture;
  14766. };
  14767. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14768. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14769. return null;
  14770. }
  14771. if (parsedTexture.isCube) {
  14772. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14773. }
  14774. var texture;
  14775. if (parsedTexture.mirrorPlane) {
  14776. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14777. texture._waitingRenderList = parsedTexture.renderList;
  14778. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14779. } else if (parsedTexture.isRenderTarget) {
  14780. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14781. texture._waitingRenderList = parsedTexture.renderList;
  14782. } else {
  14783. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14784. }
  14785. texture.name = parsedTexture.name;
  14786. texture.hasAlpha = parsedTexture.hasAlpha;
  14787. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14788. texture.level = parsedTexture.level;
  14789. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14790. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14791. texture.uOffset = parsedTexture.uOffset;
  14792. texture.vOffset = parsedTexture.vOffset;
  14793. texture.uScale = parsedTexture.uScale;
  14794. texture.vScale = parsedTexture.vScale;
  14795. texture.uAng = parsedTexture.uAng;
  14796. texture.vAng = parsedTexture.vAng;
  14797. texture.wAng = parsedTexture.wAng;
  14798. texture.wrapU = parsedTexture.wrapU;
  14799. texture.wrapV = parsedTexture.wrapV;
  14800. if (parsedTexture.animations) {
  14801. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14802. var parsedAnimation = parsedTexture.animations[animationIndex];
  14803. texture.animations.push(parseAnimation(parsedAnimation));
  14804. }
  14805. }
  14806. return texture;
  14807. };
  14808. var parseSkeleton = function (parsedSkeleton, scene) {
  14809. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14810. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14811. var parsedBone = parsedSkeleton.bones[index];
  14812. var parentBone = null;
  14813. if (parsedBone.parentBoneIndex > -1) {
  14814. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14815. }
  14816. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14817. if (parsedBone.animation) {
  14818. bone.animations.push(parseAnimation(parsedBone.animation));
  14819. }
  14820. }
  14821. return skeleton;
  14822. };
  14823. var parseFresnelParameters = function (parsedFresnelParameters) {
  14824. var fresnelParameters = new BABYLON.FresnelParameters();
  14825. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14826. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14827. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14828. fresnelParameters.bias = parsedFresnelParameters.bias;
  14829. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14830. return fresnelParameters;
  14831. };
  14832. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14833. var material;
  14834. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14835. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14836. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14837. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14838. material.specularPower = parsedMaterial.specularPower;
  14839. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14840. material.alpha = parsedMaterial.alpha;
  14841. material.id = parsedMaterial.id;
  14842. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14843. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14844. material.wireframe = parsedMaterial.wireframe;
  14845. if (parsedMaterial.diffuseTexture) {
  14846. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14847. }
  14848. if (parsedMaterial.diffuseFresnelParameters) {
  14849. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14850. }
  14851. if (parsedMaterial.ambientTexture) {
  14852. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14853. }
  14854. if (parsedMaterial.opacityTexture) {
  14855. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14856. }
  14857. if (parsedMaterial.opacityFresnelParameters) {
  14858. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14859. }
  14860. if (parsedMaterial.reflectionTexture) {
  14861. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14862. }
  14863. if (parsedMaterial.reflectionFresnelParameters) {
  14864. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14865. }
  14866. if (parsedMaterial.emissiveTexture) {
  14867. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14868. }
  14869. if (parsedMaterial.emissiveFresnelParameters) {
  14870. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14871. }
  14872. if (parsedMaterial.specularTexture) {
  14873. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14874. }
  14875. if (parsedMaterial.bumpTexture) {
  14876. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14877. }
  14878. return material;
  14879. };
  14880. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14881. for (var index = 0; index < parsedData.materials.length; index++) {
  14882. var parsedMaterial = parsedData.materials[index];
  14883. if (parsedMaterial.id === id) {
  14884. return parseMaterial(parsedMaterial, scene, rootUrl);
  14885. }
  14886. }
  14887. return null;
  14888. };
  14889. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14890. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14891. multiMaterial.id = parsedMultiMaterial.id;
  14892. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14893. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14894. var subMatId = parsedMultiMaterial.materials[matIndex];
  14895. if (subMatId) {
  14896. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14897. } else {
  14898. multiMaterial.subMaterials.push(null);
  14899. }
  14900. }
  14901. return multiMaterial;
  14902. };
  14903. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14904. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14905. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14906. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14907. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14908. var parsedFlare = parsedLensFlareSystem.flares[index];
  14909. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14910. }
  14911. return lensFlareSystem;
  14912. };
  14913. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14914. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14915. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14916. if (parsedParticleSystem.textureName) {
  14917. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14918. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14919. }
  14920. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14921. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14922. particleSystem.minSize = parsedParticleSystem.minSize;
  14923. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14924. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14925. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14926. particleSystem.emitter = emitter;
  14927. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14928. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14929. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14930. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14931. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14932. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14933. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14934. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14935. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14936. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14937. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14938. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14939. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14940. particleSystem.start();
  14941. return particleSystem;
  14942. };
  14943. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14944. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14945. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14946. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14947. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14948. shadowGenerator.getShadowMap().renderList.push(mesh);
  14949. }
  14950. if (parsedShadowGenerator.usePoissonSampling) {
  14951. shadowGenerator.usePoissonSampling = true;
  14952. } else {
  14953. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14954. }
  14955. return shadowGenerator;
  14956. };
  14957. var parseAnimation = function (parsedAnimation) {
  14958. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14959. var dataType = parsedAnimation.dataType;
  14960. var keys = [];
  14961. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14962. var key = parsedAnimation.keys[index];
  14963. var data;
  14964. switch (dataType) {
  14965. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14966. data = key.values[0];
  14967. break;
  14968. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14969. data = BABYLON.Quaternion.FromArray(key.values);
  14970. break;
  14971. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14972. data = BABYLON.Matrix.FromArray(key.values);
  14973. break;
  14974. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14975. default:
  14976. data = BABYLON.Vector3.FromArray(key.values);
  14977. break;
  14978. }
  14979. keys.push({
  14980. frame: key.frame,
  14981. value: data
  14982. });
  14983. }
  14984. animation.setKeys(keys);
  14985. return animation;
  14986. };
  14987. var parseLight = function (parsedLight, scene) {
  14988. var light;
  14989. switch (parsedLight.type) {
  14990. case 0:
  14991. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14992. break;
  14993. case 1:
  14994. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14995. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14996. break;
  14997. case 2:
  14998. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14999. break;
  15000. case 3:
  15001. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15002. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15003. break;
  15004. }
  15005. light.id = parsedLight.id;
  15006. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15007. if (parsedLight.intensity !== undefined) {
  15008. light.intensity = parsedLight.intensity;
  15009. }
  15010. if (parsedLight.range) {
  15011. light.range = parsedLight.range;
  15012. }
  15013. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15014. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15015. if (parsedLight.excludedMeshesIds) {
  15016. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15017. }
  15018. if (parsedLight.includedOnlyMeshesIds) {
  15019. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15020. }
  15021. if (parsedLight.animations) {
  15022. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15023. var parsedAnimation = parsedLight.animations[animationIndex];
  15024. light.animations.push(parseAnimation(parsedAnimation));
  15025. }
  15026. }
  15027. if (parsedLight.autoAnimate) {
  15028. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15029. }
  15030. };
  15031. var parseCamera = function (parsedCamera, scene) {
  15032. var camera;
  15033. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15034. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15035. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15036. var alpha = parsedCamera.alpha;
  15037. var beta = parsedCamera.beta;
  15038. var radius = parsedCamera.radius;
  15039. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15040. var eye_space = parsedCamera.eye_space;
  15041. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15042. } else {
  15043. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15044. }
  15045. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15046. var eye_space = parsedCamera.eye_space;
  15047. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15048. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15049. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15050. } else if (parsedCamera.type === "FollowCamera") {
  15051. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15052. camera.heightOffset = parsedCamera.heightOffset;
  15053. camera.radius = parsedCamera.radius;
  15054. camera.rotationOffset = parsedCamera.rotationOffset;
  15055. if (lockedTargetMesh)
  15056. camera.target = lockedTargetMesh;
  15057. } else if (parsedCamera.type === "GamepadCamera") {
  15058. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15059. } else if (parsedCamera.type === "OculusCamera") {
  15060. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15061. } else if (parsedCamera.type === "TouchCamera") {
  15062. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15063. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15064. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15065. } else if (parsedCamera.type === "WebVRCamera") {
  15066. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15067. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15068. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15069. } else {
  15070. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15071. }
  15072. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15073. camera.lockedTarget = lockedTargetMesh;
  15074. }
  15075. camera.id = parsedCamera.id;
  15076. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15077. if (parsedCamera.parentId) {
  15078. camera._waitingParentId = parsedCamera.parentId;
  15079. }
  15080. if (parsedCamera.target) {
  15081. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15082. } else {
  15083. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15084. }
  15085. camera.fov = parsedCamera.fov;
  15086. camera.minZ = parsedCamera.minZ;
  15087. camera.maxZ = parsedCamera.maxZ;
  15088. camera.speed = parsedCamera.speed;
  15089. camera.inertia = parsedCamera.inertia;
  15090. camera.checkCollisions = parsedCamera.checkCollisions;
  15091. camera.applyGravity = parsedCamera.applyGravity;
  15092. if (parsedCamera.ellipsoid) {
  15093. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15094. }
  15095. if (parsedCamera.animations) {
  15096. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15097. var parsedAnimation = parsedCamera.animations[animationIndex];
  15098. camera.animations.push(parseAnimation(parsedAnimation));
  15099. }
  15100. }
  15101. if (parsedCamera.autoAnimate) {
  15102. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15103. }
  15104. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15105. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15106. } else {
  15107. camera.layerMask = 0xFFFFFFFF;
  15108. }
  15109. return camera;
  15110. };
  15111. var parseGeometry = function (parsedGeometry, scene) {
  15112. var id = parsedGeometry.id;
  15113. return scene.getGeometryByID(id);
  15114. };
  15115. var parseBox = function (parsedBox, scene) {
  15116. if (parseGeometry(parsedBox, scene)) {
  15117. return null;
  15118. }
  15119. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15120. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15121. scene.pushGeometry(box, true);
  15122. return box;
  15123. };
  15124. var parseSphere = function (parsedSphere, scene) {
  15125. if (parseGeometry(parsedSphere, scene)) {
  15126. return null;
  15127. }
  15128. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15129. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15130. scene.pushGeometry(sphere, true);
  15131. return sphere;
  15132. };
  15133. var parseCylinder = function (parsedCylinder, scene) {
  15134. if (parseGeometry(parsedCylinder, scene)) {
  15135. return null;
  15136. }
  15137. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15138. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15139. scene.pushGeometry(cylinder, true);
  15140. return cylinder;
  15141. };
  15142. var parseTorus = function (parsedTorus, scene) {
  15143. if (parseGeometry(parsedTorus, scene)) {
  15144. return null;
  15145. }
  15146. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15147. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15148. scene.pushGeometry(torus, true);
  15149. return torus;
  15150. };
  15151. var parseGround = function (parsedGround, scene) {
  15152. if (parseGeometry(parsedGround, scene)) {
  15153. return null;
  15154. }
  15155. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15156. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15157. scene.pushGeometry(ground, true);
  15158. return ground;
  15159. };
  15160. var parsePlane = function (parsedPlane, scene) {
  15161. if (parseGeometry(parsedPlane, scene)) {
  15162. return null;
  15163. }
  15164. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15165. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15166. scene.pushGeometry(plane, true);
  15167. return plane;
  15168. };
  15169. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15170. if (parseGeometry(parsedTorusKnot, scene)) {
  15171. return null;
  15172. }
  15173. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  15174. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15175. scene.pushGeometry(torusKnot, true);
  15176. return torusKnot;
  15177. };
  15178. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15179. if (parseGeometry(parsedVertexData, scene)) {
  15180. return null;
  15181. }
  15182. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15183. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15184. if (parsedVertexData.delayLoadingFile) {
  15185. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15186. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15187. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15188. geometry._delayInfo = [];
  15189. if (parsedVertexData.hasUVs) {
  15190. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15191. }
  15192. if (parsedVertexData.hasUVs2) {
  15193. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15194. }
  15195. if (parsedVertexData.hasColors) {
  15196. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15197. }
  15198. if (parsedVertexData.hasMatricesIndices) {
  15199. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15200. }
  15201. if (parsedVertexData.hasMatricesWeights) {
  15202. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15203. }
  15204. geometry._delayLoadingFunction = importVertexData;
  15205. } else {
  15206. importVertexData(parsedVertexData, geometry);
  15207. }
  15208. scene.pushGeometry(geometry, true);
  15209. return geometry;
  15210. };
  15211. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15212. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15213. mesh.id = parsedMesh.id;
  15214. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15215. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15216. if (parsedMesh.rotationQuaternion) {
  15217. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15218. } else if (parsedMesh.rotation) {
  15219. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15220. }
  15221. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15222. if (parsedMesh.localMatrix) {
  15223. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15224. } else if (parsedMesh.pivotMatrix) {
  15225. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15226. }
  15227. mesh.setEnabled(parsedMesh.isEnabled);
  15228. mesh.isVisible = parsedMesh.isVisible;
  15229. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15230. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15231. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15232. if (parsedMesh.pickable !== undefined) {
  15233. mesh.isPickable = parsedMesh.pickable;
  15234. }
  15235. mesh.receiveShadows = parsedMesh.receiveShadows;
  15236. mesh.billboardMode = parsedMesh.billboardMode;
  15237. if (parsedMesh.visibility !== undefined) {
  15238. mesh.visibility = parsedMesh.visibility;
  15239. }
  15240. mesh.checkCollisions = parsedMesh.checkCollisions;
  15241. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15242. if (parsedMesh.parentId) {
  15243. mesh._waitingParentId = parsedMesh.parentId;
  15244. }
  15245. if (parsedMesh.delayLoadingFile) {
  15246. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15247. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15248. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15249. if (parsedMesh._binaryInfo) {
  15250. mesh._binaryInfo = parsedMesh._binaryInfo;
  15251. }
  15252. mesh._delayInfo = [];
  15253. if (parsedMesh.hasUVs) {
  15254. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15255. }
  15256. if (parsedMesh.hasUVs2) {
  15257. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15258. }
  15259. if (parsedMesh.hasColors) {
  15260. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15261. }
  15262. if (parsedMesh.hasMatricesIndices) {
  15263. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15264. }
  15265. if (parsedMesh.hasMatricesWeights) {
  15266. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15267. }
  15268. mesh._delayLoadingFunction = importGeometry;
  15269. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15270. mesh._checkDelayState();
  15271. }
  15272. } else {
  15273. importGeometry(parsedMesh, mesh);
  15274. }
  15275. if (parsedMesh.materialId) {
  15276. mesh.setMaterialByID(parsedMesh.materialId);
  15277. } else {
  15278. mesh.material = null;
  15279. }
  15280. if (parsedMesh.skeletonId > -1) {
  15281. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15282. }
  15283. if (parsedMesh.physicsImpostor) {
  15284. if (!scene.isPhysicsEnabled()) {
  15285. scene.enablePhysics();
  15286. }
  15287. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15288. }
  15289. if (parsedMesh.animations) {
  15290. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15291. var parsedAnimation = parsedMesh.animations[animationIndex];
  15292. mesh.animations.push(parseAnimation(parsedAnimation));
  15293. }
  15294. }
  15295. if (parsedMesh.autoAnimate) {
  15296. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15297. }
  15298. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15299. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15300. } else {
  15301. mesh.layerMask = 0xFFFFFFFF;
  15302. }
  15303. if (parsedMesh.instances) {
  15304. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15305. var parsedInstance = parsedMesh.instances[index];
  15306. var instance = mesh.createInstance(parsedInstance.name);
  15307. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15308. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15309. if (parsedInstance.rotationQuaternion) {
  15310. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15311. } else if (parsedInstance.rotation) {
  15312. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15313. }
  15314. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15315. instance.checkCollisions = mesh.checkCollisions;
  15316. if (parsedMesh.animations) {
  15317. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15318. parsedAnimation = parsedMesh.animations[animationIndex];
  15319. instance.animations.push(parseAnimation(parsedAnimation));
  15320. }
  15321. }
  15322. }
  15323. }
  15324. return mesh;
  15325. };
  15326. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15327. names = (names instanceof Array) ? names : [names];
  15328. for (var i in names) {
  15329. if (mesh.name === names[i]) {
  15330. hierarchyIds.push(mesh.id);
  15331. return true;
  15332. }
  15333. }
  15334. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15335. hierarchyIds.push(mesh.id);
  15336. return true;
  15337. }
  15338. return false;
  15339. };
  15340. var importVertexData = function (parsedVertexData, geometry) {
  15341. var vertexData = new BABYLON.VertexData();
  15342. var positions = parsedVertexData.positions;
  15343. if (positions) {
  15344. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15345. }
  15346. var normals = parsedVertexData.normals;
  15347. if (normals) {
  15348. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15349. }
  15350. var uvs = parsedVertexData.uvs;
  15351. if (uvs) {
  15352. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15353. }
  15354. var uv2s = parsedVertexData.uv2s;
  15355. if (uv2s) {
  15356. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15357. }
  15358. var colors = parsedVertexData.colors;
  15359. if (colors) {
  15360. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15361. }
  15362. var matricesIndices = parsedVertexData.matricesIndices;
  15363. if (matricesIndices) {
  15364. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15365. }
  15366. var matricesWeights = parsedVertexData.matricesWeights;
  15367. if (matricesWeights) {
  15368. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15369. }
  15370. var indices = parsedVertexData.indices;
  15371. if (indices) {
  15372. vertexData.indices = indices;
  15373. }
  15374. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15375. };
  15376. var importGeometry = function (parsedGeometry, mesh) {
  15377. var scene = mesh.getScene();
  15378. var geometryId = parsedGeometry.geometryId;
  15379. if (geometryId) {
  15380. var geometry = scene.getGeometryByID(geometryId);
  15381. if (geometry) {
  15382. geometry.applyToMesh(mesh);
  15383. }
  15384. } else if (parsedGeometry instanceof ArrayBuffer) {
  15385. var binaryInfo = mesh._binaryInfo;
  15386. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15387. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15388. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15389. }
  15390. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15391. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15392. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15393. }
  15394. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15395. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15396. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15397. }
  15398. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15399. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15400. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15401. }
  15402. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15403. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15404. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15405. }
  15406. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15407. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15408. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15409. }
  15410. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15411. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15413. }
  15414. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15415. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15416. mesh.setIndices(indicesData);
  15417. }
  15418. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15419. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15420. mesh.subMeshes = [];
  15421. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15422. var materialIndex = subMeshesData[(i * 5) + 0];
  15423. var verticesStart = subMeshesData[(i * 5) + 1];
  15424. var verticesCount = subMeshesData[(i * 5) + 2];
  15425. var indexStart = subMeshesData[(i * 5) + 3];
  15426. var indexCount = subMeshesData[(i * 5) + 4];
  15427. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15428. }
  15429. }
  15430. return;
  15431. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15432. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15433. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15434. if (parsedGeometry.uvs) {
  15435. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15436. }
  15437. if (parsedGeometry.uvs2) {
  15438. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15439. }
  15440. if (parsedGeometry.colors) {
  15441. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15442. }
  15443. if (parsedGeometry.matricesIndices) {
  15444. if (!parsedGeometry.matricesIndices._isExpanded) {
  15445. var floatIndices = [];
  15446. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15447. var matricesIndex = parsedGeometry.matricesIndices[i];
  15448. floatIndices.push(matricesIndex & 0x000000FF);
  15449. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15450. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15451. floatIndices.push(matricesIndex >> 24);
  15452. }
  15453. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15454. } else {
  15455. delete parsedGeometry.matricesIndices._isExpanded;
  15456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15457. }
  15458. }
  15459. if (parsedGeometry.matricesWeights) {
  15460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15461. }
  15462. mesh.setIndices(parsedGeometry.indices);
  15463. }
  15464. if (parsedGeometry.subMeshes) {
  15465. mesh.subMeshes = [];
  15466. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15467. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15468. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15469. }
  15470. }
  15471. if (mesh._shouldGenerateFlatShading) {
  15472. mesh.convertToFlatShadedMesh();
  15473. delete mesh._shouldGenerateFlatShading;
  15474. }
  15475. mesh.computeWorldMatrix(true);
  15476. if (scene._selectionOctree) {
  15477. scene._selectionOctree.addMesh(mesh);
  15478. }
  15479. };
  15480. BABYLON.SceneLoader.RegisterPlugin({
  15481. extensions: ".babylon",
  15482. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15483. var parsedData = JSON.parse(data);
  15484. var loadedSkeletonsIds = [];
  15485. var loadedMaterialsIds = [];
  15486. var hierarchyIds = [];
  15487. for (var index = 0; index < parsedData.meshes.length; index++) {
  15488. var parsedMesh = parsedData.meshes[index];
  15489. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15490. if (meshesNames instanceof Array) {
  15491. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15492. }
  15493. if (parsedMesh.materialId) {
  15494. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15495. if (!materialFound) {
  15496. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15497. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15498. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15499. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15500. var subMatId = parsedMultiMaterial.materials[matIndex];
  15501. loadedMaterialsIds.push(subMatId);
  15502. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15503. }
  15504. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15505. parseMultiMaterial(parsedMultiMaterial, scene);
  15506. materialFound = true;
  15507. break;
  15508. }
  15509. }
  15510. }
  15511. if (!materialFound) {
  15512. loadedMaterialsIds.push(parsedMesh.materialId);
  15513. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15514. }
  15515. }
  15516. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15517. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15518. if (!skeletonAlreadyLoaded) {
  15519. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15520. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15521. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15522. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15523. loadedSkeletonsIds.push(parsedSkeleton.id);
  15524. }
  15525. }
  15526. }
  15527. }
  15528. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15529. meshes.push(mesh);
  15530. }
  15531. }
  15532. for (index = 0; index < scene.meshes.length; index++) {
  15533. var currentMesh = scene.meshes[index];
  15534. if (currentMesh._waitingParentId) {
  15535. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15536. currentMesh._waitingParentId = undefined;
  15537. }
  15538. }
  15539. if (parsedData.particleSystems) {
  15540. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15541. var parsedParticleSystem = parsedData.particleSystems[index];
  15542. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15543. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15544. }
  15545. }
  15546. }
  15547. return true;
  15548. },
  15549. load: function (scene, data, rootUrl) {
  15550. var parsedData = JSON.parse(data);
  15551. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15552. scene.autoClear = parsedData.autoClear;
  15553. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15554. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15555. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15556. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15557. scene.fogMode = parsedData.fogMode;
  15558. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15559. scene.fogStart = parsedData.fogStart;
  15560. scene.fogEnd = parsedData.fogEnd;
  15561. scene.fogDensity = parsedData.fogDensity;
  15562. }
  15563. for (var index = 0; index < parsedData.lights.length; index++) {
  15564. var parsedLight = parsedData.lights[index];
  15565. parseLight(parsedLight, scene);
  15566. }
  15567. if (parsedData.materials) {
  15568. for (index = 0; index < parsedData.materials.length; index++) {
  15569. var parsedMaterial = parsedData.materials[index];
  15570. parseMaterial(parsedMaterial, scene, rootUrl);
  15571. }
  15572. }
  15573. if (parsedData.multiMaterials) {
  15574. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15575. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15576. parseMultiMaterial(parsedMultiMaterial, scene);
  15577. }
  15578. }
  15579. if (parsedData.skeletons) {
  15580. for (index = 0; index < parsedData.skeletons.length; index++) {
  15581. var parsedSkeleton = parsedData.skeletons[index];
  15582. parseSkeleton(parsedSkeleton, scene);
  15583. }
  15584. }
  15585. var geometries = parsedData.geometries;
  15586. if (geometries) {
  15587. var boxes = geometries.boxes;
  15588. if (boxes) {
  15589. for (index = 0; index < boxes.length; index++) {
  15590. var parsedBox = boxes[index];
  15591. parseBox(parsedBox, scene);
  15592. }
  15593. }
  15594. var spheres = geometries.spheres;
  15595. if (spheres) {
  15596. for (index = 0; index < spheres.length; index++) {
  15597. var parsedSphere = spheres[index];
  15598. parseSphere(parsedSphere, scene);
  15599. }
  15600. }
  15601. var cylinders = geometries.cylinders;
  15602. if (cylinders) {
  15603. for (index = 0; index < cylinders.length; index++) {
  15604. var parsedCylinder = cylinders[index];
  15605. parseCylinder(parsedCylinder, scene);
  15606. }
  15607. }
  15608. var toruses = geometries.toruses;
  15609. if (toruses) {
  15610. for (index = 0; index < toruses.length; index++) {
  15611. var parsedTorus = toruses[index];
  15612. parseTorus(parsedTorus, scene);
  15613. }
  15614. }
  15615. var grounds = geometries.grounds;
  15616. if (grounds) {
  15617. for (index = 0; index < grounds.length; index++) {
  15618. var parsedGround = grounds[index];
  15619. parseGround(parsedGround, scene);
  15620. }
  15621. }
  15622. var planes = geometries.planes;
  15623. if (planes) {
  15624. for (index = 0; index < planes.length; index++) {
  15625. var parsedPlane = planes[index];
  15626. parsePlane(parsedPlane, scene);
  15627. }
  15628. }
  15629. var torusKnots = geometries.torusKnots;
  15630. if (torusKnots) {
  15631. for (index = 0; index < torusKnots.length; index++) {
  15632. var parsedTorusKnot = torusKnots[index];
  15633. parseTorusKnot(parsedTorusKnot, scene);
  15634. }
  15635. }
  15636. var vertexData = geometries.vertexData;
  15637. if (vertexData) {
  15638. for (index = 0; index < vertexData.length; index++) {
  15639. var parsedVertexData = vertexData[index];
  15640. parseVertexData(parsedVertexData, scene, rootUrl);
  15641. }
  15642. }
  15643. }
  15644. for (index = 0; index < parsedData.meshes.length; index++) {
  15645. var parsedMesh = parsedData.meshes[index];
  15646. parseMesh(parsedMesh, scene, rootUrl);
  15647. }
  15648. for (index = 0; index < parsedData.cameras.length; index++) {
  15649. var parsedCamera = parsedData.cameras[index];
  15650. parseCamera(parsedCamera, scene);
  15651. }
  15652. if (parsedData.activeCameraID) {
  15653. scene.setActiveCameraByID(parsedData.activeCameraID);
  15654. }
  15655. for (index = 0; index < scene.cameras.length; index++) {
  15656. var camera = scene.cameras[index];
  15657. if (camera._waitingParentId) {
  15658. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  15659. camera._waitingParentId = undefined;
  15660. }
  15661. }
  15662. for (index = 0; index < scene.meshes.length; index++) {
  15663. var mesh = scene.meshes[index];
  15664. if (mesh._waitingParentId) {
  15665. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15666. mesh._waitingParentId = undefined;
  15667. }
  15668. }
  15669. if (parsedData.particleSystems) {
  15670. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15671. var parsedParticleSystem = parsedData.particleSystems[index];
  15672. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15673. }
  15674. }
  15675. if (parsedData.lensFlareSystems) {
  15676. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15677. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15678. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15679. }
  15680. }
  15681. if (parsedData.shadowGenerators) {
  15682. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15683. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15684. parseShadowGenerator(parsedShadowGenerator, scene);
  15685. }
  15686. }
  15687. return true;
  15688. }
  15689. });
  15690. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15691. var Internals = BABYLON.Internals;
  15692. })(BABYLON || (BABYLON = {}));
  15693. var BABYLON;
  15694. (function (BABYLON) {
  15695. var currentCSGMeshId = 0;
  15696. var Vertex = (function () {
  15697. function Vertex(pos, normal, uv) {
  15698. this.pos = pos;
  15699. this.normal = normal;
  15700. this.uv = uv;
  15701. }
  15702. Vertex.prototype.clone = function () {
  15703. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15704. };
  15705. Vertex.prototype.flip = function () {
  15706. this.normal = this.normal.scale(-1);
  15707. };
  15708. Vertex.prototype.interpolate = function (other, t) {
  15709. 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));
  15710. };
  15711. return Vertex;
  15712. })();
  15713. var Plane = (function () {
  15714. function Plane(normal, w) {
  15715. this.normal = normal;
  15716. this.w = w;
  15717. }
  15718. Plane.FromPoints = function (a, b, c) {
  15719. var v0 = c.subtract(a);
  15720. var v1 = b.subtract(a);
  15721. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15722. return null;
  15723. }
  15724. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15725. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15726. };
  15727. Plane.prototype.clone = function () {
  15728. return new Plane(this.normal.clone(), this.w);
  15729. };
  15730. Plane.prototype.flip = function () {
  15731. this.normal.scaleInPlace(-1);
  15732. this.w = -this.w;
  15733. };
  15734. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15735. var COPLANAR = 0;
  15736. var FRONT = 1;
  15737. var BACK = 2;
  15738. var SPANNING = 3;
  15739. var polygonType = 0;
  15740. var types = [];
  15741. for (var i = 0; i < polygon.vertices.length; i++) {
  15742. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15743. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15744. polygonType |= type;
  15745. types.push(type);
  15746. }
  15747. switch (polygonType) {
  15748. case COPLANAR:
  15749. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15750. break;
  15751. case FRONT:
  15752. front.push(polygon);
  15753. break;
  15754. case BACK:
  15755. back.push(polygon);
  15756. break;
  15757. case SPANNING:
  15758. var f = [], b = [];
  15759. for (i = 0; i < polygon.vertices.length; i++) {
  15760. var j = (i + 1) % polygon.vertices.length;
  15761. var ti = types[i], tj = types[j];
  15762. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15763. if (ti != BACK)
  15764. f.push(vi);
  15765. if (ti != FRONT)
  15766. b.push(ti != BACK ? vi.clone() : vi);
  15767. if ((ti | tj) == SPANNING) {
  15768. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15769. var v = vi.interpolate(vj, t);
  15770. f.push(v);
  15771. b.push(v.clone());
  15772. }
  15773. }
  15774. if (f.length >= 3) {
  15775. var poly = new Polygon(f, polygon.shared);
  15776. if (poly.plane)
  15777. front.push(poly);
  15778. }
  15779. if (b.length >= 3) {
  15780. poly = new Polygon(b, polygon.shared);
  15781. if (poly.plane)
  15782. back.push(poly);
  15783. }
  15784. break;
  15785. }
  15786. };
  15787. Plane.EPSILON = 1e-5;
  15788. return Plane;
  15789. })();
  15790. var Polygon = (function () {
  15791. function Polygon(vertices, shared) {
  15792. this.vertices = vertices;
  15793. this.shared = shared;
  15794. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15795. }
  15796. Polygon.prototype.clone = function () {
  15797. var vertices = this.vertices.map(function (v) {
  15798. return v.clone();
  15799. });
  15800. return new Polygon(vertices, this.shared);
  15801. };
  15802. Polygon.prototype.flip = function () {
  15803. this.vertices.reverse().map(function (v) {
  15804. v.flip();
  15805. });
  15806. this.plane.flip();
  15807. };
  15808. return Polygon;
  15809. })();
  15810. var Node = (function () {
  15811. function Node(polygons) {
  15812. this.plane = null;
  15813. this.front = null;
  15814. this.back = null;
  15815. this.polygons = [];
  15816. if (polygons) {
  15817. this.build(polygons);
  15818. }
  15819. }
  15820. Node.prototype.clone = function () {
  15821. var node = new Node();
  15822. node.plane = this.plane && this.plane.clone();
  15823. node.front = this.front && this.front.clone();
  15824. node.back = this.back && this.back.clone();
  15825. node.polygons = this.polygons.map(function (p) {
  15826. return p.clone();
  15827. });
  15828. return node;
  15829. };
  15830. Node.prototype.invert = function () {
  15831. for (var i = 0; i < this.polygons.length; i++) {
  15832. this.polygons[i].flip();
  15833. }
  15834. if (this.plane) {
  15835. this.plane.flip();
  15836. }
  15837. if (this.front) {
  15838. this.front.invert();
  15839. }
  15840. if (this.back) {
  15841. this.back.invert();
  15842. }
  15843. var temp = this.front;
  15844. this.front = this.back;
  15845. this.back = temp;
  15846. };
  15847. Node.prototype.clipPolygons = function (polygons) {
  15848. if (!this.plane)
  15849. return polygons.slice();
  15850. var front = [], back = [];
  15851. for (var i = 0; i < polygons.length; i++) {
  15852. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15853. }
  15854. if (this.front) {
  15855. front = this.front.clipPolygons(front);
  15856. }
  15857. if (this.back) {
  15858. back = this.back.clipPolygons(back);
  15859. } else {
  15860. back = [];
  15861. }
  15862. return front.concat(back);
  15863. };
  15864. Node.prototype.clipTo = function (bsp) {
  15865. this.polygons = bsp.clipPolygons(this.polygons);
  15866. if (this.front)
  15867. this.front.clipTo(bsp);
  15868. if (this.back)
  15869. this.back.clipTo(bsp);
  15870. };
  15871. Node.prototype.allPolygons = function () {
  15872. var polygons = this.polygons.slice();
  15873. if (this.front)
  15874. polygons = polygons.concat(this.front.allPolygons());
  15875. if (this.back)
  15876. polygons = polygons.concat(this.back.allPolygons());
  15877. return polygons;
  15878. };
  15879. Node.prototype.build = function (polygons) {
  15880. if (!polygons.length)
  15881. return;
  15882. if (!this.plane)
  15883. this.plane = polygons[0].plane.clone();
  15884. var front = [], back = [];
  15885. for (var i = 0; i < polygons.length; i++) {
  15886. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15887. }
  15888. if (front.length) {
  15889. if (!this.front)
  15890. this.front = new Node();
  15891. this.front.build(front);
  15892. }
  15893. if (back.length) {
  15894. if (!this.back)
  15895. this.back = new Node();
  15896. this.back.build(back);
  15897. }
  15898. };
  15899. return Node;
  15900. })();
  15901. var CSG = (function () {
  15902. function CSG() {
  15903. this.polygons = new Array();
  15904. }
  15905. CSG.FromMesh = function (mesh) {
  15906. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15907. if (mesh instanceof BABYLON.Mesh) {
  15908. mesh.computeWorldMatrix(true);
  15909. var matrix = mesh.getWorldMatrix();
  15910. var meshPosition = mesh.position.clone();
  15911. var meshRotation = mesh.rotation.clone();
  15912. var meshScaling = mesh.scaling.clone();
  15913. } else {
  15914. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15915. }
  15916. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15917. var subMeshes = mesh.subMeshes;
  15918. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15919. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15920. vertices = [];
  15921. for (var j = 0; j < 3; j++) {
  15922. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15923. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15924. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15925. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15926. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15927. vertex = new Vertex(position, normal, uv);
  15928. vertices.push(vertex);
  15929. }
  15930. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15931. if (polygon.plane)
  15932. polygons.push(polygon);
  15933. }
  15934. }
  15935. var csg = CSG.FromPolygons(polygons);
  15936. csg.matrix = matrix;
  15937. csg.position = meshPosition;
  15938. csg.rotation = meshRotation;
  15939. csg.scaling = meshScaling;
  15940. currentCSGMeshId++;
  15941. return csg;
  15942. };
  15943. CSG.FromPolygons = function (polygons) {
  15944. var csg = new BABYLON.CSG();
  15945. csg.polygons = polygons;
  15946. return csg;
  15947. };
  15948. CSG.prototype.clone = function () {
  15949. var csg = new BABYLON.CSG();
  15950. csg.polygons = this.polygons.map(function (p) {
  15951. return p.clone();
  15952. });
  15953. csg.copyTransformAttributes(this);
  15954. return csg;
  15955. };
  15956. CSG.prototype.toPolygons = function () {
  15957. return this.polygons;
  15958. };
  15959. CSG.prototype.union = function (csg) {
  15960. var a = new Node(this.clone().polygons);
  15961. var b = new Node(csg.clone().polygons);
  15962. a.clipTo(b);
  15963. b.clipTo(a);
  15964. b.invert();
  15965. b.clipTo(a);
  15966. b.invert();
  15967. a.build(b.allPolygons());
  15968. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15969. };
  15970. CSG.prototype.unionInPlace = function (csg) {
  15971. var a = new Node(this.polygons);
  15972. var b = new Node(csg.polygons);
  15973. a.clipTo(b);
  15974. b.clipTo(a);
  15975. b.invert();
  15976. b.clipTo(a);
  15977. b.invert();
  15978. a.build(b.allPolygons());
  15979. this.polygons = a.allPolygons();
  15980. };
  15981. CSG.prototype.subtract = function (csg) {
  15982. var a = new Node(this.clone().polygons);
  15983. var b = new Node(csg.clone().polygons);
  15984. a.invert();
  15985. a.clipTo(b);
  15986. b.clipTo(a);
  15987. b.invert();
  15988. b.clipTo(a);
  15989. b.invert();
  15990. a.build(b.allPolygons());
  15991. a.invert();
  15992. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15993. };
  15994. CSG.prototype.subtractInPlace = function (csg) {
  15995. var a = new Node(this.polygons);
  15996. var b = new Node(csg.polygons);
  15997. a.invert();
  15998. a.clipTo(b);
  15999. b.clipTo(a);
  16000. b.invert();
  16001. b.clipTo(a);
  16002. b.invert();
  16003. a.build(b.allPolygons());
  16004. a.invert();
  16005. this.polygons = a.allPolygons();
  16006. };
  16007. CSG.prototype.intersect = function (csg) {
  16008. var a = new Node(this.clone().polygons);
  16009. var b = new Node(csg.clone().polygons);
  16010. a.invert();
  16011. b.clipTo(a);
  16012. b.invert();
  16013. a.clipTo(b);
  16014. b.clipTo(a);
  16015. a.build(b.allPolygons());
  16016. a.invert();
  16017. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16018. };
  16019. CSG.prototype.intersectInPlace = function (csg) {
  16020. var a = new Node(this.polygons);
  16021. var b = new Node(csg.polygons);
  16022. a.invert();
  16023. b.clipTo(a);
  16024. b.invert();
  16025. a.clipTo(b);
  16026. b.clipTo(a);
  16027. a.build(b.allPolygons());
  16028. a.invert();
  16029. this.polygons = a.allPolygons();
  16030. };
  16031. CSG.prototype.inverse = function () {
  16032. var csg = this.clone();
  16033. csg.inverseInPlace();
  16034. return csg;
  16035. };
  16036. CSG.prototype.inverseInPlace = function () {
  16037. this.polygons.map(function (p) {
  16038. p.flip();
  16039. });
  16040. };
  16041. CSG.prototype.copyTransformAttributes = function (csg) {
  16042. this.matrix = csg.matrix;
  16043. this.position = csg.position;
  16044. this.rotation = csg.rotation;
  16045. this.scaling = csg.scaling;
  16046. return this;
  16047. };
  16048. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16049. var matrix = this.matrix.clone();
  16050. matrix.invert();
  16051. 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;
  16052. if (keepSubMeshes) {
  16053. polygons.sort(function (a, b) {
  16054. if (a.shared.meshId === b.shared.meshId) {
  16055. return a.shared.subMeshId - b.shared.subMeshId;
  16056. } else {
  16057. return a.shared.meshId - b.shared.meshId;
  16058. }
  16059. });
  16060. }
  16061. for (var i = 0, il = polygons.length; i < il; i++) {
  16062. polygon = polygons[i];
  16063. if (!subMesh_dict[polygon.shared.meshId]) {
  16064. subMesh_dict[polygon.shared.meshId] = {};
  16065. }
  16066. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16067. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16068. indexStart: +Infinity,
  16069. indexEnd: -Infinity,
  16070. materialIndex: polygon.shared.materialIndex
  16071. };
  16072. }
  16073. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16074. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16075. polygonIndices[0] = 0;
  16076. polygonIndices[1] = j - 1;
  16077. polygonIndices[2] = j;
  16078. for (var k = 0; k < 3; k++) {
  16079. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16080. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16081. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16082. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16083. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16084. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16085. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16086. vertices.push(vertex.x, vertex.y, vertex.z);
  16087. uvs.push(uv.x, uv.y);
  16088. normals.push(normal.x, normal.y, normal.z);
  16089. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16090. }
  16091. indices.push(vertex_idx);
  16092. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16093. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16094. currentIndex++;
  16095. }
  16096. }
  16097. }
  16098. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16099. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16100. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16101. mesh.setIndices(indices);
  16102. if (keepSubMeshes) {
  16103. var materialIndexOffset = 0, materialMaxIndex;
  16104. mesh.subMeshes.length = 0;
  16105. for (var m in subMesh_dict) {
  16106. materialMaxIndex = -1;
  16107. for (var sm in subMesh_dict[m]) {
  16108. subMesh_obj = subMesh_dict[m][sm];
  16109. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16110. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16111. }
  16112. materialIndexOffset += ++materialMaxIndex;
  16113. }
  16114. }
  16115. return mesh;
  16116. };
  16117. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16118. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16119. mesh.material = material;
  16120. mesh.position.copyFrom(this.position);
  16121. mesh.rotation.copyFrom(this.rotation);
  16122. mesh.scaling.copyFrom(this.scaling);
  16123. mesh.computeWorldMatrix(true);
  16124. return mesh;
  16125. };
  16126. return CSG;
  16127. })();
  16128. BABYLON.CSG = CSG;
  16129. })(BABYLON || (BABYLON = {}));
  16130. var __extends = this.__extends || function (d, b) {
  16131. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16132. function __() { this.constructor = d; }
  16133. __.prototype = b.prototype;
  16134. d.prototype = new __();
  16135. };
  16136. var BABYLON;
  16137. (function (BABYLON) {
  16138. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16139. __extends(OculusDistortionCorrectionPostProcess, _super);
  16140. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16141. var _this = this;
  16142. _super.call(this, name, "oculusDistortionCorrection", [
  16143. 'LensCenter',
  16144. 'Scale',
  16145. 'ScaleIn',
  16146. 'HmdWarpParam'
  16147. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16148. this._isRightEye = isRightEye;
  16149. this._distortionFactors = cameraSettings.DistortionK;
  16150. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16151. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16152. this.onSizeChanged = function () {
  16153. _this.aspectRatio = _this.width * .5 / _this.height;
  16154. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16155. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16156. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16157. };
  16158. this.onApply = function (effect) {
  16159. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16160. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16161. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16162. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16163. };
  16164. }
  16165. return OculusDistortionCorrectionPostProcess;
  16166. })(BABYLON.PostProcess);
  16167. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16168. })(BABYLON || (BABYLON = {}));
  16169. var BABYLON;
  16170. (function (BABYLON) {
  16171. (function (JoystickAxis) {
  16172. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16173. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16174. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16175. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16176. var JoystickAxis = BABYLON.JoystickAxis;
  16177. var VirtualJoystick = (function () {
  16178. function VirtualJoystick(leftJoystick) {
  16179. var _this = this;
  16180. if (leftJoystick) {
  16181. this._leftJoystick = true;
  16182. } else {
  16183. this._leftJoystick = false;
  16184. }
  16185. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16186. VirtualJoystick._globalJoystickIndex++;
  16187. this._axisTargetedByLeftAndRight = 0 /* X */;
  16188. this._axisTargetedByUpAndDown = 1 /* Y */;
  16189. this.reverseLeftRight = false;
  16190. this.reverseUpDown = false;
  16191. this._touches = new BABYLON.VirtualJoystick.Collection();
  16192. this.deltaPosition = BABYLON.Vector3.Zero();
  16193. this._joystickSensibility = 25;
  16194. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16195. this._rotationSpeed = 25;
  16196. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16197. this._rotateOnAxisRelativeToMesh = false;
  16198. if (!VirtualJoystick.vjCanvas) {
  16199. window.addEventListener("resize", function () {
  16200. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16201. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16202. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16203. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16204. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16205. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16206. }, false);
  16207. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16208. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16209. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16210. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16211. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16212. VirtualJoystick.vjCanvas.style.width = "100%";
  16213. VirtualJoystick.vjCanvas.style.height = "100%";
  16214. VirtualJoystick.vjCanvas.style.position = "absolute";
  16215. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16216. VirtualJoystick.vjCanvas.style.top = "0px";
  16217. VirtualJoystick.vjCanvas.style.left = "0px";
  16218. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16219. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16220. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16221. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16222. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16223. document.body.appendChild(VirtualJoystick.vjCanvas);
  16224. }
  16225. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16226. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16227. this.pressed = false;
  16228. this._joystickColor = "cyan";
  16229. this._joystickPointerID = -1;
  16230. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16231. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16232. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16233. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16234. _this._onPointerDown(evt);
  16235. }, false);
  16236. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16237. _this._onPointerMove(evt);
  16238. }, false);
  16239. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16240. _this._onPointerUp(evt);
  16241. }, false);
  16242. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16243. _this._onPointerUp(evt);
  16244. }, false);
  16245. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16246. evt.preventDefault();
  16247. }, false);
  16248. requestAnimationFrame(function () {
  16249. _this._drawVirtualJoystick();
  16250. });
  16251. }
  16252. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16253. this._joystickSensibility = newJoystickSensibility;
  16254. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16255. };
  16256. VirtualJoystick.prototype._onPointerDown = function (e) {
  16257. var positionOnScreenCondition;
  16258. e.preventDefault();
  16259. if (this._leftJoystick === true) {
  16260. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16261. } else {
  16262. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16263. }
  16264. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16265. this._joystickPointerID = e.pointerId;
  16266. this._joystickPointerStartPos.x = e.clientX;
  16267. this._joystickPointerStartPos.y = e.clientY;
  16268. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16269. this._deltaJoystickVector.x = 0;
  16270. this._deltaJoystickVector.y = 0;
  16271. this.pressed = true;
  16272. this._touches.add(e.pointerId.toString(), e);
  16273. } else {
  16274. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16275. this._action();
  16276. this._touches.add(e.pointerId.toString(), e);
  16277. }
  16278. }
  16279. };
  16280. VirtualJoystick.prototype._onPointerMove = function (e) {
  16281. if (this._joystickPointerID == e.pointerId) {
  16282. this._joystickPointerPos.x = e.clientX;
  16283. this._joystickPointerPos.y = e.clientY;
  16284. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16285. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16286. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16287. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16288. switch (this._axisTargetedByLeftAndRight) {
  16289. case 0 /* X */:
  16290. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16291. break;
  16292. case 1 /* Y */:
  16293. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16294. break;
  16295. case 2 /* Z */:
  16296. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16297. break;
  16298. }
  16299. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16300. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16301. switch (this._axisTargetedByUpAndDown) {
  16302. case 0 /* X */:
  16303. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16304. break;
  16305. case 1 /* Y */:
  16306. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16307. break;
  16308. case 2 /* Z */:
  16309. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16310. break;
  16311. }
  16312. } else {
  16313. if (this._touches.item(e.pointerId.toString())) {
  16314. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16315. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16316. }
  16317. }
  16318. };
  16319. VirtualJoystick.prototype._onPointerUp = function (e) {
  16320. this._clearCanvas();
  16321. if (this._joystickPointerID == e.pointerId) {
  16322. this._joystickPointerID = -1;
  16323. this.pressed = false;
  16324. }
  16325. this._deltaJoystickVector.x = 0;
  16326. this._deltaJoystickVector.y = 0;
  16327. this._touches.remove(e.pointerId.toString());
  16328. };
  16329. /**
  16330. * Change the color of the virtual joystick
  16331. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16332. */
  16333. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16334. this._joystickColor = newColor;
  16335. };
  16336. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16337. this._action = action;
  16338. };
  16339. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16340. switch (axis) {
  16341. case 0 /* X */:
  16342. case 1 /* Y */:
  16343. case 2 /* Z */:
  16344. this._axisTargetedByLeftAndRight = axis;
  16345. break;
  16346. default:
  16347. this._axisTargetedByLeftAndRight = 0 /* X */;
  16348. break;
  16349. }
  16350. };
  16351. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16352. switch (axis) {
  16353. case 0 /* X */:
  16354. case 1 /* Y */:
  16355. case 2 /* Z */:
  16356. this._axisTargetedByUpAndDown = axis;
  16357. break;
  16358. default:
  16359. this._axisTargetedByUpAndDown = 1 /* Y */;
  16360. break;
  16361. }
  16362. };
  16363. VirtualJoystick.prototype._clearCanvas = function () {
  16364. if (this._leftJoystick) {
  16365. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16366. } else {
  16367. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16368. }
  16369. };
  16370. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16371. var _this = this;
  16372. if (this.pressed) {
  16373. this._clearCanvas();
  16374. this._touches.forEach(function (touch) {
  16375. if (touch.pointerId === _this._joystickPointerID) {
  16376. VirtualJoystick.vjCanvasContext.beginPath();
  16377. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16378. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16379. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16380. VirtualJoystick.vjCanvasContext.stroke();
  16381. VirtualJoystick.vjCanvasContext.beginPath();
  16382. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16383. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16384. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16385. VirtualJoystick.vjCanvasContext.stroke();
  16386. VirtualJoystick.vjCanvasContext.beginPath();
  16387. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16388. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16389. VirtualJoystick.vjCanvasContext.stroke();
  16390. } else {
  16391. VirtualJoystick.vjCanvasContext.beginPath();
  16392. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16393. VirtualJoystick.vjCanvasContext.beginPath();
  16394. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16395. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16396. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16397. VirtualJoystick.vjCanvasContext.stroke();
  16398. }
  16399. ;
  16400. });
  16401. }
  16402. requestAnimationFrame(function () {
  16403. _this._drawVirtualJoystick();
  16404. });
  16405. };
  16406. VirtualJoystick.prototype.releaseCanvas = function () {
  16407. if (VirtualJoystick.vjCanvas) {
  16408. document.body.removeChild(VirtualJoystick.vjCanvas);
  16409. VirtualJoystick.vjCanvas = null;
  16410. }
  16411. };
  16412. VirtualJoystick._globalJoystickIndex = 0;
  16413. return VirtualJoystick;
  16414. })();
  16415. BABYLON.VirtualJoystick = VirtualJoystick;
  16416. })(BABYLON || (BABYLON = {}));
  16417. var BABYLON;
  16418. (function (BABYLON) {
  16419. (function (VirtualJoystick) {
  16420. var Collection = (function () {
  16421. function Collection() {
  16422. this._count = 0;
  16423. this._collection = new Array();
  16424. }
  16425. Collection.prototype.Count = function () {
  16426. return this._count;
  16427. };
  16428. Collection.prototype.add = function (key, item) {
  16429. if (this._collection[key] != undefined) {
  16430. return undefined;
  16431. }
  16432. this._collection[key] = item;
  16433. return ++this._count;
  16434. };
  16435. Collection.prototype.remove = function (key) {
  16436. if (this._collection[key] == undefined) {
  16437. return undefined;
  16438. }
  16439. delete this._collection[key];
  16440. return --this._count;
  16441. };
  16442. Collection.prototype.item = function (key) {
  16443. return this._collection[key];
  16444. };
  16445. Collection.prototype.forEach = function (block) {
  16446. var key;
  16447. for (key in this._collection) {
  16448. if (this._collection.hasOwnProperty(key)) {
  16449. block(this._collection[key]);
  16450. }
  16451. }
  16452. };
  16453. return Collection;
  16454. })();
  16455. VirtualJoystick.Collection = Collection;
  16456. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16457. var VirtualJoystick = BABYLON.VirtualJoystick;
  16458. })(BABYLON || (BABYLON = {}));
  16459. var __extends = this.__extends || function (d, b) {
  16460. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16461. function __() { this.constructor = d; }
  16462. __.prototype = b.prototype;
  16463. d.prototype = new __();
  16464. };
  16465. var BABYLON;
  16466. (function (BABYLON) {
  16467. var OculusRiftDevKit2013_Metric = {
  16468. HResolution: 1280,
  16469. VResolution: 800,
  16470. HScreenSize: 0.149759993,
  16471. VScreenSize: 0.0935999975,
  16472. VScreenCenter: 0.0467999987,
  16473. EyeToScreenDistance: 0.0410000011,
  16474. LensSeparationDistance: 0.0635000020,
  16475. InterpupillaryDistance: 0.0640000030,
  16476. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16477. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16478. PostProcessScaleFactor: 1.714605507808412,
  16479. LensCenterOffset: 0.151976421
  16480. };
  16481. var _OculusInnerCamera = (function (_super) {
  16482. __extends(_OculusInnerCamera, _super);
  16483. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16484. _super.call(this, name, position, scene);
  16485. this._workMatrix = new BABYLON.Matrix();
  16486. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16487. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16488. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16489. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16490. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16491. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16492. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16493. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16494. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16495. }
  16496. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16497. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16498. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16499. return this._projectionMatrix;
  16500. };
  16501. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16502. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16503. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16504. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16505. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16506. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16507. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16508. return this._viewMatrix;
  16509. };
  16510. return _OculusInnerCamera;
  16511. })(BABYLON.FreeCamera);
  16512. var OculusCamera = (function (_super) {
  16513. __extends(OculusCamera, _super);
  16514. function OculusCamera(name, position, scene) {
  16515. _super.call(this, name, position, scene);
  16516. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16517. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16518. this.subCameras.push(this._leftCamera);
  16519. this.subCameras.push(this._rightCamera);
  16520. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16521. }
  16522. OculusCamera.prototype._update = function () {
  16523. this._leftCamera.position.copyFrom(this.position);
  16524. this._rightCamera.position.copyFrom(this.position);
  16525. this._updateCamera(this._leftCamera);
  16526. this._updateCamera(this._rightCamera);
  16527. _super.prototype._update.call(this);
  16528. };
  16529. OculusCamera.prototype._updateCamera = function (camera) {
  16530. camera.minZ = this.minZ;
  16531. camera.maxZ = this.maxZ;
  16532. camera.rotation.x = this.rotation.x;
  16533. camera.rotation.y = this.rotation.y;
  16534. camera.rotation.z = this.rotation.z;
  16535. };
  16536. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16537. var yaw = evt.alpha / 180 * Math.PI;
  16538. var pitch = evt.beta / 180 * Math.PI;
  16539. var roll = evt.gamma / 180 * Math.PI;
  16540. if (!this._offsetOrientation) {
  16541. this._offsetOrientation = {
  16542. yaw: yaw,
  16543. pitch: pitch,
  16544. roll: roll
  16545. };
  16546. return;
  16547. } else {
  16548. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16549. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16550. this.rotation.z += this._offsetOrientation.roll - roll;
  16551. this._offsetOrientation.yaw = yaw;
  16552. this._offsetOrientation.pitch = pitch;
  16553. this._offsetOrientation.roll = roll;
  16554. }
  16555. };
  16556. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16557. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16558. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16559. };
  16560. OculusCamera.prototype.detachControl = function (element) {
  16561. _super.prototype.detachControl.call(this, element);
  16562. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16563. };
  16564. return OculusCamera;
  16565. })(BABYLON.FreeCamera);
  16566. BABYLON.OculusCamera = OculusCamera;
  16567. })(BABYLON || (BABYLON = {}));
  16568. var __extends = this.__extends || function (d, b) {
  16569. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16570. function __() { this.constructor = d; }
  16571. __.prototype = b.prototype;
  16572. d.prototype = new __();
  16573. };
  16574. var BABYLON;
  16575. (function (BABYLON) {
  16576. var OculusRiftDevKit2013_Metric = {
  16577. HResolution: 1280,
  16578. VResolution: 800,
  16579. HScreenSize: 0.149759993,
  16580. VScreenSize: 0.0935999975,
  16581. VScreenCenter: 0.0467999987,
  16582. EyeToScreenDistance: 0.0410000011,
  16583. LensSeparationDistance: 0.0635000020,
  16584. InterpupillaryDistance: 0.0640000030,
  16585. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16586. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16587. PostProcessScaleFactor: 1.714605507808412,
  16588. LensCenterOffset: 0.151976421
  16589. };
  16590. var _OculusInnerGamepadCamera = (function (_super) {
  16591. __extends(_OculusInnerGamepadCamera, _super);
  16592. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16593. _super.call(this, name, position, scene);
  16594. this._workMatrix = new BABYLON.Matrix();
  16595. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16596. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16597. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16598. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16599. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16600. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16601. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16602. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16603. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16604. }
  16605. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16606. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16607. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16608. return this._projectionMatrix;
  16609. };
  16610. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16611. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16612. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16613. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16614. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16615. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16616. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16617. return this._viewMatrix;
  16618. };
  16619. return _OculusInnerGamepadCamera;
  16620. })(BABYLON.FreeCamera);
  16621. var OculusGamepadCamera = (function (_super) {
  16622. __extends(OculusGamepadCamera, _super);
  16623. function OculusGamepadCamera(name, position, scene) {
  16624. var _this = this;
  16625. _super.call(this, name, position, scene);
  16626. this.angularSensibility = 200;
  16627. this.moveSensibility = 75;
  16628. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16629. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16630. this.subCameras.push(this._leftCamera);
  16631. this.subCameras.push(this._rightCamera);
  16632. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16633. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16634. _this._onNewGameConnected(gamepad);
  16635. });
  16636. }
  16637. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16638. if (gamepad.index === 0) {
  16639. this._gamepad = gamepad;
  16640. }
  16641. };
  16642. OculusGamepadCamera.prototype._update = function () {
  16643. this._leftCamera.position.copyFrom(this.position);
  16644. this._rightCamera.position.copyFrom(this.position);
  16645. this._updateCamera(this._leftCamera);
  16646. this._updateCamera(this._rightCamera);
  16647. _super.prototype._update.call(this);
  16648. };
  16649. OculusGamepadCamera.prototype._checkInputs = function () {
  16650. if (!this._gamepad) {
  16651. return;
  16652. }
  16653. var LSValues = this._gamepad.leftStick;
  16654. var normalizedLX = LSValues.x / this.moveSensibility;
  16655. var normalizedLY = LSValues.y / this.moveSensibility;
  16656. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16657. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16658. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16659. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  16660. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16661. };
  16662. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16663. camera.minZ = this.minZ;
  16664. camera.maxZ = this.maxZ;
  16665. camera.rotation.x = this.rotation.x;
  16666. camera.rotation.y = this.rotation.y;
  16667. camera.rotation.z = this.rotation.z;
  16668. };
  16669. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16670. var yaw = evt.alpha / 180 * Math.PI;
  16671. var pitch = evt.beta / 180 * Math.PI;
  16672. var roll = evt.gamma / 180 * Math.PI;
  16673. if (!this._offsetOrientation) {
  16674. this._offsetOrientation = {
  16675. yaw: yaw,
  16676. pitch: pitch,
  16677. roll: roll
  16678. };
  16679. return;
  16680. } else {
  16681. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16682. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16683. this.rotation.z += this._offsetOrientation.roll - roll;
  16684. this._offsetOrientation.yaw = yaw;
  16685. this._offsetOrientation.pitch = pitch;
  16686. this._offsetOrientation.roll = roll;
  16687. }
  16688. };
  16689. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16690. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16691. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16692. };
  16693. OculusGamepadCamera.prototype.detachControl = function (element) {
  16694. _super.prototype.detachControl.call(this, element);
  16695. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16696. };
  16697. OculusGamepadCamera.prototype.dispose = function () {
  16698. this._gamepads.dispose();
  16699. _super.prototype.dispose.call(this);
  16700. };
  16701. return OculusGamepadCamera;
  16702. })(BABYLON.FreeCamera);
  16703. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16704. })(BABYLON || (BABYLON = {}));
  16705. var __extends = this.__extends || function (d, b) {
  16706. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16707. function __() { this.constructor = d; }
  16708. __.prototype = b.prototype;
  16709. d.prototype = new __();
  16710. };
  16711. var BABYLON;
  16712. (function (BABYLON) {
  16713. var VirtualJoysticksCamera = (function (_super) {
  16714. __extends(VirtualJoysticksCamera, _super);
  16715. function VirtualJoysticksCamera(name, position, scene) {
  16716. _super.call(this, name, position, scene);
  16717. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16718. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16719. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16720. this._leftjoystick.setJoystickSensibility(0.15);
  16721. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16722. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16723. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16724. this._rightjoystick.reverseUpDown = true;
  16725. this._rightjoystick.setJoystickSensibility(0.05);
  16726. this._rightjoystick.setJoystickColor("yellow");
  16727. }
  16728. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16729. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16730. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16731. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16732. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16733. if (!this._leftjoystick.pressed) {
  16734. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16735. }
  16736. if (!this._rightjoystick.pressed) {
  16737. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16738. }
  16739. };
  16740. VirtualJoysticksCamera.prototype.dispose = function () {
  16741. this._leftjoystick.releaseCanvas();
  16742. _super.prototype.dispose.call(this);
  16743. };
  16744. return VirtualJoysticksCamera;
  16745. })(BABYLON.FreeCamera);
  16746. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16747. })(BABYLON || (BABYLON = {}));
  16748. var __extends = this.__extends || function (d, b) {
  16749. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16750. function __() { this.constructor = d; }
  16751. __.prototype = b.prototype;
  16752. d.prototype = new __();
  16753. };
  16754. var BABYLON;
  16755. (function (BABYLON) {
  16756. var ShaderMaterial = (function (_super) {
  16757. __extends(ShaderMaterial, _super);
  16758. function ShaderMaterial(name, scene, shaderPath, options) {
  16759. _super.call(this, name, scene);
  16760. this._textures = new Array();
  16761. this._floats = new Array();
  16762. this._floatsArrays = {};
  16763. this._colors3 = new Array();
  16764. this._colors4 = new Array();
  16765. this._vectors2 = new Array();
  16766. this._vectors3 = new Array();
  16767. this._matrices = new Array();
  16768. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16769. this._shaderPath = shaderPath;
  16770. options.needAlphaBlending = options.needAlphaBlending || false;
  16771. options.needAlphaTesting = options.needAlphaTesting || false;
  16772. options.attributes = options.attributes || ["position", "normal", "uv"];
  16773. options.uniforms = options.uniforms || ["worldViewProjection"];
  16774. options.samplers = options.samplers || [];
  16775. this._options = options;
  16776. }
  16777. ShaderMaterial.prototype.needAlphaBlending = function () {
  16778. return this._options.needAlphaBlending;
  16779. };
  16780. ShaderMaterial.prototype.needAlphaTesting = function () {
  16781. return this._options.needAlphaTesting;
  16782. };
  16783. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16784. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16785. this._options.uniforms.push(uniformName);
  16786. }
  16787. };
  16788. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16789. if (this._options.samplers.indexOf(name) === -1) {
  16790. this._options.samplers.push(name);
  16791. }
  16792. this._textures[name] = texture;
  16793. return this;
  16794. };
  16795. ShaderMaterial.prototype.setFloat = function (name, value) {
  16796. this._checkUniform(name);
  16797. this._floats[name] = value;
  16798. return this;
  16799. };
  16800. ShaderMaterial.prototype.setFloats = function (name, value) {
  16801. this._checkUniform(name);
  16802. this._floatsArrays[name] = value;
  16803. return this;
  16804. };
  16805. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16806. this._checkUniform(name);
  16807. this._colors3[name] = value;
  16808. return this;
  16809. };
  16810. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16811. this._checkUniform(name);
  16812. this._colors4[name] = value;
  16813. return this;
  16814. };
  16815. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16816. this._checkUniform(name);
  16817. this._vectors2[name] = value;
  16818. return this;
  16819. };
  16820. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16821. this._checkUniform(name);
  16822. this._vectors3[name] = value;
  16823. return this;
  16824. };
  16825. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16826. this._checkUniform(name);
  16827. this._matrices[name] = value;
  16828. return this;
  16829. };
  16830. ShaderMaterial.prototype.isReady = function () {
  16831. var engine = this.getScene().getEngine();
  16832. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16833. if (!this._effect.isReady()) {
  16834. return false;
  16835. }
  16836. return true;
  16837. };
  16838. ShaderMaterial.prototype.bind = function (world) {
  16839. if (this._options.uniforms.indexOf("world") !== -1) {
  16840. this._effect.setMatrix("world", world);
  16841. }
  16842. if (this._options.uniforms.indexOf("view") !== -1) {
  16843. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16844. }
  16845. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16846. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16847. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16848. }
  16849. if (this._options.uniforms.indexOf("projection") !== -1) {
  16850. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16851. }
  16852. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16853. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16854. }
  16855. for (var name in this._textures) {
  16856. this._effect.setTexture(name, this._textures[name]);
  16857. }
  16858. for (name in this._floats) {
  16859. this._effect.setFloat(name, this._floats[name]);
  16860. }
  16861. for (name in this._floatsArrays) {
  16862. this._effect.setArray(name, this._floatsArrays[name]);
  16863. }
  16864. for (name in this._colors3) {
  16865. this._effect.setColor3(name, this._colors3[name]);
  16866. }
  16867. for (name in this._colors4) {
  16868. var color = this._colors4[name];
  16869. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16870. }
  16871. for (name in this._vectors2) {
  16872. this._effect.setVector2(name, this._vectors2[name]);
  16873. }
  16874. for (name in this._vectors3) {
  16875. this._effect.setVector3(name, this._vectors3[name]);
  16876. }
  16877. for (name in this._matrices) {
  16878. this._effect.setMatrix(name, this._matrices[name]);
  16879. }
  16880. };
  16881. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16882. for (var name in this._textures) {
  16883. this._textures[name].dispose();
  16884. }
  16885. this._textures = [];
  16886. _super.prototype.dispose.call(this, forceDisposeEffect);
  16887. };
  16888. return ShaderMaterial;
  16889. })(BABYLON.Material);
  16890. BABYLON.ShaderMaterial = ShaderMaterial;
  16891. })(BABYLON || (BABYLON = {}));
  16892. var BABYLON;
  16893. (function (BABYLON) {
  16894. var VertexData = (function () {
  16895. function VertexData() {
  16896. }
  16897. VertexData.prototype.set = function (data, kind) {
  16898. switch (kind) {
  16899. case BABYLON.VertexBuffer.PositionKind:
  16900. this.positions = data;
  16901. break;
  16902. case BABYLON.VertexBuffer.NormalKind:
  16903. this.normals = data;
  16904. break;
  16905. case BABYLON.VertexBuffer.UVKind:
  16906. this.uvs = data;
  16907. break;
  16908. case BABYLON.VertexBuffer.UV2Kind:
  16909. this.uv2s = data;
  16910. break;
  16911. case BABYLON.VertexBuffer.ColorKind:
  16912. this.colors = data;
  16913. break;
  16914. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16915. this.matricesIndices = data;
  16916. break;
  16917. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16918. this.matricesWeights = data;
  16919. break;
  16920. }
  16921. };
  16922. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16923. this._applyTo(mesh, updatable);
  16924. };
  16925. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16926. this._applyTo(geometry, updatable);
  16927. };
  16928. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16929. this._update(mesh);
  16930. };
  16931. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16932. this._update(geometry);
  16933. };
  16934. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16935. if (this.positions) {
  16936. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16937. }
  16938. if (this.normals) {
  16939. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16940. }
  16941. if (this.uvs) {
  16942. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16943. }
  16944. if (this.uv2s) {
  16945. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16946. }
  16947. if (this.colors) {
  16948. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16949. }
  16950. if (this.matricesIndices) {
  16951. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16952. }
  16953. if (this.matricesWeights) {
  16954. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16955. }
  16956. if (this.indices) {
  16957. meshOrGeometry.setIndices(this.indices);
  16958. }
  16959. };
  16960. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16961. if (this.positions) {
  16962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16963. }
  16964. if (this.normals) {
  16965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16966. }
  16967. if (this.uvs) {
  16968. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16969. }
  16970. if (this.uv2s) {
  16971. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16972. }
  16973. if (this.colors) {
  16974. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16975. }
  16976. if (this.matricesIndices) {
  16977. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16978. }
  16979. if (this.matricesWeights) {
  16980. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16981. }
  16982. if (this.indices) {
  16983. meshOrGeometry.setIndices(this.indices);
  16984. }
  16985. };
  16986. VertexData.prototype.transform = function (matrix) {
  16987. var transformed = BABYLON.Vector3.Zero();
  16988. if (this.positions) {
  16989. var position = BABYLON.Vector3.Zero();
  16990. for (var index = 0; index < this.positions.length; index += 3) {
  16991. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16992. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16993. this.positions[index] = transformed.x;
  16994. this.positions[index + 1] = transformed.y;
  16995. this.positions[index + 2] = transformed.z;
  16996. }
  16997. }
  16998. if (this.normals) {
  16999. var normal = BABYLON.Vector3.Zero();
  17000. for (index = 0; index < this.normals.length; index += 3) {
  17001. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17002. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17003. this.normals[index] = transformed.x;
  17004. this.normals[index + 1] = transformed.y;
  17005. this.normals[index + 2] = transformed.z;
  17006. }
  17007. }
  17008. };
  17009. VertexData.prototype.merge = function (other) {
  17010. if (other.indices) {
  17011. if (!this.indices) {
  17012. this.indices = [];
  17013. }
  17014. var offset = this.positions ? this.positions.length / 3 : 0;
  17015. for (var index = 0; index < other.indices.length; index++) {
  17016. this.indices.push(other.indices[index] + offset);
  17017. }
  17018. }
  17019. if (other.positions) {
  17020. if (!this.positions) {
  17021. this.positions = [];
  17022. }
  17023. for (index = 0; index < other.positions.length; index++) {
  17024. this.positions.push(other.positions[index]);
  17025. }
  17026. }
  17027. if (other.normals) {
  17028. if (!this.normals) {
  17029. this.normals = [];
  17030. }
  17031. for (index = 0; index < other.normals.length; index++) {
  17032. this.normals.push(other.normals[index]);
  17033. }
  17034. }
  17035. if (other.uvs) {
  17036. if (!this.uvs) {
  17037. this.uvs = [];
  17038. }
  17039. for (index = 0; index < other.uvs.length; index++) {
  17040. this.uvs.push(other.uvs[index]);
  17041. }
  17042. }
  17043. if (other.uv2s) {
  17044. if (!this.uv2s) {
  17045. this.uv2s = [];
  17046. }
  17047. for (index = 0; index < other.uv2s.length; index++) {
  17048. this.uv2s.push(other.uv2s[index]);
  17049. }
  17050. }
  17051. if (other.matricesIndices) {
  17052. if (!this.matricesIndices) {
  17053. this.matricesIndices = [];
  17054. }
  17055. for (index = 0; index < other.matricesIndices.length; index++) {
  17056. this.matricesIndices.push(other.matricesIndices[index]);
  17057. }
  17058. }
  17059. if (other.matricesWeights) {
  17060. if (!this.matricesWeights) {
  17061. this.matricesWeights = [];
  17062. }
  17063. for (index = 0; index < other.matricesWeights.length; index++) {
  17064. this.matricesWeights.push(other.matricesWeights[index]);
  17065. }
  17066. }
  17067. if (other.colors) {
  17068. if (!this.colors) {
  17069. this.colors = [];
  17070. }
  17071. for (index = 0; index < other.colors.length; index++) {
  17072. this.colors.push(other.colors[index]);
  17073. }
  17074. }
  17075. };
  17076. VertexData.ExtractFromMesh = function (mesh) {
  17077. return VertexData._ExtractFrom(mesh);
  17078. };
  17079. VertexData.ExtractFromGeometry = function (geometry) {
  17080. return VertexData._ExtractFrom(geometry);
  17081. };
  17082. VertexData._ExtractFrom = function (meshOrGeometry) {
  17083. var result = new BABYLON.VertexData();
  17084. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17085. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17086. }
  17087. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17088. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17089. }
  17090. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17091. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17092. }
  17093. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17094. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17095. }
  17096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17097. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17098. }
  17099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17100. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17101. }
  17102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17103. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17104. }
  17105. result.indices = meshOrGeometry.getIndices();
  17106. return result;
  17107. };
  17108. VertexData.CreateBox = function (size) {
  17109. var normalsSource = [
  17110. new BABYLON.Vector3(0, 0, 1),
  17111. new BABYLON.Vector3(0, 0, -1),
  17112. new BABYLON.Vector3(1, 0, 0),
  17113. new BABYLON.Vector3(-1, 0, 0),
  17114. new BABYLON.Vector3(0, 1, 0),
  17115. new BABYLON.Vector3(0, -1, 0)
  17116. ];
  17117. var indices = [];
  17118. var positions = [];
  17119. var normals = [];
  17120. var uvs = [];
  17121. size = size || 1;
  17122. for (var index = 0; index < normalsSource.length; index++) {
  17123. var normal = normalsSource[index];
  17124. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17125. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17126. var verticesLength = positions.length / 3;
  17127. indices.push(verticesLength);
  17128. indices.push(verticesLength + 1);
  17129. indices.push(verticesLength + 2);
  17130. indices.push(verticesLength);
  17131. indices.push(verticesLength + 2);
  17132. indices.push(verticesLength + 3);
  17133. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17134. positions.push(vertex.x, vertex.y, vertex.z);
  17135. normals.push(normal.x, normal.y, normal.z);
  17136. uvs.push(1.0, 1.0);
  17137. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17138. positions.push(vertex.x, vertex.y, vertex.z);
  17139. normals.push(normal.x, normal.y, normal.z);
  17140. uvs.push(0.0, 1.0);
  17141. vertex = normal.add(side1).add(side2).scale(size / 2);
  17142. positions.push(vertex.x, vertex.y, vertex.z);
  17143. normals.push(normal.x, normal.y, normal.z);
  17144. uvs.push(0.0, 0.0);
  17145. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17146. positions.push(vertex.x, vertex.y, vertex.z);
  17147. normals.push(normal.x, normal.y, normal.z);
  17148. uvs.push(1.0, 0.0);
  17149. }
  17150. var vertexData = new BABYLON.VertexData();
  17151. vertexData.indices = indices;
  17152. vertexData.positions = positions;
  17153. vertexData.normals = normals;
  17154. vertexData.uvs = uvs;
  17155. return vertexData;
  17156. };
  17157. VertexData.CreateSphere = function (segments, diameter) {
  17158. segments = segments || 32;
  17159. diameter = diameter || 1;
  17160. var radius = diameter / 2;
  17161. var totalZRotationSteps = 2 + segments;
  17162. var totalYRotationSteps = 2 * totalZRotationSteps;
  17163. var indices = [];
  17164. var positions = [];
  17165. var normals = [];
  17166. var uvs = [];
  17167. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17168. var normalizedZ = zRotationStep / totalZRotationSteps;
  17169. var angleZ = (normalizedZ * Math.PI);
  17170. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17171. var normalizedY = yRotationStep / totalYRotationSteps;
  17172. var angleY = normalizedY * Math.PI * 2;
  17173. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17174. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17175. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17176. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17177. var vertex = complete.scale(radius);
  17178. var normal = BABYLON.Vector3.Normalize(vertex);
  17179. positions.push(vertex.x, vertex.y, vertex.z);
  17180. normals.push(normal.x, normal.y, normal.z);
  17181. uvs.push(normalizedZ, normalizedY);
  17182. }
  17183. if (zRotationStep > 0) {
  17184. var verticesCount = positions.length / 3;
  17185. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17186. indices.push((firstIndex));
  17187. indices.push((firstIndex + 1));
  17188. indices.push(firstIndex + totalYRotationSteps + 1);
  17189. indices.push((firstIndex + totalYRotationSteps + 1));
  17190. indices.push((firstIndex + 1));
  17191. indices.push((firstIndex + totalYRotationSteps + 2));
  17192. }
  17193. }
  17194. }
  17195. var vertexData = new BABYLON.VertexData();
  17196. vertexData.indices = indices;
  17197. vertexData.positions = positions;
  17198. vertexData.normals = normals;
  17199. vertexData.uvs = uvs;
  17200. return vertexData;
  17201. };
  17202. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17203. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17204. var radiusTop = diameterTop / 2;
  17205. var radiusBottom = diameterBottom / 2;
  17206. var indices = [];
  17207. var positions = [];
  17208. var normals = [];
  17209. var uvs = [];
  17210. height = height || 1;
  17211. diameterTop = diameterTop || 0.5;
  17212. diameterBottom = diameterBottom || 1;
  17213. tessellation = tessellation || 16;
  17214. subdivisions = subdivisions || 1;
  17215. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17216. var getCircleVector = function (i) {
  17217. var angle = (i * 2.0 * Math.PI / tessellation);
  17218. var dx = Math.cos(angle);
  17219. var dz = Math.sin(angle);
  17220. return new BABYLON.Vector3(dx, 0, dz);
  17221. };
  17222. var createCylinderCap = function (isTop) {
  17223. var radius = isTop ? radiusTop : radiusBottom;
  17224. if (radius == 0) {
  17225. return;
  17226. }
  17227. var vbase = positions.length / 3;
  17228. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17229. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17230. if (!isTop) {
  17231. offset.scaleInPlace(-1);
  17232. textureScale.x = -textureScale.x;
  17233. }
  17234. for (i = 0; i < tessellation; i++) {
  17235. var circleVector = getCircleVector(i);
  17236. var position = circleVector.scale(radius).add(offset);
  17237. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17238. positions.push(position.x, position.y, position.z);
  17239. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17240. }
  17241. for (var i = 0; i < tessellation - 2; i++) {
  17242. if (!isTop) {
  17243. indices.push(vbase);
  17244. indices.push(vbase + (i + 2) % tessellation);
  17245. indices.push(vbase + (i + 1) % tessellation);
  17246. } else {
  17247. indices.push(vbase);
  17248. indices.push(vbase + (i + 1) % tessellation);
  17249. indices.push(vbase + (i + 2) % tessellation);
  17250. }
  17251. }
  17252. };
  17253. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17254. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17255. var stride = tessellation + 1;
  17256. for (var i = 0; i <= tessellation; i++) {
  17257. var circleVector = getCircleVector(i);
  17258. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17259. var position, radius = radiusBottom;
  17260. for (var s = 0; s <= subdivisions; s++) {
  17261. position = circleVector.scale(radius);
  17262. position.addInPlace(base.add(offset.scale(s)));
  17263. textureCoordinate.y += 1 / subdivisions;
  17264. radius += (radiusTop - radiusBottom) / subdivisions;
  17265. positions.push(position.x, position.y, position.z);
  17266. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17267. }
  17268. }
  17269. subdivisions += 1;
  17270. for (var s = 0; s < subdivisions - 1; s++) {
  17271. for (var i = 0; i <= tessellation; i++) {
  17272. indices.push(i * subdivisions + s);
  17273. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17274. indices.push(i * subdivisions + (s + 1));
  17275. indices.push(i * subdivisions + (s + 1));
  17276. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17277. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17278. }
  17279. }
  17280. createCylinderCap(true);
  17281. createCylinderCap(false);
  17282. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17283. var vertexData = new BABYLON.VertexData();
  17284. vertexData.indices = indices;
  17285. vertexData.positions = positions;
  17286. vertexData.normals = normals;
  17287. vertexData.uvs = uvs;
  17288. return vertexData;
  17289. };
  17290. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17291. var indices = [];
  17292. var positions = [];
  17293. var normals = [];
  17294. var uvs = [];
  17295. diameter = diameter || 1;
  17296. thickness = thickness || 0.5;
  17297. tessellation = tessellation || 16;
  17298. var stride = tessellation + 1;
  17299. for (var i = 0; i <= tessellation; i++) {
  17300. var u = i / tessellation;
  17301. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17302. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17303. for (var j = 0; j <= tessellation; j++) {
  17304. var v = 1 - j / tessellation;
  17305. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17306. var dx = Math.cos(innerAngle);
  17307. var dy = Math.sin(innerAngle);
  17308. var normal = new BABYLON.Vector3(dx, dy, 0);
  17309. var position = normal.scale(thickness / 2);
  17310. var textureCoordinate = new BABYLON.Vector2(u, v);
  17311. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17312. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17313. positions.push(position.x, position.y, position.z);
  17314. normals.push(normal.x, normal.y, normal.z);
  17315. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17316. var nextI = (i + 1) % stride;
  17317. var nextJ = (j + 1) % stride;
  17318. indices.push(i * stride + j);
  17319. indices.push(i * stride + nextJ);
  17320. indices.push(nextI * stride + j);
  17321. indices.push(i * stride + nextJ);
  17322. indices.push(nextI * stride + nextJ);
  17323. indices.push(nextI * stride + j);
  17324. }
  17325. }
  17326. var vertexData = new BABYLON.VertexData();
  17327. vertexData.indices = indices;
  17328. vertexData.positions = positions;
  17329. vertexData.normals = normals;
  17330. vertexData.uvs = uvs;
  17331. return vertexData;
  17332. };
  17333. VertexData.CreateLines = function (points) {
  17334. var indices = [];
  17335. var positions = [];
  17336. for (var index = 0; index < points.length; index++) {
  17337. positions.push(points[index].x, points[index].y, points[index].z);
  17338. if (index > 0) {
  17339. indices.push(index - 1);
  17340. indices.push(index);
  17341. }
  17342. }
  17343. var vertexData = new BABYLON.VertexData();
  17344. vertexData.indices = indices;
  17345. vertexData.positions = positions;
  17346. return vertexData;
  17347. };
  17348. VertexData.CreateGround = function (width, height, subdivisions) {
  17349. var indices = [];
  17350. var positions = [];
  17351. var normals = [];
  17352. var uvs = [];
  17353. var row, col;
  17354. width = width || 1;
  17355. height = height || 1;
  17356. subdivisions = subdivisions || 1;
  17357. for (row = 0; row <= subdivisions; row++) {
  17358. for (col = 0; col <= subdivisions; col++) {
  17359. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17360. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17361. positions.push(position.x, position.y, position.z);
  17362. normals.push(normal.x, normal.y, normal.z);
  17363. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17364. }
  17365. }
  17366. for (row = 0; row < subdivisions; row++) {
  17367. for (col = 0; col < subdivisions; col++) {
  17368. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17369. indices.push(col + 1 + row * (subdivisions + 1));
  17370. indices.push(col + row * (subdivisions + 1));
  17371. indices.push(col + (row + 1) * (subdivisions + 1));
  17372. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17373. indices.push(col + row * (subdivisions + 1));
  17374. }
  17375. }
  17376. var vertexData = new BABYLON.VertexData();
  17377. vertexData.indices = indices;
  17378. vertexData.positions = positions;
  17379. vertexData.normals = normals;
  17380. vertexData.uvs = uvs;
  17381. return vertexData;
  17382. };
  17383. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17384. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17385. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17386. var indices = [];
  17387. var positions = [];
  17388. var normals = [];
  17389. var uvs = [];
  17390. var row, col, tileRow, tileCol;
  17391. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17392. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17393. precision.w = (precision.w < 1) ? 1 : precision.w;
  17394. precision.h = (precision.h < 1) ? 1 : precision.h;
  17395. var tileSize = {
  17396. 'w': (xmax - xmin) / subdivisions.w,
  17397. 'h': (zmax - zmin) / subdivisions.h
  17398. };
  17399. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17400. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17401. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17402. }
  17403. }
  17404. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17405. var base = positions.length / 3;
  17406. var rowLength = precision.w + 1;
  17407. for (row = 0; row < precision.h; row++) {
  17408. for (col = 0; col < precision.w; col++) {
  17409. var square = [
  17410. base + col + row * rowLength,
  17411. base + (col + 1) + row * rowLength,
  17412. base + (col + 1) + (row + 1) * rowLength,
  17413. base + col + (row + 1) * rowLength
  17414. ];
  17415. indices.push(square[1]);
  17416. indices.push(square[2]);
  17417. indices.push(square[3]);
  17418. indices.push(square[0]);
  17419. indices.push(square[1]);
  17420. indices.push(square[3]);
  17421. }
  17422. }
  17423. var position = BABYLON.Vector3.Zero();
  17424. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17425. for (row = 0; row <= precision.h; row++) {
  17426. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17427. for (col = 0; col <= precision.w; col++) {
  17428. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17429. position.y = 0;
  17430. positions.push(position.x, position.y, position.z);
  17431. normals.push(normal.x, normal.y, normal.z);
  17432. uvs.push(col / precision.w, row / precision.h);
  17433. }
  17434. }
  17435. }
  17436. var vertexData = new BABYLON.VertexData();
  17437. vertexData.indices = indices;
  17438. vertexData.positions = positions;
  17439. vertexData.normals = normals;
  17440. vertexData.uvs = uvs;
  17441. return vertexData;
  17442. };
  17443. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17444. var indices = [];
  17445. var positions = [];
  17446. var normals = [];
  17447. var uvs = [];
  17448. var row, col;
  17449. for (row = 0; row <= subdivisions; row++) {
  17450. for (col = 0; col <= subdivisions; col++) {
  17451. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17452. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17453. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17454. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17455. var r = buffer[pos] / 255.0;
  17456. var g = buffer[pos + 1] / 255.0;
  17457. var b = buffer[pos + 2] / 255.0;
  17458. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17459. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17460. positions.push(position.x, position.y, position.z);
  17461. normals.push(0, 0, 0);
  17462. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17463. }
  17464. }
  17465. for (row = 0; row < subdivisions; row++) {
  17466. for (col = 0; col < subdivisions; col++) {
  17467. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17468. indices.push(col + 1 + row * (subdivisions + 1));
  17469. indices.push(col + row * (subdivisions + 1));
  17470. indices.push(col + (row + 1) * (subdivisions + 1));
  17471. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17472. indices.push(col + row * (subdivisions + 1));
  17473. }
  17474. }
  17475. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17476. var vertexData = new BABYLON.VertexData();
  17477. vertexData.indices = indices;
  17478. vertexData.positions = positions;
  17479. vertexData.normals = normals;
  17480. vertexData.uvs = uvs;
  17481. return vertexData;
  17482. };
  17483. VertexData.CreatePlane = function (size) {
  17484. var indices = [];
  17485. var positions = [];
  17486. var normals = [];
  17487. var uvs = [];
  17488. size = size || 1;
  17489. var halfSize = size / 2.0;
  17490. positions.push(-halfSize, -halfSize, 0);
  17491. normals.push(0, 0, -1.0);
  17492. uvs.push(0.0, 0.0);
  17493. positions.push(halfSize, -halfSize, 0);
  17494. normals.push(0, 0, -1.0);
  17495. uvs.push(1.0, 0.0);
  17496. positions.push(halfSize, halfSize, 0);
  17497. normals.push(0, 0, -1.0);
  17498. uvs.push(1.0, 1.0);
  17499. positions.push(-halfSize, halfSize, 0);
  17500. normals.push(0, 0, -1.0);
  17501. uvs.push(0.0, 1.0);
  17502. indices.push(0);
  17503. indices.push(1);
  17504. indices.push(2);
  17505. indices.push(0);
  17506. indices.push(2);
  17507. indices.push(3);
  17508. var vertexData = new BABYLON.VertexData();
  17509. vertexData.indices = indices;
  17510. vertexData.positions = positions;
  17511. vertexData.normals = normals;
  17512. vertexData.uvs = uvs;
  17513. return vertexData;
  17514. };
  17515. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17516. var indices = [];
  17517. var positions = [];
  17518. var normals = [];
  17519. var uvs = [];
  17520. radius = radius || 2;
  17521. tube = tube || 0.5;
  17522. radialSegments = radialSegments || 32;
  17523. tubularSegments = tubularSegments || 32;
  17524. p = p || 2;
  17525. q = q || 3;
  17526. var getPos = function (angle) {
  17527. var cu = Math.cos(angle);
  17528. var su = Math.sin(angle);
  17529. var quOverP = q / p * angle;
  17530. var cs = Math.cos(quOverP);
  17531. var tx = radius * (2 + cs) * 0.5 * cu;
  17532. var ty = radius * (2 + cs) * su * 0.5;
  17533. var tz = radius * Math.sin(quOverP) * 0.5;
  17534. return new BABYLON.Vector3(tx, ty, tz);
  17535. };
  17536. for (var i = 0; i <= radialSegments; i++) {
  17537. var modI = i % radialSegments;
  17538. var u = modI / radialSegments * 2 * p * Math.PI;
  17539. var p1 = getPos(u);
  17540. var p2 = getPos(u + 0.01);
  17541. var tang = p2.subtract(p1);
  17542. var n = p2.add(p1);
  17543. var bitan = BABYLON.Vector3.Cross(tang, n);
  17544. n = BABYLON.Vector3.Cross(bitan, tang);
  17545. bitan.normalize();
  17546. n.normalize();
  17547. for (var j = 0; j < tubularSegments; j++) {
  17548. var modJ = j % tubularSegments;
  17549. var v = modJ / tubularSegments * 2 * Math.PI;
  17550. var cx = -tube * Math.cos(v);
  17551. var cy = tube * Math.sin(v);
  17552. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17553. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17554. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17555. uvs.push(i / radialSegments);
  17556. uvs.push(j / tubularSegments);
  17557. }
  17558. }
  17559. for (i = 0; i < radialSegments; i++) {
  17560. for (j = 0; j < tubularSegments; j++) {
  17561. var jNext = (j + 1) % tubularSegments;
  17562. var a = i * tubularSegments + j;
  17563. var b = (i + 1) * tubularSegments + j;
  17564. var c = (i + 1) * tubularSegments + jNext;
  17565. var d = i * tubularSegments + jNext;
  17566. indices.push(d);
  17567. indices.push(b);
  17568. indices.push(a);
  17569. indices.push(d);
  17570. indices.push(c);
  17571. indices.push(b);
  17572. }
  17573. }
  17574. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17575. var vertexData = new BABYLON.VertexData();
  17576. vertexData.indices = indices;
  17577. vertexData.positions = positions;
  17578. vertexData.normals = normals;
  17579. vertexData.uvs = uvs;
  17580. return vertexData;
  17581. };
  17582. VertexData.ComputeNormals = function (positions, indices, normals) {
  17583. var positionVectors = [];
  17584. var facesOfVertices = [];
  17585. var index;
  17586. for (index = 0; index < positions.length; index += 3) {
  17587. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17588. positionVectors.push(vector3);
  17589. facesOfVertices.push([]);
  17590. }
  17591. var facesNormals = [];
  17592. for (index = 0; index < indices.length / 3; index++) {
  17593. var i1 = indices[index * 3];
  17594. var i2 = indices[index * 3 + 1];
  17595. var i3 = indices[index * 3 + 2];
  17596. var p1 = positionVectors[i1];
  17597. var p2 = positionVectors[i2];
  17598. var p3 = positionVectors[i3];
  17599. var p1p2 = p1.subtract(p2);
  17600. var p3p2 = p3.subtract(p2);
  17601. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17602. facesOfVertices[i1].push(index);
  17603. facesOfVertices[i2].push(index);
  17604. facesOfVertices[i3].push(index);
  17605. }
  17606. for (index = 0; index < positionVectors.length; index++) {
  17607. var faces = facesOfVertices[index];
  17608. var normal = BABYLON.Vector3.Zero();
  17609. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17610. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17611. }
  17612. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17613. normals[index * 3] = normal.x;
  17614. normals[index * 3 + 1] = normal.y;
  17615. normals[index * 3 + 2] = normal.z;
  17616. }
  17617. };
  17618. return VertexData;
  17619. })();
  17620. BABYLON.VertexData = VertexData;
  17621. })(BABYLON || (BABYLON = {}));
  17622. var __extends = this.__extends || function (d, b) {
  17623. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17624. function __() { this.constructor = d; }
  17625. __.prototype = b.prototype;
  17626. d.prototype = new __();
  17627. };
  17628. var BABYLON;
  17629. (function (BABYLON) {
  17630. var buildCamera = function (that, name) {
  17631. that._leftCamera.isIntermediate = true;
  17632. that.subCameras.push(that._leftCamera);
  17633. that.subCameras.push(that._rightCamera);
  17634. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17635. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17636. that._anaglyphPostProcess.onApply = function (effect) {
  17637. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17638. };
  17639. that._update();
  17640. };
  17641. var AnaglyphArcRotateCamera = (function (_super) {
  17642. __extends(AnaglyphArcRotateCamera, _super);
  17643. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17644. _super.call(this, name, alpha, beta, radius, target, scene);
  17645. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17646. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17647. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17648. buildCamera(this, name);
  17649. }
  17650. AnaglyphArcRotateCamera.prototype._update = function () {
  17651. this._updateCamera(this._leftCamera);
  17652. this._updateCamera(this._rightCamera);
  17653. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17654. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17655. _super.prototype._update.call(this);
  17656. };
  17657. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17658. camera.beta = this.beta;
  17659. camera.radius = this.radius;
  17660. camera.minZ = this.minZ;
  17661. camera.maxZ = this.maxZ;
  17662. camera.fov = this.fov;
  17663. camera.target = this.target;
  17664. };
  17665. return AnaglyphArcRotateCamera;
  17666. })(BABYLON.ArcRotateCamera);
  17667. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17668. var AnaglyphFreeCamera = (function (_super) {
  17669. __extends(AnaglyphFreeCamera, _super);
  17670. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17671. _super.call(this, name, position, scene);
  17672. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17673. this._transformMatrix = new BABYLON.Matrix();
  17674. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17675. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17676. buildCamera(this, name);
  17677. }
  17678. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17679. var target = this.getTarget();
  17680. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17681. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17682. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17683. };
  17684. AnaglyphFreeCamera.prototype._update = function () {
  17685. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17686. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17687. this._updateCamera(this._leftCamera);
  17688. this._updateCamera(this._rightCamera);
  17689. _super.prototype._update.call(this);
  17690. };
  17691. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17692. camera.minZ = this.minZ;
  17693. camera.maxZ = this.maxZ;
  17694. camera.fov = this.fov;
  17695. camera.viewport = this.viewport;
  17696. camera.setTarget(this.getTarget());
  17697. };
  17698. return AnaglyphFreeCamera;
  17699. })(BABYLON.FreeCamera);
  17700. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17701. })(BABYLON || (BABYLON = {}));
  17702. var __extends = this.__extends || function (d, b) {
  17703. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17704. function __() { this.constructor = d; }
  17705. __.prototype = b.prototype;
  17706. d.prototype = new __();
  17707. };
  17708. var BABYLON;
  17709. (function (BABYLON) {
  17710. var AnaglyphPostProcess = (function (_super) {
  17711. __extends(AnaglyphPostProcess, _super);
  17712. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17713. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17714. }
  17715. return AnaglyphPostProcess;
  17716. })(BABYLON.PostProcess);
  17717. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17718. })(BABYLON || (BABYLON = {}));
  17719. var BABYLON;
  17720. (function (BABYLON) {
  17721. var Tags = (function () {
  17722. function Tags() {
  17723. }
  17724. Tags.EnableFor = function (obj) {
  17725. obj._tags = obj._tags || {};
  17726. obj.hasTags = function () {
  17727. return Tags.HasTags(obj);
  17728. };
  17729. obj.addTags = function (tagsString) {
  17730. return Tags.AddTagsTo(obj, tagsString);
  17731. };
  17732. obj.removeTags = function (tagsString) {
  17733. return Tags.RemoveTagsFrom(obj, tagsString);
  17734. };
  17735. obj.matchesTagsQuery = function (tagsQuery) {
  17736. return Tags.MatchesQuery(obj, tagsQuery);
  17737. };
  17738. };
  17739. Tags.DisableFor = function (obj) {
  17740. delete obj._tags;
  17741. delete obj.hasTags;
  17742. delete obj.addTags;
  17743. delete obj.removeTags;
  17744. delete obj.matchesTagsQuery;
  17745. };
  17746. Tags.HasTags = function (obj) {
  17747. if (!obj._tags) {
  17748. return false;
  17749. }
  17750. return !BABYLON.Tools.IsEmpty(obj._tags);
  17751. };
  17752. Tags.GetTags = function (obj) {
  17753. if (!obj._tags) {
  17754. return null;
  17755. }
  17756. return obj._tags;
  17757. };
  17758. Tags.AddTagsTo = function (obj, tagsString) {
  17759. if (!tagsString) {
  17760. return;
  17761. }
  17762. var tags = tagsString.split(" ");
  17763. for (var t in tags) {
  17764. Tags._AddTagTo(obj, tags[t]);
  17765. }
  17766. };
  17767. Tags._AddTagTo = function (obj, tag) {
  17768. tag = tag.trim();
  17769. if (tag === "" || tag === "true" || tag === "false") {
  17770. return;
  17771. }
  17772. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17773. return;
  17774. }
  17775. Tags.EnableFor(obj);
  17776. obj._tags[tag] = true;
  17777. };
  17778. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17779. if (!Tags.HasTags(obj)) {
  17780. return;
  17781. }
  17782. var tags = tagsString.split(" ");
  17783. for (var t in tags) {
  17784. Tags._RemoveTagFrom(obj, tags[t]);
  17785. }
  17786. };
  17787. Tags._RemoveTagFrom = function (obj, tag) {
  17788. delete obj._tags[tag];
  17789. };
  17790. Tags.MatchesQuery = function (obj, tagsQuery) {
  17791. if (tagsQuery === undefined) {
  17792. return true;
  17793. }
  17794. if (tagsQuery === "") {
  17795. return Tags.HasTags(obj);
  17796. }
  17797. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17798. return Tags.HasTags(obj) && obj._tags[r];
  17799. });
  17800. };
  17801. return Tags;
  17802. })();
  17803. BABYLON.Tags = Tags;
  17804. })(BABYLON || (BABYLON = {}));
  17805. var BABYLON;
  17806. (function (BABYLON) {
  17807. (function (Internals) {
  17808. var AndOrNotEvaluator = (function () {
  17809. function AndOrNotEvaluator() {
  17810. }
  17811. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17812. if (!query.match(/\([^\(\)]*\)/g)) {
  17813. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17814. } else {
  17815. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17816. r = r.slice(1, r.length - 1);
  17817. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17818. });
  17819. }
  17820. if (query === "true") {
  17821. return true;
  17822. }
  17823. if (query === "false") {
  17824. return false;
  17825. }
  17826. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17827. };
  17828. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17829. evaluateCallback = evaluateCallback || (function (r) {
  17830. return r === "true" ? true : false;
  17831. });
  17832. var result;
  17833. var or = parenthesisContent.split("||");
  17834. for (var i in or) {
  17835. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17836. var and = ori.split("&&");
  17837. if (and.length > 1) {
  17838. for (var j = 0; j < and.length; ++j) {
  17839. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17840. if (andj !== "true" && andj !== "false") {
  17841. if (andj[0] === "!") {
  17842. result = !evaluateCallback(andj.substring(1));
  17843. } else {
  17844. result = evaluateCallback(andj);
  17845. }
  17846. } else {
  17847. result = andj === "true" ? true : false;
  17848. }
  17849. if (!result) {
  17850. ori = "false";
  17851. break;
  17852. }
  17853. }
  17854. }
  17855. if (result || ori === "true") {
  17856. result = true;
  17857. break;
  17858. }
  17859. if (ori !== "true" && ori !== "false") {
  17860. if (ori[0] === "!") {
  17861. result = !evaluateCallback(ori.substring(1));
  17862. } else {
  17863. result = evaluateCallback(ori);
  17864. }
  17865. } else {
  17866. result = ori === "true" ? true : false;
  17867. }
  17868. }
  17869. return result ? "true" : "false";
  17870. };
  17871. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17872. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17873. r = r.replace(/[\s]/g, function () {
  17874. return "";
  17875. });
  17876. return r.length % 2 ? "!" : "";
  17877. });
  17878. booleanString = booleanString.trim();
  17879. if (booleanString === "!true") {
  17880. booleanString = "false";
  17881. } else if (booleanString === "!false") {
  17882. booleanString = "true";
  17883. }
  17884. return booleanString;
  17885. };
  17886. return AndOrNotEvaluator;
  17887. })();
  17888. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17889. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17890. var Internals = BABYLON.Internals;
  17891. })(BABYLON || (BABYLON = {}));
  17892. var BABYLON;
  17893. (function (BABYLON) {
  17894. var PostProcessRenderPass = (function () {
  17895. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17896. this._enabled = true;
  17897. this._refCount = 0;
  17898. this._name = name;
  17899. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17900. this.setRenderList(renderList);
  17901. this._renderTexture.onBeforeRender = beforeRender;
  17902. this._renderTexture.onAfterRender = afterRender;
  17903. this._scene = scene;
  17904. }
  17905. PostProcessRenderPass.prototype._incRefCount = function () {
  17906. if (this._refCount === 0) {
  17907. this._scene.customRenderTargets.push(this._renderTexture);
  17908. }
  17909. return ++this._refCount;
  17910. };
  17911. PostProcessRenderPass.prototype._decRefCount = function () {
  17912. this._refCount--;
  17913. if (this._refCount <= 0) {
  17914. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17915. }
  17916. return this._refCount;
  17917. };
  17918. PostProcessRenderPass.prototype._update = function () {
  17919. this.setRenderList(this._renderList);
  17920. };
  17921. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17922. this._renderTexture.renderList = renderList;
  17923. };
  17924. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17925. return this._renderTexture;
  17926. };
  17927. return PostProcessRenderPass;
  17928. })();
  17929. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17930. })(BABYLON || (BABYLON = {}));
  17931. var BABYLON;
  17932. (function (BABYLON) {
  17933. var PostProcessRenderEffect = (function () {
  17934. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17935. this._engine = engine;
  17936. this._name = name;
  17937. this._singleInstance = singleInstance || true;
  17938. this._getPostProcess = getPostProcess;
  17939. this._cameras = [];
  17940. this._postProcesses = [];
  17941. this._indicesForCamera = [];
  17942. this._renderPasses = [];
  17943. this._renderEffectAsPasses = [];
  17944. }
  17945. PostProcessRenderEffect.prototype._update = function () {
  17946. for (var renderPassName in this._renderPasses) {
  17947. this._renderPasses[renderPassName]._update();
  17948. }
  17949. };
  17950. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17951. this._renderPasses[renderPass._name] = renderPass;
  17952. this._linkParameters();
  17953. };
  17954. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17955. delete this._renderPasses[renderPass._name];
  17956. this._linkParameters();
  17957. };
  17958. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17959. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17960. this._linkParameters();
  17961. };
  17962. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17963. for (var renderPassName in this._renderPasses) {
  17964. if (renderPassName === passName) {
  17965. return this._renderPasses[passName];
  17966. }
  17967. }
  17968. };
  17969. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17970. this._renderPasses.length = 0;
  17971. this._linkParameters();
  17972. };
  17973. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17974. var cameraKey;
  17975. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17976. for (var i = 0; i < _cam.length; i++) {
  17977. var camera = _cam[i];
  17978. var cameraName = camera.name;
  17979. if (this._singleInstance) {
  17980. cameraKey = 0;
  17981. } else {
  17982. cameraKey = cameraName;
  17983. }
  17984. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17985. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17986. if (!this._indicesForCamera[cameraName]) {
  17987. this._indicesForCamera[cameraName] = [];
  17988. }
  17989. this._indicesForCamera[cameraName].push(index);
  17990. if (this._cameras.indexOf(camera) === -1) {
  17991. this._cameras[cameraName] = camera;
  17992. }
  17993. for (var passName in this._renderPasses) {
  17994. this._renderPasses[passName]._incRefCount();
  17995. }
  17996. }
  17997. this._linkParameters();
  17998. };
  17999. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18000. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18001. for (var i = 0; i < _cam.length; i++) {
  18002. var camera = _cam[i];
  18003. var cameraName = camera.name;
  18004. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18005. var index = this._cameras.indexOf(cameraName);
  18006. this._indicesForCamera.splice(index, 1);
  18007. this._cameras.splice(index, 1);
  18008. for (var passName in this._renderPasses) {
  18009. this._renderPasses[passName]._decRefCount();
  18010. }
  18011. }
  18012. };
  18013. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18014. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18015. for (var i = 0; i < _cam.length; i++) {
  18016. var camera = _cam[i];
  18017. var cameraName = camera.name;
  18018. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18019. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18020. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18021. }
  18022. }
  18023. for (var passName in this._renderPasses) {
  18024. this._renderPasses[passName]._incRefCount();
  18025. }
  18026. }
  18027. };
  18028. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18029. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18030. for (var i = 0; i < _cam.length; i++) {
  18031. var camera = _cam[i];
  18032. var cameraName = camera.Name;
  18033. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18034. for (var passName in this._renderPasses) {
  18035. this._renderPasses[passName]._decRefCount();
  18036. }
  18037. }
  18038. };
  18039. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18040. if (this._singleInstance) {
  18041. return this._postProcesses[0];
  18042. } else {
  18043. return this._postProcesses[camera.name];
  18044. }
  18045. };
  18046. PostProcessRenderEffect.prototype._linkParameters = function () {
  18047. var _this = this;
  18048. for (var index in this._postProcesses) {
  18049. if (this.applyParameters) {
  18050. this.applyParameters(this._postProcesses[index]);
  18051. }
  18052. this._postProcesses[index].onBeforeRender = function (effect) {
  18053. _this._linkTextures(effect);
  18054. };
  18055. }
  18056. };
  18057. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18058. for (var renderPassName in this._renderPasses) {
  18059. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18060. }
  18061. for (var renderEffectName in this._renderEffectAsPasses) {
  18062. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18063. }
  18064. };
  18065. return PostProcessRenderEffect;
  18066. })();
  18067. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18068. })(BABYLON || (BABYLON = {}));
  18069. var BABYLON;
  18070. (function (BABYLON) {
  18071. var PostProcessRenderPipeline = (function () {
  18072. function PostProcessRenderPipeline(engine, name) {
  18073. this._engine = engine;
  18074. this._name = name;
  18075. this._renderEffects = [];
  18076. this._renderEffectsForIsolatedPass = [];
  18077. this._cameras = [];
  18078. }
  18079. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18080. this._renderEffects[renderEffect._name] = renderEffect;
  18081. };
  18082. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18083. var renderEffects = this._renderEffects[renderEffectName];
  18084. if (!renderEffects) {
  18085. return;
  18086. }
  18087. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18088. };
  18089. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18090. var renderEffects = this._renderEffects[renderEffectName];
  18091. if (!renderEffects) {
  18092. return;
  18093. }
  18094. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18095. };
  18096. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18097. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18098. var indicesToDelete = [];
  18099. for (var i = 0; i < _cam.length; i++) {
  18100. var camera = _cam[i];
  18101. var cameraName = camera.name;
  18102. if (this._cameras.indexOf(camera) === -1) {
  18103. this._cameras[cameraName] = camera;
  18104. } else if (unique) {
  18105. indicesToDelete.push(i);
  18106. }
  18107. }
  18108. for (var i = 0; i < indicesToDelete.length; i++) {
  18109. cameras.splice(indicesToDelete[i], 1);
  18110. }
  18111. for (var renderEffectName in this._renderEffects) {
  18112. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18113. }
  18114. };
  18115. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18116. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18117. for (var renderEffectName in this._renderEffects) {
  18118. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18119. }
  18120. for (var i = 0; i < _cam.length; i++) {
  18121. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18122. }
  18123. };
  18124. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18125. var _this = this;
  18126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18127. var pass = null;
  18128. for (var renderEffectName in this._renderEffects) {
  18129. pass = this._renderEffects[renderEffectName].getPass(passName);
  18130. if (pass != null) {
  18131. break;
  18132. }
  18133. }
  18134. if (pass === null) {
  18135. return;
  18136. }
  18137. for (var renderEffectName in this._renderEffects) {
  18138. this._renderEffects[renderEffectName]._disable(_cam);
  18139. }
  18140. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18141. for (var i = 0; i < _cam.length; i++) {
  18142. var camera = _cam[i];
  18143. var cameraName = camera.name;
  18144. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18145. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18146. });
  18147. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18148. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18149. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18150. }
  18151. };
  18152. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18153. var _this = this;
  18154. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18155. for (var i = 0; i < _cam.length; i++) {
  18156. var camera = _cam[i];
  18157. var cameraName = camera.name;
  18158. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18159. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18160. });
  18161. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18162. }
  18163. for (var renderEffectName in this._renderEffects) {
  18164. this._renderEffects[renderEffectName]._enable(_cam);
  18165. }
  18166. };
  18167. PostProcessRenderPipeline.prototype._update = function () {
  18168. for (var renderEffectName in this._renderEffects) {
  18169. this._renderEffects[renderEffectName]._update();
  18170. }
  18171. for (var i = 0; i < this._cameras.length; i++) {
  18172. var cameraName = this._cameras[i].name;
  18173. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18174. this._renderEffectsForIsolatedPass[cameraName]._update();
  18175. }
  18176. }
  18177. };
  18178. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18179. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18180. return PostProcessRenderPipeline;
  18181. })();
  18182. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18183. })(BABYLON || (BABYLON = {}));
  18184. var BABYLON;
  18185. (function (BABYLON) {
  18186. var PostProcessRenderPipelineManager = (function () {
  18187. function PostProcessRenderPipelineManager() {
  18188. this._renderPipelines = new Array();
  18189. }
  18190. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18191. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18192. };
  18193. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18194. var renderPipeline = this._renderPipelines[renderPipelineName];
  18195. if (!renderPipeline) {
  18196. return;
  18197. }
  18198. renderPipeline._attachCameras(cameras, unique);
  18199. };
  18200. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18201. var renderPipeline = this._renderPipelines[renderPipelineName];
  18202. if (!renderPipeline) {
  18203. return;
  18204. }
  18205. renderPipeline._detachCameras(cameras);
  18206. };
  18207. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18208. var renderPipeline = this._renderPipelines[renderPipelineName];
  18209. if (!renderPipeline) {
  18210. return;
  18211. }
  18212. renderPipeline._enableEffect(renderEffectName, cameras);
  18213. };
  18214. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18215. var renderPipeline = this._renderPipelines[renderPipelineName];
  18216. if (!renderPipeline) {
  18217. return;
  18218. }
  18219. renderPipeline._disableEffect(renderEffectName, cameras);
  18220. };
  18221. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18222. var renderPipeline = this._renderPipelines[renderPipelineName];
  18223. if (!renderPipeline) {
  18224. return;
  18225. }
  18226. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18227. };
  18228. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18229. var renderPipeline = this._renderPipelines[renderPipelineName];
  18230. if (!renderPipeline) {
  18231. return;
  18232. }
  18233. renderPipeline._disableDisplayOnlyPass(cameras);
  18234. };
  18235. PostProcessRenderPipelineManager.prototype.update = function () {
  18236. for (var renderPipelineName in this._renderPipelines) {
  18237. this._renderPipelines[renderPipelineName]._update();
  18238. }
  18239. };
  18240. return PostProcessRenderPipelineManager;
  18241. })();
  18242. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18243. })(BABYLON || (BABYLON = {}));
  18244. var __extends = this.__extends || function (d, b) {
  18245. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18246. function __() { this.constructor = d; }
  18247. __.prototype = b.prototype;
  18248. d.prototype = new __();
  18249. };
  18250. var BABYLON;
  18251. (function (BABYLON) {
  18252. var DisplayPassPostProcess = (function (_super) {
  18253. __extends(DisplayPassPostProcess, _super);
  18254. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18255. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18256. }
  18257. return DisplayPassPostProcess;
  18258. })(BABYLON.PostProcess);
  18259. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18260. })(BABYLON || (BABYLON = {}));
  18261. var BABYLON;
  18262. (function (BABYLON) {
  18263. var BoundingBoxRenderer = (function () {
  18264. function BoundingBoxRenderer(scene) {
  18265. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18266. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18267. this.showBackLines = true;
  18268. this.renderList = new BABYLON.SmartArray(32);
  18269. this._scene = scene;
  18270. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18271. attributes: ["position"],
  18272. uniforms: ["worldViewProjection", "color"]
  18273. });
  18274. var engine = this._scene.getEngine();
  18275. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18276. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18277. this._ib = 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]);
  18278. }
  18279. BoundingBoxRenderer.prototype.reset = function () {
  18280. this.renderList.reset();
  18281. };
  18282. BoundingBoxRenderer.prototype.render = function () {
  18283. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18284. return;
  18285. }
  18286. var engine = this._scene.getEngine();
  18287. engine.setDepthWrite(false);
  18288. this._colorShader._preBind();
  18289. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18290. var boundingBox = this.renderList.data[boundingBoxIndex];
  18291. var min = boundingBox.minimum;
  18292. var max = boundingBox.maximum;
  18293. var diff = max.subtract(min);
  18294. var median = min.add(diff.scale(0.5));
  18295. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18296. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18297. if (this.showBackLines) {
  18298. engine.setDepthFunctionToGreaterOrEqual();
  18299. this._colorShader.setColor4("color", this.backColor.toColor4());
  18300. this._colorShader.bind(worldMatrix);
  18301. engine.draw(false, 0, 24);
  18302. }
  18303. engine.setDepthFunctionToLess();
  18304. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18305. this._colorShader.bind(worldMatrix);
  18306. engine.draw(false, 0, 24);
  18307. }
  18308. this._colorShader.unbind();
  18309. engine.setDepthFunctionToLessOrEqual();
  18310. engine.setDepthWrite(true);
  18311. };
  18312. BoundingBoxRenderer.prototype.dispose = function () {
  18313. this._colorShader.dispose();
  18314. this._vb.dispose();
  18315. this._scene.getEngine()._releaseBuffer(this._ib);
  18316. };
  18317. return BoundingBoxRenderer;
  18318. })();
  18319. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18320. })(BABYLON || (BABYLON = {}));
  18321. /**
  18322. * Based on jsTGALoader - Javascript loader for TGA file
  18323. * By Vincent Thibault
  18324. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18325. */
  18326. var BABYLON;
  18327. (function (BABYLON) {
  18328. (function (Internals) {
  18329. var TGATools = (function () {
  18330. function TGATools() {
  18331. }
  18332. TGATools.GetTGAHeader = function (data) {
  18333. var offset = 0;
  18334. var header = {
  18335. id_length: data[offset++],
  18336. colormap_type: data[offset++],
  18337. image_type: data[offset++],
  18338. colormap_index: data[offset++] | data[offset++] << 8,
  18339. colormap_length: data[offset++] | data[offset++] << 8,
  18340. colormap_size: data[offset++],
  18341. origin: [
  18342. data[offset++] | data[offset++] << 8,
  18343. data[offset++] | data[offset++] << 8
  18344. ],
  18345. width: data[offset++] | data[offset++] << 8,
  18346. height: data[offset++] | data[offset++] << 8,
  18347. pixel_size: data[offset++],
  18348. flags: data[offset++]
  18349. };
  18350. return header;
  18351. };
  18352. TGATools.UploadContent = function (gl, data) {
  18353. if (data.length < 19) {
  18354. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18355. return;
  18356. }
  18357. var offset = 18;
  18358. var header = TGATools.GetTGAHeader(data);
  18359. if (header.id_length + offset > data.length) {
  18360. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18361. return;
  18362. }
  18363. offset += header.id_length;
  18364. var use_rle = false;
  18365. var use_pal = false;
  18366. var use_rgb = false;
  18367. var use_grey = false;
  18368. switch (header.image_type) {
  18369. case TGATools._TYPE_RLE_INDEXED:
  18370. use_rle = true;
  18371. case TGATools._TYPE_INDEXED:
  18372. use_pal = true;
  18373. break;
  18374. case TGATools._TYPE_RLE_RGB:
  18375. use_rle = true;
  18376. case TGATools._TYPE_RGB:
  18377. use_rgb = true;
  18378. break;
  18379. case TGATools._TYPE_RLE_GREY:
  18380. use_rle = true;
  18381. case TGATools._TYPE_GREY:
  18382. use_grey = true;
  18383. break;
  18384. }
  18385. var pixel_data;
  18386. var numAlphaBits = header.flags & 0xf;
  18387. var pixel_size = header.pixel_size >> 3;
  18388. var pixel_total = header.width * header.height * pixel_size;
  18389. var palettes;
  18390. if (use_pal) {
  18391. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18392. }
  18393. if (use_rle) {
  18394. pixel_data = new Uint8Array(pixel_total);
  18395. var c, count, i;
  18396. var localOffset = 0;
  18397. var pixels = new Uint8Array(pixel_size);
  18398. while (offset < pixel_total && localOffset < pixel_total) {
  18399. c = data[offset++];
  18400. count = (c & 0x7f) + 1;
  18401. if (c & 0x80) {
  18402. for (i = 0; i < pixel_size; ++i) {
  18403. pixels[i] = data[offset++];
  18404. }
  18405. for (i = 0; i < count; ++i) {
  18406. pixel_data.set(pixels, localOffset + i * pixel_size);
  18407. }
  18408. localOffset += pixel_size * count;
  18409. } else {
  18410. count *= pixel_size;
  18411. for (i = 0; i < count; ++i) {
  18412. pixel_data[localOffset + i] = data[offset++];
  18413. }
  18414. localOffset += count;
  18415. }
  18416. }
  18417. } else {
  18418. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18419. }
  18420. var x_start, y_start, x_step, y_step, y_end, x_end;
  18421. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18422. default:
  18423. case TGATools._ORIGIN_UL:
  18424. x_start = 0;
  18425. x_step = 1;
  18426. x_end = header.width;
  18427. y_start = 0;
  18428. y_step = 1;
  18429. y_end = header.height;
  18430. break;
  18431. case TGATools._ORIGIN_BL:
  18432. x_start = 0;
  18433. x_step = 1;
  18434. x_end = header.width;
  18435. y_start = header.height - 1;
  18436. y_step = -1;
  18437. y_end = -1;
  18438. break;
  18439. case TGATools._ORIGIN_UR:
  18440. x_start = header.width - 1;
  18441. x_step = -1;
  18442. x_end = -1;
  18443. y_start = 0;
  18444. y_step = 1;
  18445. y_end = header.height;
  18446. break;
  18447. case TGATools._ORIGIN_BR:
  18448. x_start = header.width - 1;
  18449. x_step = -1;
  18450. x_end = -1;
  18451. y_start = header.height - 1;
  18452. y_step = -1;
  18453. y_end = -1;
  18454. break;
  18455. }
  18456. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18457. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18458. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18459. };
  18460. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18461. var image = pixel_data, colormap = palettes;
  18462. var width = header.width, height = header.height;
  18463. var color, i = 0, x, y;
  18464. var imageData = new Uint8Array(width * height * 4);
  18465. for (y = y_start; y !== y_end; y += y_step) {
  18466. for (x = x_start; x !== x_end; x += x_step, i++) {
  18467. color = image[i];
  18468. imageData[(x + width * y) * 4 + 3] = 255;
  18469. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18470. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18471. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18472. }
  18473. }
  18474. return imageData;
  18475. };
  18476. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18477. var image = pixel_data;
  18478. var width = header.width, height = header.height;
  18479. var color, i = 0, x, y;
  18480. var imageData = new Uint8Array(width * height * 4);
  18481. for (y = y_start; y !== y_end; y += y_step) {
  18482. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18483. color = image[i + 0] + (image[i + 1] << 8);
  18484. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18485. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18486. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18487. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18488. }
  18489. }
  18490. return imageData;
  18491. };
  18492. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18493. var image = pixel_data;
  18494. var width = header.width, height = header.height;
  18495. var i = 0, x, y;
  18496. var imageData = new Uint8Array(width * height * 4);
  18497. for (y = y_start; y !== y_end; y += y_step) {
  18498. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18499. imageData[(x + width * y) * 4 + 3] = 255;
  18500. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18501. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18502. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18503. }
  18504. }
  18505. return imageData;
  18506. };
  18507. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18508. var image = pixel_data;
  18509. var width = header.width, height = header.height;
  18510. var i = 0, x, y;
  18511. var imageData = new Uint8Array(width * height * 4);
  18512. for (y = y_start; y !== y_end; y += y_step) {
  18513. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18514. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18515. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18516. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18517. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18518. }
  18519. }
  18520. return imageData;
  18521. };
  18522. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18523. var image = pixel_data;
  18524. var width = header.width, height = header.height;
  18525. var color, i = 0, x, y;
  18526. var imageData = new Uint8Array(width * height * 4);
  18527. for (y = y_start; y !== y_end; y += y_step) {
  18528. for (x = x_start; x !== x_end; x += x_step, i++) {
  18529. color = image[i];
  18530. imageData[(x + width * y) * 4 + 0] = color;
  18531. imageData[(x + width * y) * 4 + 1] = color;
  18532. imageData[(x + width * y) * 4 + 2] = color;
  18533. imageData[(x + width * y) * 4 + 3] = 255;
  18534. }
  18535. }
  18536. return imageData;
  18537. };
  18538. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18539. var image = pixel_data;
  18540. var width = header.width, height = header.height;
  18541. var i = 0, x, y;
  18542. var imageData = new Uint8Array(width * height * 4);
  18543. for (y = y_start; y !== y_end; y += y_step) {
  18544. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18545. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18546. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18547. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18548. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18549. }
  18550. }
  18551. return imageData;
  18552. };
  18553. TGATools._TYPE_NO_DATA = 0;
  18554. TGATools._TYPE_INDEXED = 1;
  18555. TGATools._TYPE_RGB = 2;
  18556. TGATools._TYPE_GREY = 3;
  18557. TGATools._TYPE_RLE_INDEXED = 9;
  18558. TGATools._TYPE_RLE_RGB = 10;
  18559. TGATools._TYPE_RLE_GREY = 11;
  18560. TGATools._ORIGIN_MASK = 0x30;
  18561. TGATools._ORIGIN_SHIFT = 0x04;
  18562. TGATools._ORIGIN_BL = 0x00;
  18563. TGATools._ORIGIN_BR = 0x01;
  18564. TGATools._ORIGIN_UL = 0x02;
  18565. TGATools._ORIGIN_UR = 0x03;
  18566. return TGATools;
  18567. })();
  18568. Internals.TGATools = TGATools;
  18569. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18570. var Internals = BABYLON.Internals;
  18571. })(BABYLON || (BABYLON = {}));
  18572. var BABYLON;
  18573. (function (BABYLON) {
  18574. (function (Internals) {
  18575. var DDS_MAGIC = 0x20534444;
  18576. 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;
  18577. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18578. 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;
  18579. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18580. function FourCCToInt32(value) {
  18581. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18582. }
  18583. function Int32ToFourCC(value) {
  18584. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18585. }
  18586. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18587. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18588. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18589. var headerLengthInt = 31;
  18590. var off_magic = 0;
  18591. var off_size = 1;
  18592. var off_flags = 2;
  18593. var off_height = 3;
  18594. var off_width = 4;
  18595. var off_mipmapCount = 7;
  18596. var off_pfFlags = 20;
  18597. var off_pfFourCC = 21;
  18598. var off_RGBbpp = 22;
  18599. var off_RMask = 23;
  18600. var off_GMask = 24;
  18601. var off_BMask = 25;
  18602. var off_AMask = 26;
  18603. var off_caps1 = 27;
  18604. var off_caps2 = 28;
  18605. ;
  18606. var DDSTools = (function () {
  18607. function DDSTools() {
  18608. }
  18609. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18610. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18611. var mipmapCount = 1;
  18612. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18613. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18614. }
  18615. return {
  18616. width: header[off_width],
  18617. height: header[off_height],
  18618. mipmapCount: mipmapCount,
  18619. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18620. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18621. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18622. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18623. };
  18624. };
  18625. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18626. var byteArray = new Uint8Array(dataLength);
  18627. var srcData = new Uint8Array(arrayBuffer);
  18628. var index = 0;
  18629. for (var y = height - 1; y >= 0; y--) {
  18630. for (var x = 0; x < width; x++) {
  18631. var srcPos = dataOffset + (x + y * width) * 4;
  18632. byteArray[index + 2] = srcData[srcPos];
  18633. byteArray[index + 1] = srcData[srcPos + 1];
  18634. byteArray[index] = srcData[srcPos + 2];
  18635. byteArray[index + 3] = srcData[srcPos + 3];
  18636. index += 4;
  18637. }
  18638. }
  18639. return byteArray;
  18640. };
  18641. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18642. var byteArray = new Uint8Array(dataLength);
  18643. var srcData = new Uint8Array(arrayBuffer);
  18644. var index = 0;
  18645. for (var y = height - 1; y >= 0; y--) {
  18646. for (var x = 0; x < width; x++) {
  18647. var srcPos = dataOffset + (x + y * width) * 3;
  18648. byteArray[index + 2] = srcData[srcPos];
  18649. byteArray[index + 1] = srcData[srcPos + 1];
  18650. byteArray[index] = srcData[srcPos + 2];
  18651. index += 3;
  18652. }
  18653. }
  18654. return byteArray;
  18655. };
  18656. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18657. var byteArray = new Uint8Array(dataLength);
  18658. var srcData = new Uint8Array(arrayBuffer);
  18659. var index = 0;
  18660. for (var y = height - 1; y >= 0; y--) {
  18661. for (var x = 0; x < width; x++) {
  18662. var srcPos = dataOffset + (x + y * width);
  18663. byteArray[index] = srcData[srcPos];
  18664. index++;
  18665. }
  18666. }
  18667. return byteArray;
  18668. };
  18669. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18670. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18671. if (header[off_magic] != DDS_MAGIC) {
  18672. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18673. return;
  18674. }
  18675. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18676. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18677. return;
  18678. }
  18679. if (info.isFourCC) {
  18680. fourCC = header[off_pfFourCC];
  18681. switch (fourCC) {
  18682. case FOURCC_DXT1:
  18683. blockBytes = 8;
  18684. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18685. break;
  18686. case FOURCC_DXT3:
  18687. blockBytes = 16;
  18688. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18689. break;
  18690. case FOURCC_DXT5:
  18691. blockBytes = 16;
  18692. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18693. break;
  18694. default:
  18695. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18696. return;
  18697. }
  18698. }
  18699. mipmapCount = 1;
  18700. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18701. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18702. }
  18703. var bpp = header[off_RGBbpp];
  18704. for (var face = 0; face < faces; face++) {
  18705. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18706. width = header[off_width];
  18707. height = header[off_height];
  18708. dataOffset = header[off_size] + 4;
  18709. for (i = 0; i < mipmapCount; ++i) {
  18710. if (info.isRGB) {
  18711. if (bpp == 24) {
  18712. dataLength = width * height * 3;
  18713. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18714. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18715. } else {
  18716. dataLength = width * height * 4;
  18717. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18718. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18719. }
  18720. } else if (info.isLuminance) {
  18721. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18722. var unpaddedRowSize = width;
  18723. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18724. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18725. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18726. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18727. } else {
  18728. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18729. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18730. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18731. }
  18732. dataOffset += dataLength;
  18733. width *= 0.5;
  18734. height *= 0.5;
  18735. width = Math.max(1.0, width);
  18736. height = Math.max(1.0, height);
  18737. }
  18738. }
  18739. };
  18740. return DDSTools;
  18741. })();
  18742. Internals.DDSTools = DDSTools;
  18743. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18744. var Internals = BABYLON.Internals;
  18745. })(BABYLON || (BABYLON = {}));
  18746. var BABYLON;
  18747. (function (BABYLON) {
  18748. var SmartArray = (function () {
  18749. function SmartArray(capacity) {
  18750. this.length = 0;
  18751. this._duplicateId = 0;
  18752. this.data = new Array(capacity);
  18753. this._id = SmartArray._GlobalId++;
  18754. }
  18755. SmartArray.prototype.push = function (value) {
  18756. this.data[this.length++] = value;
  18757. if (this.length > this.data.length) {
  18758. this.data.length *= 2;
  18759. }
  18760. if (!value.__smartArrayFlags) {
  18761. value.__smartArrayFlags = {};
  18762. }
  18763. value.__smartArrayFlags[this._id] = this._duplicateId;
  18764. };
  18765. SmartArray.prototype.pushNoDuplicate = function (value) {
  18766. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18767. return;
  18768. }
  18769. this.push(value);
  18770. };
  18771. SmartArray.prototype.sort = function (compareFn) {
  18772. this.data.sort(compareFn);
  18773. };
  18774. SmartArray.prototype.reset = function () {
  18775. this.length = 0;
  18776. this._duplicateId++;
  18777. };
  18778. SmartArray.prototype.concat = function (array) {
  18779. if (array.length === 0) {
  18780. return;
  18781. }
  18782. if (this.length + array.length > this.data.length) {
  18783. this.data.length = (this.length + array.length) * 2;
  18784. }
  18785. for (var index = 0; index < array.length; index++) {
  18786. this.data[this.length++] = (array.data || array)[index];
  18787. }
  18788. };
  18789. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18790. if (array.length === 0) {
  18791. return;
  18792. }
  18793. if (this.length + array.length > this.data.length) {
  18794. this.data.length = (this.length + array.length) * 2;
  18795. }
  18796. for (var index = 0; index < array.length; index++) {
  18797. var item = (array.data || array)[index];
  18798. this.pushNoDuplicate(item);
  18799. }
  18800. };
  18801. SmartArray.prototype.indexOf = function (value) {
  18802. var position = this.data.indexOf(value);
  18803. if (position >= this.length) {
  18804. return -1;
  18805. }
  18806. return position;
  18807. };
  18808. SmartArray._GlobalId = 0;
  18809. return SmartArray;
  18810. })();
  18811. BABYLON.SmartArray = SmartArray;
  18812. })(BABYLON || (BABYLON = {}));
  18813. var BABYLON;
  18814. (function (BABYLON) {
  18815. var CannonJSPlugin = (function () {
  18816. function CannonJSPlugin() {
  18817. this._registeredMeshes = [];
  18818. this._physicsMaterials = [];
  18819. this.updateBodyPosition = function (mesh) {
  18820. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18821. var registeredMesh = this._registeredMeshes[index];
  18822. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18823. var body = registeredMesh.body;
  18824. var center = mesh.getBoundingInfo().boundingBox.center;
  18825. body.position.set(center.x, center.z, center.y);
  18826. body.quaternion.x = mesh.rotationQuaternion.x;
  18827. body.quaternion.z = mesh.rotationQuaternion.y;
  18828. body.quaternion.y = mesh.rotationQuaternion.z;
  18829. body.quaternion.w = -mesh.rotationQuaternion.w;
  18830. return;
  18831. }
  18832. }
  18833. };
  18834. }
  18835. CannonJSPlugin.prototype.initialize = function (iterations) {
  18836. if (typeof iterations === "undefined") { iterations = 10; }
  18837. this._world = new CANNON.World();
  18838. this._world.broadphase = new CANNON.NaiveBroadphase();
  18839. this._world.solver.iterations = iterations;
  18840. };
  18841. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18842. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18843. };
  18844. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18845. this._world.step(delta);
  18846. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18847. var registeredMesh = this._registeredMeshes[index];
  18848. if (registeredMesh.isChild) {
  18849. continue;
  18850. }
  18851. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18852. var deltaPos = registeredMesh.delta;
  18853. if (deltaPos) {
  18854. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18855. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18856. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18857. } else {
  18858. registeredMesh.mesh.position.x = bodyX;
  18859. registeredMesh.mesh.position.y = bodyZ;
  18860. registeredMesh.mesh.position.z = bodyY;
  18861. }
  18862. if (!registeredMesh.mesh.rotationQuaternion) {
  18863. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18864. }
  18865. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18866. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18867. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18868. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18869. }
  18870. };
  18871. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18872. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18873. };
  18874. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18875. this.unregisterMesh(mesh);
  18876. mesh.computeWorldMatrix(true);
  18877. switch (impostor) {
  18878. case BABYLON.PhysicsEngine.SphereImpostor:
  18879. var bbox = mesh.getBoundingInfo().boundingBox;
  18880. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18881. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18882. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18883. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18884. case BABYLON.PhysicsEngine.BoxImpostor:
  18885. bbox = mesh.getBoundingInfo().boundingBox;
  18886. var min = bbox.minimumWorld;
  18887. var max = bbox.maximumWorld;
  18888. var box = max.subtract(min).scale(0.5);
  18889. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18890. case BABYLON.PhysicsEngine.PlaneImpostor:
  18891. return this._createPlane(mesh, options);
  18892. case BABYLON.PhysicsEngine.MeshImpostor:
  18893. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18894. var rawFaces = mesh.getIndices();
  18895. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18896. }
  18897. return null;
  18898. };
  18899. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18900. var shape = new CANNON.Sphere(radius);
  18901. if (!options) {
  18902. return shape;
  18903. }
  18904. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18905. };
  18906. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18907. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18908. if (!options) {
  18909. return shape;
  18910. }
  18911. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18912. };
  18913. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18914. var shape = new CANNON.Plane();
  18915. if (!options) {
  18916. return shape;
  18917. }
  18918. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18919. };
  18920. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18921. var verts = [], faces = [];
  18922. mesh.computeWorldMatrix(true);
  18923. for (var i = 0; i < rawVerts.length; i += 3) {
  18924. var transformed = BABYLON.Vector3.Zero();
  18925. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18926. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18927. }
  18928. for (var j = 0; j < rawFaces.length; j += 3) {
  18929. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18930. }
  18931. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18932. if (!options) {
  18933. return shape;
  18934. }
  18935. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18936. };
  18937. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18938. var index;
  18939. var mat;
  18940. for (index = 0; index < this._physicsMaterials.length; index++) {
  18941. mat = this._physicsMaterials[index];
  18942. if (mat.friction === friction && mat.restitution === restitution) {
  18943. return mat;
  18944. }
  18945. }
  18946. var currentMat = new CANNON.Material();
  18947. currentMat.friction = friction;
  18948. currentMat.restitution = restitution;
  18949. this._physicsMaterials.push(currentMat);
  18950. for (index = 0; index < this._physicsMaterials.length; index++) {
  18951. mat = this._physicsMaterials[index];
  18952. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18953. contactMaterial.contactEquationStiffness = 1e10;
  18954. contactMaterial.contactEquationRegularizationTime = 10;
  18955. this._world.addContactMaterial(contactMaterial);
  18956. }
  18957. return currentMat;
  18958. };
  18959. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18960. var initialRotation = null;
  18961. if (mesh.rotationQuaternion) {
  18962. initialRotation = mesh.rotationQuaternion.clone();
  18963. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18964. }
  18965. var bbox = mesh.getBoundingInfo().boundingBox;
  18966. var deltaPosition = mesh.position.subtract(bbox.center);
  18967. var material = this._addMaterial(friction, restitution);
  18968. var body = new CANNON.RigidBody(mass, shape, material);
  18969. if (initialRotation) {
  18970. body.quaternion.x = initialRotation.x;
  18971. body.quaternion.z = initialRotation.y;
  18972. body.quaternion.y = initialRotation.z;
  18973. body.quaternion.w = -initialRotation.w;
  18974. }
  18975. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18976. this._world.add(body);
  18977. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18978. return body;
  18979. };
  18980. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18981. var compoundShape = new CANNON.Compound();
  18982. for (var index = 0; index < parts.length; index++) {
  18983. var mesh = parts[index].mesh;
  18984. var shape = this.registerMesh(mesh, parts[index].impostor);
  18985. if (index == 0) {
  18986. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18987. } else {
  18988. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18989. }
  18990. }
  18991. var initialMesh = parts[0].mesh;
  18992. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18993. body.parts = parts;
  18994. return body;
  18995. };
  18996. CannonJSPlugin.prototype._unbindBody = function (body) {
  18997. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18998. var registeredMesh = this._registeredMeshes[index];
  18999. if (registeredMesh.body === body) {
  19000. registeredMesh.body = null;
  19001. registeredMesh.delta = 0;
  19002. }
  19003. }
  19004. };
  19005. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19006. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19007. var registeredMesh = this._registeredMeshes[index];
  19008. if (registeredMesh.mesh === mesh) {
  19009. if (registeredMesh.body) {
  19010. this._world.remove(registeredMesh.body);
  19011. this._unbindBody(registeredMesh.body);
  19012. }
  19013. this._registeredMeshes.splice(index, 1);
  19014. return;
  19015. }
  19016. }
  19017. };
  19018. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19019. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19020. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19021. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19022. var registeredMesh = this._registeredMeshes[index];
  19023. if (registeredMesh.mesh === mesh) {
  19024. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19025. return;
  19026. }
  19027. }
  19028. };
  19029. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19030. var body1 = null, body2 = null;
  19031. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19032. var registeredMesh = this._registeredMeshes[index];
  19033. if (registeredMesh.mesh === mesh1) {
  19034. body1 = registeredMesh.body;
  19035. } else if (registeredMesh.mesh === mesh2) {
  19036. body2 = registeredMesh.body;
  19037. }
  19038. }
  19039. if (!body1 || !body2) {
  19040. return false;
  19041. }
  19042. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  19043. this._world.addConstraint(constraint);
  19044. return true;
  19045. };
  19046. CannonJSPlugin.prototype.dispose = function () {
  19047. while (this._registeredMeshes.length) {
  19048. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19049. }
  19050. };
  19051. CannonJSPlugin.prototype.isSupported = function () {
  19052. return window.CANNON !== undefined;
  19053. };
  19054. return CannonJSPlugin;
  19055. })();
  19056. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19057. })(BABYLON || (BABYLON = {}));
  19058. var __extends = this.__extends || function (d, b) {
  19059. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19060. function __() { this.constructor = d; }
  19061. __.prototype = b.prototype;
  19062. d.prototype = new __();
  19063. };
  19064. var BABYLON;
  19065. (function (BABYLON) {
  19066. var Condition = (function () {
  19067. function Condition(actionManager) {
  19068. this._actionManager = actionManager;
  19069. }
  19070. Condition.prototype.isValid = function () {
  19071. return true;
  19072. };
  19073. Condition.prototype._getProperty = function (propertyPath) {
  19074. return this._actionManager._getProperty(propertyPath);
  19075. };
  19076. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19077. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19078. };
  19079. return Condition;
  19080. })();
  19081. BABYLON.Condition = Condition;
  19082. var ValueCondition = (function (_super) {
  19083. __extends(ValueCondition, _super);
  19084. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19085. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19086. _super.call(this, actionManager);
  19087. this.propertyPath = propertyPath;
  19088. this.value = value;
  19089. this.operator = operator;
  19090. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19091. this._property = this._getProperty(this.propertyPath);
  19092. }
  19093. Object.defineProperty(ValueCondition, "IsEqual", {
  19094. get: function () {
  19095. return ValueCondition._IsEqual;
  19096. },
  19097. enumerable: true,
  19098. configurable: true
  19099. });
  19100. Object.defineProperty(ValueCondition, "IsDifferent", {
  19101. get: function () {
  19102. return ValueCondition._IsDifferent;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Object.defineProperty(ValueCondition, "IsGreater", {
  19108. get: function () {
  19109. return ValueCondition._IsGreater;
  19110. },
  19111. enumerable: true,
  19112. configurable: true
  19113. });
  19114. Object.defineProperty(ValueCondition, "IsLesser", {
  19115. get: function () {
  19116. return ValueCondition._IsLesser;
  19117. },
  19118. enumerable: true,
  19119. configurable: true
  19120. });
  19121. ValueCondition.prototype.isValid = function () {
  19122. switch (this.operator) {
  19123. case ValueCondition.IsGreater:
  19124. return this._target[this._property] > this.value;
  19125. case ValueCondition.IsLesser:
  19126. return this._target[this._property] < this.value;
  19127. case ValueCondition.IsEqual:
  19128. case ValueCondition.IsDifferent:
  19129. var check;
  19130. if (this.value.equals) {
  19131. check = this.value.equals(this._target[this._property]);
  19132. } else {
  19133. check = this.value === this._target[this._property];
  19134. }
  19135. return this.operator === ValueCondition.IsEqual ? check : !check;
  19136. }
  19137. return false;
  19138. };
  19139. ValueCondition._IsEqual = 0;
  19140. ValueCondition._IsDifferent = 1;
  19141. ValueCondition._IsGreater = 2;
  19142. ValueCondition._IsLesser = 3;
  19143. return ValueCondition;
  19144. })(Condition);
  19145. BABYLON.ValueCondition = ValueCondition;
  19146. var PredicateCondition = (function (_super) {
  19147. __extends(PredicateCondition, _super);
  19148. function PredicateCondition(actionManager, predicate) {
  19149. _super.call(this, actionManager);
  19150. this.predicate = predicate;
  19151. }
  19152. PredicateCondition.prototype.isValid = function () {
  19153. return this.predicate();
  19154. };
  19155. return PredicateCondition;
  19156. })(Condition);
  19157. BABYLON.PredicateCondition = PredicateCondition;
  19158. var StateCondition = (function (_super) {
  19159. __extends(StateCondition, _super);
  19160. function StateCondition(actionManager, target, value) {
  19161. _super.call(this, actionManager);
  19162. this.value = value;
  19163. this._target = target;
  19164. }
  19165. StateCondition.prototype.isValid = function () {
  19166. return this._target.state === this.value;
  19167. };
  19168. return StateCondition;
  19169. })(Condition);
  19170. BABYLON.StateCondition = StateCondition;
  19171. })(BABYLON || (BABYLON = {}));
  19172. var BABYLON;
  19173. (function (BABYLON) {
  19174. var Action = (function () {
  19175. function Action(triggerOptions, condition) {
  19176. this.triggerOptions = triggerOptions;
  19177. if (triggerOptions.parameter) {
  19178. this.trigger = triggerOptions.trigger;
  19179. this._triggerParameter = triggerOptions.parameter;
  19180. } else {
  19181. this.trigger = triggerOptions;
  19182. }
  19183. this._nextActiveAction = this;
  19184. this._condition = condition;
  19185. }
  19186. Action.prototype._prepare = function () {
  19187. };
  19188. Action.prototype.getTriggerParameter = function () {
  19189. return this._triggerParameter;
  19190. };
  19191. Action.prototype._executeCurrent = function (evt) {
  19192. if (this._condition) {
  19193. var currentRenderId = this._actionManager.getScene().getRenderId();
  19194. if (this._condition._evaluationId === currentRenderId) {
  19195. if (!this._condition._currentResult) {
  19196. return;
  19197. }
  19198. } else {
  19199. this._condition._evaluationId = currentRenderId;
  19200. if (!this._condition.isValid()) {
  19201. this._condition._currentResult = false;
  19202. return;
  19203. }
  19204. this._condition._currentResult = true;
  19205. }
  19206. }
  19207. this._nextActiveAction.execute(evt);
  19208. if (this._nextActiveAction._child) {
  19209. if (!this._nextActiveAction._child._actionManager) {
  19210. this._nextActiveAction._child._actionManager = this._actionManager;
  19211. }
  19212. this._nextActiveAction = this._nextActiveAction._child;
  19213. } else {
  19214. this._nextActiveAction = this;
  19215. }
  19216. };
  19217. Action.prototype.execute = function (evt) {
  19218. };
  19219. Action.prototype.then = function (action) {
  19220. this._child = action;
  19221. action._actionManager = this._actionManager;
  19222. action._prepare();
  19223. return action;
  19224. };
  19225. Action.prototype._getProperty = function (propertyPath) {
  19226. return this._actionManager._getProperty(propertyPath);
  19227. };
  19228. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19229. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19230. };
  19231. return Action;
  19232. })();
  19233. BABYLON.Action = Action;
  19234. })(BABYLON || (BABYLON = {}));
  19235. var BABYLON;
  19236. (function (BABYLON) {
  19237. var ActionEvent = (function () {
  19238. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19239. this.source = source;
  19240. this.pointerX = pointerX;
  19241. this.pointerY = pointerY;
  19242. this.meshUnderPointer = meshUnderPointer;
  19243. this.sourceEvent = sourceEvent;
  19244. }
  19245. ActionEvent.CreateNew = function (source) {
  19246. var scene = source.getScene();
  19247. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19248. };
  19249. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19250. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19251. };
  19252. return ActionEvent;
  19253. })();
  19254. BABYLON.ActionEvent = ActionEvent;
  19255. var ActionManager = (function () {
  19256. function ActionManager(scene) {
  19257. this.actions = new Array();
  19258. this._scene = scene;
  19259. scene._actionManagers.push(this);
  19260. }
  19261. Object.defineProperty(ActionManager, "NothingTrigger", {
  19262. get: function () {
  19263. return ActionManager._NothingTrigger;
  19264. },
  19265. enumerable: true,
  19266. configurable: true
  19267. });
  19268. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19269. get: function () {
  19270. return ActionManager._OnPickTrigger;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19276. get: function () {
  19277. return ActionManager._OnLeftPickTrigger;
  19278. },
  19279. enumerable: true,
  19280. configurable: true
  19281. });
  19282. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19283. get: function () {
  19284. return ActionManager._OnRightPickTrigger;
  19285. },
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19290. get: function () {
  19291. return ActionManager._OnCenterPickTrigger;
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19297. get: function () {
  19298. return ActionManager._OnPointerOverTrigger;
  19299. },
  19300. enumerable: true,
  19301. configurable: true
  19302. });
  19303. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19304. get: function () {
  19305. return ActionManager._OnPointerOutTrigger;
  19306. },
  19307. enumerable: true,
  19308. configurable: true
  19309. });
  19310. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19311. get: function () {
  19312. return ActionManager._OnEveryFrameTrigger;
  19313. },
  19314. enumerable: true,
  19315. configurable: true
  19316. });
  19317. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19318. get: function () {
  19319. return ActionManager._OnIntersectionEnterTrigger;
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19325. get: function () {
  19326. return ActionManager._OnIntersectionExitTrigger;
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19332. get: function () {
  19333. return ActionManager._OnKeyDownTrigger;
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19339. get: function () {
  19340. return ActionManager._OnKeyUpTrigger;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. ActionManager.prototype.dispose = function () {
  19346. var index = this._scene._actionManagers.indexOf(this);
  19347. if (index > -1) {
  19348. this._scene._actionManagers.splice(index, 1);
  19349. }
  19350. };
  19351. ActionManager.prototype.getScene = function () {
  19352. return this._scene;
  19353. };
  19354. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19355. for (var index = 0; index < this.actions.length; index++) {
  19356. var action = this.actions[index];
  19357. if (triggers.indexOf(action.trigger) > -1) {
  19358. return true;
  19359. }
  19360. }
  19361. return false;
  19362. };
  19363. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19364. get: function () {
  19365. for (var index = 0; index < this.actions.length; index++) {
  19366. var action = this.actions[index];
  19367. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19368. return true;
  19369. }
  19370. }
  19371. return false;
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19377. get: function () {
  19378. for (var index = 0; index < this.actions.length; index++) {
  19379. var action = this.actions[index];
  19380. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19381. return true;
  19382. }
  19383. }
  19384. return false;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. ActionManager.prototype.registerAction = function (action) {
  19390. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19391. if (this.getScene().actionManager !== this) {
  19392. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19393. return null;
  19394. }
  19395. }
  19396. this.actions.push(action);
  19397. action._actionManager = this;
  19398. action._prepare();
  19399. return action;
  19400. };
  19401. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19402. for (var index = 0; index < this.actions.length; index++) {
  19403. var action = this.actions[index];
  19404. if (action.trigger === trigger) {
  19405. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19406. var parameter = action.getTriggerParameter();
  19407. if (parameter) {
  19408. if (evt.sourceEvent.key !== parameter) {
  19409. continue;
  19410. }
  19411. }
  19412. }
  19413. action._executeCurrent(evt);
  19414. }
  19415. }
  19416. };
  19417. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19418. var properties = propertyPath.split(".");
  19419. for (var index = 0; index < properties.length - 1; index++) {
  19420. target = target[properties[index]];
  19421. }
  19422. return target;
  19423. };
  19424. ActionManager.prototype._getProperty = function (propertyPath) {
  19425. var properties = propertyPath.split(".");
  19426. return properties[properties.length - 1];
  19427. };
  19428. ActionManager._NothingTrigger = 0;
  19429. ActionManager._OnPickTrigger = 1;
  19430. ActionManager._OnLeftPickTrigger = 2;
  19431. ActionManager._OnRightPickTrigger = 3;
  19432. ActionManager._OnCenterPickTrigger = 4;
  19433. ActionManager._OnPointerOverTrigger = 5;
  19434. ActionManager._OnPointerOutTrigger = 6;
  19435. ActionManager._OnEveryFrameTrigger = 7;
  19436. ActionManager._OnIntersectionEnterTrigger = 8;
  19437. ActionManager._OnIntersectionExitTrigger = 9;
  19438. ActionManager._OnKeyDownTrigger = 10;
  19439. ActionManager._OnKeyUpTrigger = 11;
  19440. return ActionManager;
  19441. })();
  19442. BABYLON.ActionManager = ActionManager;
  19443. })(BABYLON || (BABYLON = {}));
  19444. var __extends = this.__extends || function (d, b) {
  19445. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19446. function __() { this.constructor = d; }
  19447. __.prototype = b.prototype;
  19448. d.prototype = new __();
  19449. };
  19450. var BABYLON;
  19451. (function (BABYLON) {
  19452. var InterpolateValueAction = (function (_super) {
  19453. __extends(InterpolateValueAction, _super);
  19454. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19455. if (typeof duration === "undefined") { duration = 1000; }
  19456. _super.call(this, triggerOptions, condition);
  19457. this.propertyPath = propertyPath;
  19458. this.value = value;
  19459. this.duration = duration;
  19460. this.stopOtherAnimations = stopOtherAnimations;
  19461. this._target = target;
  19462. }
  19463. InterpolateValueAction.prototype._prepare = function () {
  19464. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19465. this._property = this._getProperty(this.propertyPath);
  19466. };
  19467. InterpolateValueAction.prototype.execute = function () {
  19468. var scene = this._actionManager.getScene();
  19469. var keys = [
  19470. {
  19471. frame: 0,
  19472. value: this._target[this._property]
  19473. }, {
  19474. frame: 100,
  19475. value: this.value
  19476. }
  19477. ];
  19478. var dataType;
  19479. if (typeof this.value === "number") {
  19480. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19481. } else if (this.value instanceof BABYLON.Color3) {
  19482. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19483. } else if (this.value instanceof BABYLON.Vector3) {
  19484. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19485. } else if (this.value instanceof BABYLON.Matrix) {
  19486. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19487. } else if (this.value instanceof BABYLON.Quaternion) {
  19488. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19489. } else {
  19490. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19491. return;
  19492. }
  19493. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19494. animation.setKeys(keys);
  19495. if (this.stopOtherAnimations) {
  19496. scene.stopAnimation(this._target);
  19497. }
  19498. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19499. };
  19500. return InterpolateValueAction;
  19501. })(BABYLON.Action);
  19502. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19503. })(BABYLON || (BABYLON = {}));
  19504. var __extends = this.__extends || function (d, b) {
  19505. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19506. function __() { this.constructor = d; }
  19507. __.prototype = b.prototype;
  19508. d.prototype = new __();
  19509. };
  19510. var BABYLON;
  19511. (function (BABYLON) {
  19512. var SwitchBooleanAction = (function (_super) {
  19513. __extends(SwitchBooleanAction, _super);
  19514. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19515. _super.call(this, triggerOptions, condition);
  19516. this.propertyPath = propertyPath;
  19517. this._target = target;
  19518. }
  19519. SwitchBooleanAction.prototype._prepare = function () {
  19520. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19521. this._property = this._getProperty(this.propertyPath);
  19522. };
  19523. SwitchBooleanAction.prototype.execute = function () {
  19524. this._target[this._property] = !this._target[this._property];
  19525. };
  19526. return SwitchBooleanAction;
  19527. })(BABYLON.Action);
  19528. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19529. var SetStateAction = (function (_super) {
  19530. __extends(SetStateAction, _super);
  19531. function SetStateAction(triggerOptions, target, value, condition) {
  19532. _super.call(this, triggerOptions, condition);
  19533. this.value = value;
  19534. this._target = target;
  19535. }
  19536. SetStateAction.prototype.execute = function () {
  19537. this._target.state = this.value;
  19538. };
  19539. return SetStateAction;
  19540. })(BABYLON.Action);
  19541. BABYLON.SetStateAction = SetStateAction;
  19542. var SetValueAction = (function (_super) {
  19543. __extends(SetValueAction, _super);
  19544. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19545. _super.call(this, triggerOptions, condition);
  19546. this.propertyPath = propertyPath;
  19547. this.value = value;
  19548. this._target = target;
  19549. }
  19550. SetValueAction.prototype._prepare = function () {
  19551. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19552. this._property = this._getProperty(this.propertyPath);
  19553. };
  19554. SetValueAction.prototype.execute = function () {
  19555. this._target[this._property] = this.value;
  19556. };
  19557. return SetValueAction;
  19558. })(BABYLON.Action);
  19559. BABYLON.SetValueAction = SetValueAction;
  19560. var IncrementValueAction = (function (_super) {
  19561. __extends(IncrementValueAction, _super);
  19562. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19563. _super.call(this, triggerOptions, condition);
  19564. this.propertyPath = propertyPath;
  19565. this.value = value;
  19566. this._target = target;
  19567. }
  19568. IncrementValueAction.prototype._prepare = function () {
  19569. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19570. this._property = this._getProperty(this.propertyPath);
  19571. if (typeof this._target[this._property] !== "number") {
  19572. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19573. }
  19574. };
  19575. IncrementValueAction.prototype.execute = function () {
  19576. this._target[this._property] += this.value;
  19577. };
  19578. return IncrementValueAction;
  19579. })(BABYLON.Action);
  19580. BABYLON.IncrementValueAction = IncrementValueAction;
  19581. var PlayAnimationAction = (function (_super) {
  19582. __extends(PlayAnimationAction, _super);
  19583. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19584. _super.call(this, triggerOptions, condition);
  19585. this.from = from;
  19586. this.to = to;
  19587. this.loop = loop;
  19588. this._target = target;
  19589. }
  19590. PlayAnimationAction.prototype._prepare = function () {
  19591. };
  19592. PlayAnimationAction.prototype.execute = function () {
  19593. var scene = this._actionManager.getScene();
  19594. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19595. };
  19596. return PlayAnimationAction;
  19597. })(BABYLON.Action);
  19598. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19599. var StopAnimationAction = (function (_super) {
  19600. __extends(StopAnimationAction, _super);
  19601. function StopAnimationAction(triggerOptions, target, condition) {
  19602. _super.call(this, triggerOptions, condition);
  19603. this._target = target;
  19604. }
  19605. StopAnimationAction.prototype._prepare = function () {
  19606. };
  19607. StopAnimationAction.prototype.execute = function () {
  19608. var scene = this._actionManager.getScene();
  19609. scene.stopAnimation(this._target);
  19610. };
  19611. return StopAnimationAction;
  19612. })(BABYLON.Action);
  19613. BABYLON.StopAnimationAction = StopAnimationAction;
  19614. var DoNothingAction = (function (_super) {
  19615. __extends(DoNothingAction, _super);
  19616. function DoNothingAction(triggerOptions, condition) {
  19617. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19618. _super.call(this, triggerOptions, condition);
  19619. }
  19620. DoNothingAction.prototype.execute = function () {
  19621. };
  19622. return DoNothingAction;
  19623. })(BABYLON.Action);
  19624. BABYLON.DoNothingAction = DoNothingAction;
  19625. var CombineAction = (function (_super) {
  19626. __extends(CombineAction, _super);
  19627. function CombineAction(triggerOptions, children, condition) {
  19628. _super.call(this, triggerOptions, condition);
  19629. this.children = children;
  19630. }
  19631. CombineAction.prototype._prepare = function () {
  19632. for (var index = 0; index < this.children.length; index++) {
  19633. this.children[index]._actionManager = this._actionManager;
  19634. this.children[index]._prepare();
  19635. }
  19636. };
  19637. CombineAction.prototype.execute = function (evt) {
  19638. for (var index = 0; index < this.children.length; index++) {
  19639. this.children[index].execute(evt);
  19640. }
  19641. };
  19642. return CombineAction;
  19643. })(BABYLON.Action);
  19644. BABYLON.CombineAction = CombineAction;
  19645. var ExecuteCodeAction = (function (_super) {
  19646. __extends(ExecuteCodeAction, _super);
  19647. function ExecuteCodeAction(triggerOptions, func, condition) {
  19648. _super.call(this, triggerOptions, condition);
  19649. this.func = func;
  19650. }
  19651. ExecuteCodeAction.prototype.execute = function (evt) {
  19652. this.func(evt);
  19653. };
  19654. return ExecuteCodeAction;
  19655. })(BABYLON.Action);
  19656. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19657. var SetParentAction = (function (_super) {
  19658. __extends(SetParentAction, _super);
  19659. function SetParentAction(triggerOptions, target, parent, condition) {
  19660. _super.call(this, triggerOptions, condition);
  19661. this._target = target;
  19662. this._parent = parent;
  19663. }
  19664. SetParentAction.prototype._prepare = function () {
  19665. };
  19666. SetParentAction.prototype.execute = function () {
  19667. if (this._target.parent === this._parent) {
  19668. return;
  19669. }
  19670. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19671. invertParentWorldMatrix.invert();
  19672. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19673. this._target.parent = this._parent;
  19674. };
  19675. return SetParentAction;
  19676. })(BABYLON.Action);
  19677. BABYLON.SetParentAction = SetParentAction;
  19678. })(BABYLON || (BABYLON = {}));
  19679. var __extends = this.__extends || function (d, b) {
  19680. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19681. function __() { this.constructor = d; }
  19682. __.prototype = b.prototype;
  19683. d.prototype = new __();
  19684. };
  19685. var BABYLON;
  19686. (function (BABYLON) {
  19687. var Geometry = (function () {
  19688. function Geometry(id, scene, vertexData, updatable, mesh) {
  19689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19690. this._totalVertices = 0;
  19691. this._indices = [];
  19692. this.id = id;
  19693. this._engine = scene.getEngine();
  19694. this._meshes = [];
  19695. this._scene = scene;
  19696. if (vertexData) {
  19697. this.setAllVerticesData(vertexData, updatable);
  19698. } else {
  19699. this._totalVertices = 0;
  19700. this._indices = [];
  19701. }
  19702. if (mesh) {
  19703. this.applyToMesh(mesh);
  19704. }
  19705. }
  19706. Geometry.prototype.getScene = function () {
  19707. return this._scene;
  19708. };
  19709. Geometry.prototype.getEngine = function () {
  19710. return this._engine;
  19711. };
  19712. Geometry.prototype.isReady = function () {
  19713. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19714. };
  19715. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19716. vertexData.applyToGeometry(this, updatable);
  19717. };
  19718. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19719. this._vertexBuffers = this._vertexBuffers || {};
  19720. if (this._vertexBuffers[kind]) {
  19721. this._vertexBuffers[kind].dispose();
  19722. }
  19723. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19724. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19725. var stride = this._vertexBuffers[kind].getStrideSize();
  19726. this._totalVertices = data.length / stride;
  19727. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19728. var meshes = this._meshes;
  19729. var numOfMeshes = meshes.length;
  19730. for (var index = 0; index < numOfMeshes; index++) {
  19731. var mesh = meshes[index];
  19732. mesh._resetPointsArrayCache();
  19733. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19734. mesh._createGlobalSubMesh();
  19735. mesh.computeWorldMatrix(true);
  19736. }
  19737. }
  19738. };
  19739. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19740. var vertexBuffer = this.getVertexBuffer(kind);
  19741. if (!vertexBuffer) {
  19742. return;
  19743. }
  19744. vertexBuffer.updateDirectly(data);
  19745. };
  19746. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19747. var vertexBuffer = this.getVertexBuffer(kind);
  19748. if (!vertexBuffer) {
  19749. return;
  19750. }
  19751. vertexBuffer.update(data);
  19752. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19753. var extend;
  19754. if (updateExtends) {
  19755. var stride = vertexBuffer.getStrideSize();
  19756. this._totalVertices = data.length / stride;
  19757. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19758. }
  19759. var meshes = this._meshes;
  19760. var numOfMeshes = meshes.length;
  19761. for (var index = 0; index < numOfMeshes; index++) {
  19762. var mesh = meshes[index];
  19763. mesh._resetPointsArrayCache();
  19764. if (updateExtends) {
  19765. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19766. }
  19767. }
  19768. }
  19769. };
  19770. Geometry.prototype.getTotalVertices = function () {
  19771. if (!this.isReady()) {
  19772. return 0;
  19773. }
  19774. return this._totalVertices;
  19775. };
  19776. Geometry.prototype.getVerticesData = function (kind) {
  19777. var vertexBuffer = this.getVertexBuffer(kind);
  19778. if (!vertexBuffer) {
  19779. return null;
  19780. }
  19781. return vertexBuffer.getData();
  19782. };
  19783. Geometry.prototype.getVertexBuffer = function (kind) {
  19784. if (!this.isReady()) {
  19785. return null;
  19786. }
  19787. return this._vertexBuffers[kind];
  19788. };
  19789. Geometry.prototype.getVertexBuffers = function () {
  19790. if (!this.isReady()) {
  19791. return null;
  19792. }
  19793. return this._vertexBuffers;
  19794. };
  19795. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19796. if (!this._vertexBuffers) {
  19797. if (this._delayInfo) {
  19798. return this._delayInfo.indexOf(kind) !== -1;
  19799. }
  19800. return false;
  19801. }
  19802. return this._vertexBuffers[kind] !== undefined;
  19803. };
  19804. Geometry.prototype.getVerticesDataKinds = function () {
  19805. var result = [];
  19806. if (!this._vertexBuffers && this._delayInfo) {
  19807. for (var kind in this._delayInfo) {
  19808. result.push(kind);
  19809. }
  19810. } else {
  19811. for (kind in this._vertexBuffers) {
  19812. result.push(kind);
  19813. }
  19814. }
  19815. return result;
  19816. };
  19817. Geometry.prototype.setIndices = function (indices) {
  19818. if (this._indexBuffer) {
  19819. this._engine._releaseBuffer(this._indexBuffer);
  19820. }
  19821. this._indices = indices;
  19822. if (this._meshes.length !== 0 && this._indices) {
  19823. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19824. }
  19825. var meshes = this._meshes;
  19826. var numOfMeshes = meshes.length;
  19827. for (var index = 0; index < numOfMeshes; index++) {
  19828. meshes[index]._createGlobalSubMesh();
  19829. }
  19830. };
  19831. Geometry.prototype.getTotalIndices = function () {
  19832. if (!this.isReady()) {
  19833. return 0;
  19834. }
  19835. return this._indices.length;
  19836. };
  19837. Geometry.prototype.getIndices = function () {
  19838. if (!this.isReady()) {
  19839. return null;
  19840. }
  19841. return this._indices;
  19842. };
  19843. Geometry.prototype.getIndexBuffer = function () {
  19844. if (!this.isReady()) {
  19845. return null;
  19846. }
  19847. return this._indexBuffer;
  19848. };
  19849. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19850. var meshes = this._meshes;
  19851. var index = meshes.indexOf(mesh);
  19852. if (index === -1) {
  19853. return;
  19854. }
  19855. for (var kind in this._vertexBuffers) {
  19856. this._vertexBuffers[kind].dispose();
  19857. }
  19858. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19859. this._indexBuffer = null;
  19860. }
  19861. meshes.splice(index, 1);
  19862. mesh._geometry = null;
  19863. if (meshes.length == 0 && shouldDispose) {
  19864. this.dispose();
  19865. }
  19866. };
  19867. Geometry.prototype.applyToMesh = function (mesh) {
  19868. if (mesh._geometry === this) {
  19869. return;
  19870. }
  19871. var previousGeometry = mesh._geometry;
  19872. if (previousGeometry) {
  19873. previousGeometry.releaseForMesh(mesh);
  19874. }
  19875. var meshes = this._meshes;
  19876. mesh._geometry = this;
  19877. this._scene.pushGeometry(this);
  19878. meshes.push(mesh);
  19879. if (this.isReady()) {
  19880. this._applyToMesh(mesh);
  19881. } else {
  19882. mesh._boundingInfo = this._boundingInfo;
  19883. }
  19884. };
  19885. Geometry.prototype._applyToMesh = function (mesh) {
  19886. var numOfMeshes = this._meshes.length;
  19887. for (var kind in this._vertexBuffers) {
  19888. if (numOfMeshes === 1) {
  19889. this._vertexBuffers[kind].create();
  19890. }
  19891. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19892. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19893. mesh._resetPointsArrayCache();
  19894. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19895. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19896. mesh._createGlobalSubMesh();
  19897. }
  19898. }
  19899. if (numOfMeshes === 1 && this._indices) {
  19900. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19901. }
  19902. if (this._indexBuffer) {
  19903. this._indexBuffer.references = numOfMeshes;
  19904. }
  19905. };
  19906. Geometry.prototype.load = function (scene, onLoaded) {
  19907. var _this = this;
  19908. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19909. return;
  19910. }
  19911. if (this.isReady()) {
  19912. if (onLoaded) {
  19913. onLoaded();
  19914. }
  19915. return;
  19916. }
  19917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19918. scene._addPendingData(this);
  19919. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19920. _this._delayLoadingFunction(JSON.parse(data), _this);
  19921. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19922. _this._delayInfo = [];
  19923. scene._removePendingData(_this);
  19924. var meshes = _this._meshes;
  19925. var numOfMeshes = meshes.length;
  19926. for (var index = 0; index < numOfMeshes; index++) {
  19927. _this._applyToMesh(meshes[index]);
  19928. }
  19929. if (onLoaded) {
  19930. onLoaded();
  19931. }
  19932. }, function () {
  19933. }, scene.database);
  19934. };
  19935. Geometry.prototype.dispose = function () {
  19936. var meshes = this._meshes;
  19937. var numOfMeshes = meshes.length;
  19938. for (var index = 0; index < numOfMeshes; index++) {
  19939. this.releaseForMesh(meshes[index]);
  19940. }
  19941. this._meshes = [];
  19942. for (var kind in this._vertexBuffers) {
  19943. this._vertexBuffers[kind].dispose();
  19944. }
  19945. this._vertexBuffers = [];
  19946. this._totalVertices = 0;
  19947. if (this._indexBuffer) {
  19948. this._engine._releaseBuffer(this._indexBuffer);
  19949. }
  19950. this._indexBuffer = null;
  19951. this._indices = [];
  19952. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19953. this.delayLoadingFile = null;
  19954. this._delayLoadingFunction = null;
  19955. this._delayInfo = [];
  19956. this._boundingInfo = null;
  19957. var geometries = this._scene.getGeometries();
  19958. index = geometries.indexOf(this);
  19959. if (index > -1) {
  19960. geometries.splice(index, 1);
  19961. }
  19962. };
  19963. Geometry.prototype.copy = function (id) {
  19964. var vertexData = new BABYLON.VertexData();
  19965. vertexData.indices = [];
  19966. var indices = this.getIndices();
  19967. for (var index = 0; index < indices.length; index++) {
  19968. vertexData.indices.push(indices[index]);
  19969. }
  19970. var updatable = false;
  19971. var stopChecking = false;
  19972. for (var kind in this._vertexBuffers) {
  19973. vertexData.set(this.getVerticesData(kind), kind);
  19974. if (!stopChecking) {
  19975. updatable = this.getVertexBuffer(kind).isUpdatable();
  19976. stopChecking = !updatable;
  19977. }
  19978. }
  19979. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19980. geometry.delayLoadState = this.delayLoadState;
  19981. geometry.delayLoadingFile = this.delayLoadingFile;
  19982. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19983. for (kind in this._delayInfo) {
  19984. geometry._delayInfo = geometry._delayInfo || [];
  19985. geometry._delayInfo.push(kind);
  19986. }
  19987. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19988. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19989. return geometry;
  19990. };
  19991. Geometry.ExtractFromMesh = function (mesh, id) {
  19992. var geometry = mesh._geometry;
  19993. if (!geometry) {
  19994. return null;
  19995. }
  19996. return geometry.copy(id);
  19997. };
  19998. Geometry.RandomId = function () {
  19999. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20000. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20001. return v.toString(16);
  20002. });
  20003. };
  20004. return Geometry;
  20005. })();
  20006. BABYLON.Geometry = Geometry;
  20007. (function (Geometry) {
  20008. (function (Primitives) {
  20009. var _Primitive = (function (_super) {
  20010. __extends(_Primitive, _super);
  20011. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20012. this._beingRegenerated = true;
  20013. this._canBeRegenerated = canBeRegenerated;
  20014. _super.call(this, id, scene, vertexData, false, mesh);
  20015. this._beingRegenerated = false;
  20016. }
  20017. _Primitive.prototype.canBeRegenerated = function () {
  20018. return this._canBeRegenerated;
  20019. };
  20020. _Primitive.prototype.regenerate = function () {
  20021. if (!this._canBeRegenerated) {
  20022. return;
  20023. }
  20024. this._beingRegenerated = true;
  20025. this.setAllVerticesData(this._regenerateVertexData(), false);
  20026. this._beingRegenerated = false;
  20027. };
  20028. _Primitive.prototype.asNewGeometry = function (id) {
  20029. return _super.prototype.copy.call(this, id);
  20030. };
  20031. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20032. if (!this._beingRegenerated) {
  20033. return;
  20034. }
  20035. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20036. };
  20037. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20038. if (!this._beingRegenerated) {
  20039. return;
  20040. }
  20041. _super.prototype.setVerticesData.call(this, kind, data, false);
  20042. };
  20043. _Primitive.prototype._regenerateVertexData = function () {
  20044. throw new Error("Abstract method");
  20045. };
  20046. _Primitive.prototype.copy = function (id) {
  20047. throw new Error("Must be overriden in sub-classes.");
  20048. };
  20049. return _Primitive;
  20050. })(Geometry);
  20051. Primitives._Primitive = _Primitive;
  20052. var Box = (function (_super) {
  20053. __extends(Box, _super);
  20054. function Box(id, scene, size, canBeRegenerated, mesh) {
  20055. this.size = size;
  20056. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20057. }
  20058. Box.prototype._regenerateVertexData = function () {
  20059. return BABYLON.VertexData.CreateBox(this.size);
  20060. };
  20061. Box.prototype.copy = function (id) {
  20062. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20063. };
  20064. return Box;
  20065. })(_Primitive);
  20066. Primitives.Box = Box;
  20067. var Sphere = (function (_super) {
  20068. __extends(Sphere, _super);
  20069. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20070. this.segments = segments;
  20071. this.diameter = diameter;
  20072. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20073. }
  20074. Sphere.prototype._regenerateVertexData = function () {
  20075. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20076. };
  20077. Sphere.prototype.copy = function (id) {
  20078. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20079. };
  20080. return Sphere;
  20081. })(_Primitive);
  20082. Primitives.Sphere = Sphere;
  20083. var Cylinder = (function (_super) {
  20084. __extends(Cylinder, _super);
  20085. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20086. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20087. this.height = height;
  20088. this.diameterTop = diameterTop;
  20089. this.diameterBottom = diameterBottom;
  20090. this.tessellation = tessellation;
  20091. this.subdivisions = subdivisions;
  20092. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20093. }
  20094. Cylinder.prototype._regenerateVertexData = function () {
  20095. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20096. };
  20097. Cylinder.prototype.copy = function (id) {
  20098. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20099. };
  20100. return Cylinder;
  20101. })(_Primitive);
  20102. Primitives.Cylinder = Cylinder;
  20103. var Torus = (function (_super) {
  20104. __extends(Torus, _super);
  20105. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20106. this.diameter = diameter;
  20107. this.thickness = thickness;
  20108. this.tessellation = tessellation;
  20109. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20110. }
  20111. Torus.prototype._regenerateVertexData = function () {
  20112. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20113. };
  20114. Torus.prototype.copy = function (id) {
  20115. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20116. };
  20117. return Torus;
  20118. })(_Primitive);
  20119. Primitives.Torus = Torus;
  20120. var Ground = (function (_super) {
  20121. __extends(Ground, _super);
  20122. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20123. this.width = width;
  20124. this.height = height;
  20125. this.subdivisions = subdivisions;
  20126. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20127. }
  20128. Ground.prototype._regenerateVertexData = function () {
  20129. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20130. };
  20131. Ground.prototype.copy = function (id) {
  20132. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20133. };
  20134. return Ground;
  20135. })(_Primitive);
  20136. Primitives.Ground = Ground;
  20137. var TiledGround = (function (_super) {
  20138. __extends(TiledGround, _super);
  20139. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20140. this.xmin = xmin;
  20141. this.zmin = zmin;
  20142. this.xmax = xmax;
  20143. this.zmax = zmax;
  20144. this.subdivisions = subdivisions;
  20145. this.precision = precision;
  20146. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20147. }
  20148. TiledGround.prototype._regenerateVertexData = function () {
  20149. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20150. };
  20151. TiledGround.prototype.copy = function (id) {
  20152. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20153. };
  20154. return TiledGround;
  20155. })(_Primitive);
  20156. Primitives.TiledGround = TiledGround;
  20157. var Plane = (function (_super) {
  20158. __extends(Plane, _super);
  20159. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20160. this.size = size;
  20161. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20162. }
  20163. Plane.prototype._regenerateVertexData = function () {
  20164. return BABYLON.VertexData.CreatePlane(this.size);
  20165. };
  20166. Plane.prototype.copy = function (id) {
  20167. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20168. };
  20169. return Plane;
  20170. })(_Primitive);
  20171. Primitives.Plane = Plane;
  20172. var TorusKnot = (function (_super) {
  20173. __extends(TorusKnot, _super);
  20174. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20175. this.radius = radius;
  20176. this.tube = tube;
  20177. this.radialSegments = radialSegments;
  20178. this.tubularSegments = tubularSegments;
  20179. this.p = p;
  20180. this.q = q;
  20181. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20182. }
  20183. TorusKnot.prototype._regenerateVertexData = function () {
  20184. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20185. };
  20186. TorusKnot.prototype.copy = function (id) {
  20187. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20188. };
  20189. return TorusKnot;
  20190. })(_Primitive);
  20191. Primitives.TorusKnot = TorusKnot;
  20192. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20193. var Primitives = Geometry.Primitives;
  20194. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20195. var Geometry = BABYLON.Geometry;
  20196. })(BABYLON || (BABYLON = {}));
  20197. var __extends = this.__extends || function (d, b) {
  20198. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20199. function __() { this.constructor = d; }
  20200. __.prototype = b.prototype;
  20201. d.prototype = new __();
  20202. };
  20203. var BABYLON;
  20204. (function (BABYLON) {
  20205. var Gamepads = (function () {
  20206. function Gamepads(ongamedpadconnected) {
  20207. var _this = this;
  20208. this.babylonGamepads = [];
  20209. this.oneGamepadConnected = false;
  20210. this.isMonitoring = false;
  20211. this.gamepadEventSupported = 'GamepadEvent' in window;
  20212. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20213. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  20214. this._callbackGamepadConnected = ongamedpadconnected;
  20215. if (this.gamepadSupportAvailable) {
  20216. if (this.gamepadEventSupported) {
  20217. window.addEventListener('gamepadconnected', function (evt) {
  20218. _this._onGamepadConnected(evt);
  20219. }, false);
  20220. window.addEventListener('gamepaddisconnected', function (evt) {
  20221. _this._onGamepadDisconnected(evt);
  20222. }, false);
  20223. } else {
  20224. this._startMonitoringGamepads();
  20225. }
  20226. if (!this.oneGamepadConnected) {
  20227. this._insertGamepadDOMInstructions();
  20228. }
  20229. } else {
  20230. this._insertGamepadDOMNotSupported();
  20231. }
  20232. }
  20233. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20234. Gamepads.gamepadDOMInfo = document.createElement("div");
  20235. var buttonAImage = document.createElement("img");
  20236. buttonAImage.src = this.buttonADataURL;
  20237. var spanMessage = document.createElement("span");
  20238. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20239. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20240. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20241. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20242. Gamepads.gamepadDOMInfo.style.width = "100%";
  20243. Gamepads.gamepadDOMInfo.style.height = "48px";
  20244. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20245. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20246. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20247. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20248. buttonAImage.style.position = "relative";
  20249. buttonAImage.style.bottom = "8px";
  20250. spanMessage.style.position = "relative";
  20251. spanMessage.style.fontSize = "32px";
  20252. spanMessage.style.bottom = "32px";
  20253. spanMessage.style.color = "green";
  20254. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20255. };
  20256. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20257. Gamepads.gamepadDOMInfo = document.createElement("div");
  20258. var spanMessage = document.createElement("span");
  20259. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20260. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20261. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20262. Gamepads.gamepadDOMInfo.style.width = "100%";
  20263. Gamepads.gamepadDOMInfo.style.height = "40px";
  20264. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20265. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20266. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20267. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20268. spanMessage.style.position = "relative";
  20269. spanMessage.style.fontSize = "32px";
  20270. spanMessage.style.color = "red";
  20271. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20272. };
  20273. Gamepads.prototype.dispose = function () {
  20274. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20275. };
  20276. Gamepads.prototype._onGamepadConnected = function (evt) {
  20277. var newGamepad = this._addNewGamepad(evt.gamepad);
  20278. if (this._callbackGamepadConnected)
  20279. this._callbackGamepadConnected(newGamepad);
  20280. this._startMonitoringGamepads();
  20281. };
  20282. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20283. if (!this.oneGamepadConnected) {
  20284. this.oneGamepadConnected = true;
  20285. if (Gamepads.gamepadDOMInfo) {
  20286. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20287. Gamepads.gamepadDOMInfo = null;
  20288. }
  20289. }
  20290. var newGamepad;
  20291. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20292. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20293. } else {
  20294. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20295. }
  20296. this.babylonGamepads.push(newGamepad);
  20297. return newGamepad;
  20298. };
  20299. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20300. for (var i in this.babylonGamepads) {
  20301. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20302. this.babylonGamepads.splice(i, 1);
  20303. break;
  20304. }
  20305. }
  20306. if (this.babylonGamepads.length == 0) {
  20307. this._stopMonitoringGamepads();
  20308. }
  20309. };
  20310. Gamepads.prototype._startMonitoringGamepads = function () {
  20311. if (!this.isMonitoring) {
  20312. this.isMonitoring = true;
  20313. this._checkGamepadsStatus();
  20314. }
  20315. };
  20316. Gamepads.prototype._stopMonitoringGamepads = function () {
  20317. this.isMonitoring = false;
  20318. };
  20319. Gamepads.prototype._checkGamepadsStatus = function () {
  20320. var _this = this;
  20321. this._updateGamepadObjects();
  20322. for (var i in this.babylonGamepads) {
  20323. this.babylonGamepads[i].update();
  20324. }
  20325. if (this.isMonitoring) {
  20326. if (window.requestAnimationFrame) {
  20327. window.requestAnimationFrame(function () {
  20328. _this._checkGamepadsStatus();
  20329. });
  20330. } else if (window.mozRequestAnimationFrame) {
  20331. window.mozRequestAnimationFrame(function () {
  20332. _this._checkGamepadsStatus();
  20333. });
  20334. } else if (window.webkitRequestAnimationFrame) {
  20335. window.webkitRequestAnimationFrame(function () {
  20336. _this._checkGamepadsStatus();
  20337. });
  20338. }
  20339. }
  20340. };
  20341. Gamepads.prototype._updateGamepadObjects = function () {
  20342. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20343. for (var i = 0; i < gamepads.length; i++) {
  20344. if (gamepads[i]) {
  20345. if (!(gamepads[i].index in this.babylonGamepads)) {
  20346. var newGamepad = this._addNewGamepad(gamepads[i]);
  20347. if (this._callbackGamepadConnected) {
  20348. this._callbackGamepadConnected(newGamepad);
  20349. }
  20350. } else {
  20351. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20352. }
  20353. }
  20354. }
  20355. };
  20356. return Gamepads;
  20357. })();
  20358. BABYLON.Gamepads = Gamepads;
  20359. var StickValues = (function () {
  20360. function StickValues(x, y) {
  20361. this.x = x;
  20362. this.y = y;
  20363. }
  20364. return StickValues;
  20365. })();
  20366. BABYLON.StickValues = StickValues;
  20367. var Gamepad = (function () {
  20368. function Gamepad(id, index, browserGamepad) {
  20369. this.id = id;
  20370. this.index = index;
  20371. this.browserGamepad = browserGamepad;
  20372. if (this.browserGamepad.axes.length >= 2) {
  20373. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20374. }
  20375. if (this.browserGamepad.axes.length >= 4) {
  20376. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20377. }
  20378. }
  20379. Gamepad.prototype.onleftstickchanged = function (callback) {
  20380. this._onleftstickchanged = callback;
  20381. };
  20382. Gamepad.prototype.onrightstickchanged = function (callback) {
  20383. this._onrightstickchanged = callback;
  20384. };
  20385. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20386. get: function () {
  20387. return this._leftStick;
  20388. },
  20389. set: function (newValues) {
  20390. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20391. this._onleftstickchanged(newValues);
  20392. }
  20393. this._leftStick = newValues;
  20394. },
  20395. enumerable: true,
  20396. configurable: true
  20397. });
  20398. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20399. get: function () {
  20400. return this._rightStick;
  20401. },
  20402. set: function (newValues) {
  20403. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20404. this._onrightstickchanged(newValues);
  20405. }
  20406. this._rightStick = newValues;
  20407. },
  20408. enumerable: true,
  20409. configurable: true
  20410. });
  20411. Gamepad.prototype.update = function () {
  20412. if (this._leftStick) {
  20413. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20414. }
  20415. if (this._rightStick) {
  20416. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20417. }
  20418. };
  20419. return Gamepad;
  20420. })();
  20421. BABYLON.Gamepad = Gamepad;
  20422. var GenericPad = (function (_super) {
  20423. __extends(GenericPad, _super);
  20424. function GenericPad(id, index, gamepad) {
  20425. _super.call(this, id, index, gamepad);
  20426. this.id = id;
  20427. this.index = index;
  20428. this.gamepad = gamepad;
  20429. this._buttons = new Array(gamepad.buttons.length);
  20430. }
  20431. GenericPad.prototype.onbuttondown = function (callback) {
  20432. this._onbuttondown = callback;
  20433. };
  20434. GenericPad.prototype.onbuttonup = function (callback) {
  20435. this._onbuttonup = callback;
  20436. };
  20437. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20438. if (newValue !== currentValue) {
  20439. if (this._onbuttondown && newValue === 1) {
  20440. this._onbuttondown(buttonIndex);
  20441. }
  20442. if (this._onbuttonup && newValue === 0) {
  20443. this._onbuttonup(buttonIndex);
  20444. }
  20445. }
  20446. return newValue;
  20447. };
  20448. GenericPad.prototype.update = function () {
  20449. _super.prototype.update.call(this);
  20450. for (var index = 0; index < this._buttons.length; index++) {
  20451. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20452. }
  20453. };
  20454. return GenericPad;
  20455. })(Gamepad);
  20456. BABYLON.GenericPad = GenericPad;
  20457. (function (Xbox360Button) {
  20458. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20459. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20460. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20461. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20462. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20463. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20464. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20465. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20466. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20467. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20468. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20469. var Xbox360Button = BABYLON.Xbox360Button;
  20470. (function (Xbox360Dpad) {
  20471. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20472. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20473. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20474. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20475. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20476. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20477. var Xbox360Pad = (function (_super) {
  20478. __extends(Xbox360Pad, _super);
  20479. function Xbox360Pad() {
  20480. _super.apply(this, arguments);
  20481. this._leftTrigger = 0;
  20482. this._rightTrigger = 0;
  20483. this._buttonA = 0;
  20484. this._buttonB = 0;
  20485. this._buttonX = 0;
  20486. this._buttonY = 0;
  20487. this._buttonBack = 0;
  20488. this._buttonStart = 0;
  20489. this._buttonLB = 0;
  20490. this._buttonRB = 0;
  20491. this._buttonLeftStick = 0;
  20492. this._buttonRightStick = 0;
  20493. this._dPadUp = 0;
  20494. this._dPadDown = 0;
  20495. this._dPadLeft = 0;
  20496. this._dPadRight = 0;
  20497. }
  20498. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20499. this._onlefttriggerchanged = callback;
  20500. };
  20501. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20502. this._onrighttriggerchanged = callback;
  20503. };
  20504. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20505. get: function () {
  20506. return this._leftTrigger;
  20507. },
  20508. set: function (newValue) {
  20509. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20510. this._onlefttriggerchanged(newValue);
  20511. }
  20512. this._leftTrigger = newValue;
  20513. },
  20514. enumerable: true,
  20515. configurable: true
  20516. });
  20517. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20518. get: function () {
  20519. return this._rightTrigger;
  20520. },
  20521. set: function (newValue) {
  20522. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20523. this._onrighttriggerchanged(newValue);
  20524. }
  20525. this._rightTrigger = newValue;
  20526. },
  20527. enumerable: true,
  20528. configurable: true
  20529. });
  20530. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20531. this._onbuttondown = callback;
  20532. };
  20533. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20534. this._onbuttonup = callback;
  20535. };
  20536. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20537. this._ondpaddown = callback;
  20538. };
  20539. Xbox360Pad.prototype.ondpadup = function (callback) {
  20540. this._ondpadup = callback;
  20541. };
  20542. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20543. if (newValue !== currentValue) {
  20544. if (this._onbuttondown && newValue === 1) {
  20545. this._onbuttondown(buttonType);
  20546. }
  20547. if (this._onbuttonup && newValue === 0) {
  20548. this._onbuttonup(buttonType);
  20549. }
  20550. }
  20551. return newValue;
  20552. };
  20553. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20554. if (newValue !== currentValue) {
  20555. if (this._ondpaddown && newValue === 1) {
  20556. this._ondpaddown(buttonType);
  20557. }
  20558. if (this._ondpadup && newValue === 0) {
  20559. this._ondpadup(buttonType);
  20560. }
  20561. }
  20562. return newValue;
  20563. };
  20564. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20565. get: function () {
  20566. return this._buttonA;
  20567. },
  20568. set: function (value) {
  20569. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20570. },
  20571. enumerable: true,
  20572. configurable: true
  20573. });
  20574. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20575. get: function () {
  20576. return this._buttonB;
  20577. },
  20578. set: function (value) {
  20579. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20580. },
  20581. enumerable: true,
  20582. configurable: true
  20583. });
  20584. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20585. get: function () {
  20586. return this._buttonX;
  20587. },
  20588. set: function (value) {
  20589. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20595. get: function () {
  20596. return this._buttonY;
  20597. },
  20598. set: function (value) {
  20599. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20600. },
  20601. enumerable: true,
  20602. configurable: true
  20603. });
  20604. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20605. get: function () {
  20606. return this._buttonStart;
  20607. },
  20608. set: function (value) {
  20609. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20610. },
  20611. enumerable: true,
  20612. configurable: true
  20613. });
  20614. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20615. get: function () {
  20616. return this._buttonBack;
  20617. },
  20618. set: function (value) {
  20619. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20620. },
  20621. enumerable: true,
  20622. configurable: true
  20623. });
  20624. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20625. get: function () {
  20626. return this._buttonLB;
  20627. },
  20628. set: function (value) {
  20629. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20635. get: function () {
  20636. return this._buttonRB;
  20637. },
  20638. set: function (value) {
  20639. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20645. get: function () {
  20646. return this._buttonLeftStick;
  20647. },
  20648. set: function (value) {
  20649. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20650. },
  20651. enumerable: true,
  20652. configurable: true
  20653. });
  20654. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20655. get: function () {
  20656. return this._buttonRightStick;
  20657. },
  20658. set: function (value) {
  20659. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20665. get: function () {
  20666. return this._dPadUp;
  20667. },
  20668. set: function (value) {
  20669. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20675. get: function () {
  20676. return this._dPadDown;
  20677. },
  20678. set: function (value) {
  20679. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20685. get: function () {
  20686. return this._dPadLeft;
  20687. },
  20688. set: function (value) {
  20689. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20695. get: function () {
  20696. return this._dPadRight;
  20697. },
  20698. set: function (value) {
  20699. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. Xbox360Pad.prototype.update = function () {
  20705. _super.prototype.update.call(this);
  20706. this.buttonA = this.browserGamepad.buttons[0].value;
  20707. this.buttonB = this.browserGamepad.buttons[1].value;
  20708. this.buttonX = this.browserGamepad.buttons[2].value;
  20709. this.buttonY = this.browserGamepad.buttons[3].value;
  20710. this.buttonLB = this.browserGamepad.buttons[4].value;
  20711. this.buttonRB = this.browserGamepad.buttons[5].value;
  20712. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20713. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20714. this.buttonBack = this.browserGamepad.buttons[8].value;
  20715. this.buttonStart = this.browserGamepad.buttons[9].value;
  20716. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20717. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20718. this.dPadUp = this.browserGamepad.buttons[12].value;
  20719. this.dPadDown = this.browserGamepad.buttons[13].value;
  20720. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20721. this.dPadRight = this.browserGamepad.buttons[15].value;
  20722. };
  20723. return Xbox360Pad;
  20724. })(Gamepad);
  20725. BABYLON.Xbox360Pad = Xbox360Pad;
  20726. })(BABYLON || (BABYLON = {}));
  20727. var __extends = this.__extends || function (d, b) {
  20728. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20729. function __() { this.constructor = d; }
  20730. __.prototype = b.prototype;
  20731. d.prototype = new __();
  20732. };
  20733. var BABYLON;
  20734. (function (BABYLON) {
  20735. var GamepadCamera = (function (_super) {
  20736. __extends(GamepadCamera, _super);
  20737. function GamepadCamera(name, position, scene) {
  20738. var _this = this;
  20739. _super.call(this, name, position, scene);
  20740. this.angularSensibility = 200;
  20741. this.moveSensibility = 75;
  20742. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20743. _this._onNewGameConnected(gamepad);
  20744. });
  20745. }
  20746. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20747. if (gamepad.index === 0) {
  20748. this._gamepad = gamepad;
  20749. }
  20750. };
  20751. GamepadCamera.prototype._checkInputs = function () {
  20752. if (!this._gamepad) {
  20753. return;
  20754. }
  20755. var LSValues = this._gamepad.leftStick;
  20756. var normalizedLX = LSValues.x / this.moveSensibility;
  20757. var normalizedLY = LSValues.y / this.moveSensibility;
  20758. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20759. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20760. var RSValues = this._gamepad.rightStick;
  20761. var normalizedRX = RSValues.x / this.angularSensibility;
  20762. var normalizedRY = RSValues.y / this.angularSensibility;
  20763. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20764. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20765. ;
  20766. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20767. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20768. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20769. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20770. };
  20771. GamepadCamera.prototype.dispose = function () {
  20772. this._gamepads.dispose();
  20773. _super.prototype.dispose.call(this);
  20774. };
  20775. return GamepadCamera;
  20776. })(BABYLON.FreeCamera);
  20777. BABYLON.GamepadCamera = GamepadCamera;
  20778. })(BABYLON || (BABYLON = {}));
  20779. var __extends = this.__extends || function (d, b) {
  20780. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20781. function __() { this.constructor = d; }
  20782. __.prototype = b.prototype;
  20783. d.prototype = new __();
  20784. };
  20785. var BABYLON;
  20786. (function (BABYLON) {
  20787. var LinesMesh = (function (_super) {
  20788. __extends(LinesMesh, _super);
  20789. function LinesMesh(name, scene, updatable) {
  20790. if (typeof updatable === "undefined") { updatable = false; }
  20791. _super.call(this, name, scene);
  20792. this.color = new BABYLON.Color3(1, 1, 1);
  20793. this.alpha = 1;
  20794. this._indices = new Array();
  20795. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20796. attributes: ["position"],
  20797. uniforms: ["worldViewProjection", "color"],
  20798. needAlphaBlending: true
  20799. });
  20800. }
  20801. Object.defineProperty(LinesMesh.prototype, "material", {
  20802. get: function () {
  20803. return this._colorShader;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20809. get: function () {
  20810. return false;
  20811. },
  20812. enumerable: true,
  20813. configurable: true
  20814. });
  20815. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20816. get: function () {
  20817. return false;
  20818. },
  20819. enumerable: true,
  20820. configurable: true
  20821. });
  20822. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20823. var engine = this.getScene().getEngine();
  20824. var indexToBind = this._geometry.getIndexBuffer();
  20825. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20826. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20827. };
  20828. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20829. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20830. return;
  20831. }
  20832. var engine = this.getScene().getEngine();
  20833. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20834. };
  20835. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20836. return null;
  20837. };
  20838. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20839. this._colorShader.dispose();
  20840. _super.prototype.dispose.call(this, doNotRecurse);
  20841. };
  20842. return LinesMesh;
  20843. })(BABYLON.Mesh);
  20844. BABYLON.LinesMesh = LinesMesh;
  20845. })(BABYLON || (BABYLON = {}));
  20846. var BABYLON;
  20847. (function (BABYLON) {
  20848. var OutlineRenderer = (function () {
  20849. function OutlineRenderer(scene) {
  20850. this._scene = scene;
  20851. }
  20852. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20853. var scene = this._scene;
  20854. var engine = this._scene.getEngine();
  20855. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20856. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20857. return;
  20858. }
  20859. var mesh = subMesh.getRenderingMesh();
  20860. var material = subMesh.getMaterial();
  20861. engine.enableEffect(this._effect);
  20862. this._effect.setFloat("offset", mesh.outlineWidth);
  20863. this._effect.setColor3("color", mesh.outlineColor);
  20864. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20865. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20866. if (useBones) {
  20867. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20868. }
  20869. mesh._bind(subMesh, this._effect, false);
  20870. if (material && material.needAlphaTesting()) {
  20871. var alphaTexture = material.getAlphaTestTexture();
  20872. this._effect.setTexture("diffuseSampler", alphaTexture);
  20873. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20874. }
  20875. if (hardwareInstancedRendering) {
  20876. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20877. } else {
  20878. if (batch.renderSelf[subMesh._id]) {
  20879. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20880. mesh._draw(subMesh, true);
  20881. }
  20882. if (batch.visibleInstances[subMesh._id]) {
  20883. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20884. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20885. this._effect.setMatrix("world", instance.getWorldMatrix());
  20886. mesh._draw(subMesh, true);
  20887. }
  20888. }
  20889. }
  20890. };
  20891. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20892. var defines = [];
  20893. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20894. var mesh = subMesh.getMesh();
  20895. var material = subMesh.getMaterial();
  20896. if (material && material.needAlphaTesting()) {
  20897. defines.push("#define ALPHATEST");
  20898. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20899. attribs.push(BABYLON.VertexBuffer.UVKind);
  20900. defines.push("#define UV1");
  20901. }
  20902. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20903. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20904. defines.push("#define UV2");
  20905. }
  20906. }
  20907. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20910. defines.push("#define BONES");
  20911. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20912. }
  20913. if (useInstances) {
  20914. defines.push("#define INSTANCES");
  20915. attribs.push("world0");
  20916. attribs.push("world1");
  20917. attribs.push("world2");
  20918. attribs.push("world3");
  20919. }
  20920. var join = defines.join("\n");
  20921. if (this._cachedDefines != join) {
  20922. this._cachedDefines = join;
  20923. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20924. }
  20925. return this._effect.isReady();
  20926. };
  20927. return OutlineRenderer;
  20928. })();
  20929. BABYLON.OutlineRenderer = OutlineRenderer;
  20930. })(BABYLON || (BABYLON = {}));
  20931. var BABYLON;
  20932. (function (BABYLON) {
  20933. var MeshAssetTask = (function () {
  20934. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20935. this.name = name;
  20936. this.meshesNames = meshesNames;
  20937. this.rootUrl = rootUrl;
  20938. this.sceneFilename = sceneFilename;
  20939. this.isCompleted = false;
  20940. }
  20941. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20942. var _this = this;
  20943. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20944. _this.loadedMeshes = meshes;
  20945. _this.loadedParticleSystems = particleSystems;
  20946. _this.loadedSkeletons = skeletons;
  20947. _this.isCompleted = true;
  20948. if (_this.onSuccess) {
  20949. _this.onSuccess(_this);
  20950. }
  20951. onSuccess();
  20952. }, null, function () {
  20953. if (_this.onError) {
  20954. _this.onError(_this);
  20955. }
  20956. onError();
  20957. });
  20958. };
  20959. return MeshAssetTask;
  20960. })();
  20961. BABYLON.MeshAssetTask = MeshAssetTask;
  20962. var TextFileAssetTask = (function () {
  20963. function TextFileAssetTask(name, url) {
  20964. this.name = name;
  20965. this.url = url;
  20966. this.isCompleted = false;
  20967. }
  20968. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20969. var _this = this;
  20970. BABYLON.Tools.LoadFile(this.url, function (data) {
  20971. _this.text = data;
  20972. _this.isCompleted = true;
  20973. if (_this.onSuccess) {
  20974. _this.onSuccess(_this);
  20975. }
  20976. onSuccess();
  20977. }, null, scene.database, false, function () {
  20978. if (_this.onError) {
  20979. _this.onError(_this);
  20980. }
  20981. onError();
  20982. });
  20983. };
  20984. return TextFileAssetTask;
  20985. })();
  20986. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20987. var BinaryFileAssetTask = (function () {
  20988. function BinaryFileAssetTask(name, url) {
  20989. this.name = name;
  20990. this.url = url;
  20991. this.isCompleted = false;
  20992. }
  20993. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20994. var _this = this;
  20995. BABYLON.Tools.LoadFile(this.url, function (data) {
  20996. _this.data = data;
  20997. _this.isCompleted = true;
  20998. if (_this.onSuccess) {
  20999. _this.onSuccess(_this);
  21000. }
  21001. onSuccess();
  21002. }, null, scene.database, true, function () {
  21003. if (_this.onError) {
  21004. _this.onError(_this);
  21005. }
  21006. onError();
  21007. });
  21008. };
  21009. return BinaryFileAssetTask;
  21010. })();
  21011. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21012. var ImageAssetTask = (function () {
  21013. function ImageAssetTask(name, url) {
  21014. this.name = name;
  21015. this.url = url;
  21016. this.isCompleted = false;
  21017. }
  21018. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21019. var _this = this;
  21020. var img = new Image();
  21021. img.onload = function () {
  21022. _this.image = img;
  21023. _this.isCompleted = true;
  21024. if (_this.onSuccess) {
  21025. _this.onSuccess(_this);
  21026. }
  21027. onSuccess();
  21028. };
  21029. img.onerror = function () {
  21030. if (_this.onError) {
  21031. _this.onError(_this);
  21032. }
  21033. onError();
  21034. };
  21035. img.src = this.url;
  21036. };
  21037. return ImageAssetTask;
  21038. })();
  21039. BABYLON.ImageAssetTask = ImageAssetTask;
  21040. var TextureAssetTask = (function () {
  21041. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21042. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21043. this.name = name;
  21044. this.url = url;
  21045. this.noMipmap = noMipmap;
  21046. this.invertY = invertY;
  21047. this.samplingMode = samplingMode;
  21048. this.isCompleted = false;
  21049. }
  21050. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21051. var _this = this;
  21052. var onload = function () {
  21053. _this.isCompleted = true;
  21054. if (_this.onSuccess) {
  21055. _this.onSuccess(_this);
  21056. }
  21057. onSuccess();
  21058. };
  21059. var onerror = function () {
  21060. if (_this.onError) {
  21061. _this.onError(_this);
  21062. }
  21063. onError();
  21064. };
  21065. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21066. };
  21067. return TextureAssetTask;
  21068. })();
  21069. BABYLON.TextureAssetTask = TextureAssetTask;
  21070. var AssetsManager = (function () {
  21071. function AssetsManager(scene) {
  21072. this._tasks = new Array();
  21073. this._waitingTasksCount = 0;
  21074. this.useDefaultLoadingScreen = true;
  21075. this._scene = scene;
  21076. }
  21077. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21078. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21079. this._tasks.push(task);
  21080. return task;
  21081. };
  21082. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21083. var task = new TextFileAssetTask(taskName, url);
  21084. this._tasks.push(task);
  21085. return task;
  21086. };
  21087. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21088. var task = new BinaryFileAssetTask(taskName, url);
  21089. this._tasks.push(task);
  21090. return task;
  21091. };
  21092. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21093. var task = new ImageAssetTask(taskName, url);
  21094. this._tasks.push(task);
  21095. return task;
  21096. };
  21097. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21098. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21099. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21100. this._tasks.push(task);
  21101. return task;
  21102. };
  21103. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21104. this._waitingTasksCount--;
  21105. if (this._waitingTasksCount === 0) {
  21106. if (this.onFinish) {
  21107. this.onFinish(this._tasks);
  21108. }
  21109. this._scene.getEngine().hideLoadingUI();
  21110. }
  21111. };
  21112. AssetsManager.prototype._runTask = function (task) {
  21113. var _this = this;
  21114. task.run(this._scene, function () {
  21115. if (_this.onTaskSuccess) {
  21116. _this.onTaskSuccess(task);
  21117. }
  21118. _this._decreaseWaitingTasksCount();
  21119. }, function () {
  21120. if (_this.onTaskError) {
  21121. _this.onTaskError(task);
  21122. }
  21123. _this._decreaseWaitingTasksCount();
  21124. });
  21125. };
  21126. AssetsManager.prototype.reset = function () {
  21127. this._tasks = new Array();
  21128. return this;
  21129. };
  21130. AssetsManager.prototype.load = function () {
  21131. this._waitingTasksCount = this._tasks.length;
  21132. if (this._waitingTasksCount === 0) {
  21133. if (this.onFinish) {
  21134. this.onFinish(this._tasks);
  21135. }
  21136. return this;
  21137. }
  21138. if (this.useDefaultLoadingScreen) {
  21139. this._scene.getEngine().displayLoadingUI();
  21140. }
  21141. for (var index = 0; index < this._tasks.length; index++) {
  21142. var task = this._tasks[index];
  21143. this._runTask(task);
  21144. }
  21145. return this;
  21146. };
  21147. return AssetsManager;
  21148. })();
  21149. BABYLON.AssetsManager = AssetsManager;
  21150. })(BABYLON || (BABYLON = {}));
  21151. var __extends = this.__extends || function (d, b) {
  21152. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21153. function __() { this.constructor = d; }
  21154. __.prototype = b.prototype;
  21155. d.prototype = new __();
  21156. };
  21157. var BABYLON;
  21158. (function (BABYLON) {
  21159. var VRDeviceOrientationCamera = (function (_super) {
  21160. __extends(VRDeviceOrientationCamera, _super);
  21161. function VRDeviceOrientationCamera(name, position, scene) {
  21162. _super.call(this, name, position, scene);
  21163. this._alpha = 0;
  21164. this._beta = 0;
  21165. this._gamma = 0;
  21166. }
  21167. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21168. this._alpha = +evt.alpha | 0;
  21169. this._beta = +evt.beta | 0;
  21170. this._gamma = +evt.gamma | 0;
  21171. if (this._gamma < 0) {
  21172. this._gamma = 90 + this._gamma;
  21173. } else {
  21174. this._gamma = 270 - this._gamma;
  21175. }
  21176. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21177. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21178. this.rotation.z = this._beta / 180.0 * Math.PI;
  21179. };
  21180. return VRDeviceOrientationCamera;
  21181. })(BABYLON.OculusCamera);
  21182. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21183. })(BABYLON || (BABYLON = {}));
  21184. var __extends = this.__extends || function (d, b) {
  21185. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21186. function __() { this.constructor = d; }
  21187. __.prototype = b.prototype;
  21188. d.prototype = new __();
  21189. };
  21190. var BABYLON;
  21191. (function (BABYLON) {
  21192. var WebVRCamera = (function (_super) {
  21193. __extends(WebVRCamera, _super);
  21194. function WebVRCamera(name, position, scene) {
  21195. _super.call(this, name, position, scene);
  21196. this._hmdDevice = null;
  21197. this._sensorDevice = null;
  21198. this._cacheState = null;
  21199. this._cacheQuaternion = new BABYLON.Quaternion();
  21200. this._cacheRotation = BABYLON.Vector3.Zero();
  21201. this._vrEnabled = false;
  21202. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21203. }
  21204. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21205. var size = devices.length;
  21206. var i = 0;
  21207. this._sensorDevice = null;
  21208. this._hmdDevice = null;
  21209. while (i < size && this._hmdDevice === null) {
  21210. if (devices[i] instanceof HMDVRDevice) {
  21211. this._hmdDevice = devices[i];
  21212. }
  21213. i++;
  21214. }
  21215. i = 0;
  21216. while (i < size && this._sensorDevice === null) {
  21217. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21218. this._sensorDevice = devices[i];
  21219. }
  21220. i++;
  21221. }
  21222. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21223. };
  21224. WebVRCamera.prototype._update = function () {
  21225. if (this._vrEnabled) {
  21226. this._cacheState = this._sensorDevice.getState();
  21227. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21228. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21229. this.rotation.x = -this._cacheRotation.z;
  21230. this.rotation.y = -this._cacheRotation.y;
  21231. this.rotation.z = this._cacheRotation.x;
  21232. }
  21233. _super.prototype._update.call(this);
  21234. };
  21235. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21236. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21237. if (navigator.getVRDevices) {
  21238. navigator.getVRDevices().then(this._getWebVRDevices);
  21239. } else if (navigator.mozGetVRDevices) {
  21240. navigator.mozGetVRDevices(this._getWebVRDevices);
  21241. }
  21242. };
  21243. WebVRCamera.prototype.detachControl = function (element) {
  21244. _super.prototype.detachControl.call(this, element);
  21245. this._vrEnabled = false;
  21246. };
  21247. return WebVRCamera;
  21248. })(BABYLON.OculusCamera);
  21249. BABYLON.WebVRCamera = WebVRCamera;
  21250. })(BABYLON || (BABYLON = {}));
  21251. var __extends = this.__extends || function (d, b) {
  21252. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21253. function __() { this.constructor = d; }
  21254. __.prototype = b.prototype;
  21255. d.prototype = new __();
  21256. };
  21257. var BABYLON;
  21258. (function (BABYLON) {
  21259. var SceneOptimization = (function () {
  21260. function SceneOptimization(priority) {
  21261. if (typeof priority === "undefined") { priority = 0; }
  21262. this.priority = priority;
  21263. this.apply = function (scene) {
  21264. return true;
  21265. };
  21266. }
  21267. return SceneOptimization;
  21268. })();
  21269. BABYLON.SceneOptimization = SceneOptimization;
  21270. var TextureSceneOptimization = (function (_super) {
  21271. __extends(TextureSceneOptimization, _super);
  21272. function TextureSceneOptimization(maximumSize, priority) {
  21273. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21274. if (typeof priority === "undefined") { priority = 0; }
  21275. var _this = this;
  21276. _super.call(this, priority);
  21277. this.maximumSize = maximumSize;
  21278. this.priority = priority;
  21279. this.apply = function (scene) {
  21280. var allDone = true;
  21281. for (var index = 0; index < scene.textures.length; index++) {
  21282. var texture = scene.textures[index];
  21283. if (!texture.canRescale) {
  21284. continue;
  21285. }
  21286. var currentSize = texture.getSize();
  21287. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21288. if (maxDimension > _this.maximumSize) {
  21289. texture.scale(0.5);
  21290. allDone = false;
  21291. }
  21292. }
  21293. return allDone;
  21294. };
  21295. }
  21296. return TextureSceneOptimization;
  21297. })(SceneOptimization);
  21298. BABYLON.TextureSceneOptimization = TextureSceneOptimization;
  21299. var HardwareScalingSceneOptimization = (function (_super) {
  21300. __extends(HardwareScalingSceneOptimization, _super);
  21301. function HardwareScalingSceneOptimization(maximumScale, priority) {
  21302. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21303. if (typeof priority === "undefined") { priority = 0; }
  21304. var _this = this;
  21305. _super.call(this, priority);
  21306. this.maximumScale = maximumScale;
  21307. this.priority = priority;
  21308. this._currentScale = 1;
  21309. this.apply = function (scene) {
  21310. _this._currentScale++;
  21311. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21312. return _this._currentScale >= _this.maximumScale;
  21313. };
  21314. }
  21315. return HardwareScalingSceneOptimization;
  21316. })(SceneOptimization);
  21317. BABYLON.HardwareScalingSceneOptimization = HardwareScalingSceneOptimization;
  21318. var ShadowsSceneOptimization = (function (_super) {
  21319. __extends(ShadowsSceneOptimization, _super);
  21320. function ShadowsSceneOptimization() {
  21321. _super.apply(this, arguments);
  21322. this.apply = function (scene) {
  21323. scene.shadowsEnabled = false;
  21324. return true;
  21325. };
  21326. }
  21327. return ShadowsSceneOptimization;
  21328. })(SceneOptimization);
  21329. BABYLON.ShadowsSceneOptimization = ShadowsSceneOptimization;
  21330. var PostProcessesSceneOptimization = (function (_super) {
  21331. __extends(PostProcessesSceneOptimization, _super);
  21332. function PostProcessesSceneOptimization() {
  21333. _super.apply(this, arguments);
  21334. this.apply = function (scene) {
  21335. scene.postProcessesEnabled = false;
  21336. return true;
  21337. };
  21338. }
  21339. return PostProcessesSceneOptimization;
  21340. })(SceneOptimization);
  21341. BABYLON.PostProcessesSceneOptimization = PostProcessesSceneOptimization;
  21342. var LensFlaresSceneOptimization = (function (_super) {
  21343. __extends(LensFlaresSceneOptimization, _super);
  21344. function LensFlaresSceneOptimization() {
  21345. _super.apply(this, arguments);
  21346. this.apply = function (scene) {
  21347. scene.lensFlaresEnabled = false;
  21348. return true;
  21349. };
  21350. }
  21351. return LensFlaresSceneOptimization;
  21352. })(SceneOptimization);
  21353. BABYLON.LensFlaresSceneOptimization = LensFlaresSceneOptimization;
  21354. var ParticlesSceneOptimization = (function (_super) {
  21355. __extends(ParticlesSceneOptimization, _super);
  21356. function ParticlesSceneOptimization() {
  21357. _super.apply(this, arguments);
  21358. this.apply = function (scene) {
  21359. scene.particlesEnabled = false;
  21360. return true;
  21361. };
  21362. }
  21363. return ParticlesSceneOptimization;
  21364. })(SceneOptimization);
  21365. BABYLON.ParticlesSceneOptimization = ParticlesSceneOptimization;
  21366. var SceneOptimizerOptions = (function () {
  21367. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21368. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21369. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21370. this.targetFrameRate = targetFrameRate;
  21371. this.trackerDuration = trackerDuration;
  21372. this.optimizations = new Array();
  21373. }
  21374. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21375. var result = new SceneOptimizerOptions(targetFrameRate);
  21376. var priority = 0;
  21377. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21378. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21379. priority++;
  21380. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21381. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21382. priority++;
  21383. result.optimizations.push(new TextureSceneOptimization(priority, 1024));
  21384. return result;
  21385. };
  21386. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21387. var result = new SceneOptimizerOptions(targetFrameRate);
  21388. var priority = 0;
  21389. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21390. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21391. priority++;
  21392. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21393. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21394. priority++;
  21395. result.optimizations.push(new TextureSceneOptimization(priority, 512));
  21396. priority++;
  21397. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 2));
  21398. return result;
  21399. };
  21400. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21401. var result = new SceneOptimizerOptions(targetFrameRate);
  21402. var priority = 0;
  21403. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21404. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21405. priority++;
  21406. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21407. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21408. priority++;
  21409. result.optimizations.push(new TextureSceneOptimization(priority, 256));
  21410. priority++;
  21411. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 4));
  21412. return result;
  21413. };
  21414. return SceneOptimizerOptions;
  21415. })();
  21416. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21417. var SceneOptimizer = (function () {
  21418. function SceneOptimizer() {
  21419. }
  21420. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21421. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21422. if (onSuccess) {
  21423. onSuccess();
  21424. }
  21425. return;
  21426. }
  21427. var allDone = true;
  21428. var noOptimizationApplied = true;
  21429. for (var index = 0; index < options.optimizations.length; index++) {
  21430. var optimization = options.optimizations[index];
  21431. if (optimization.priority === currentPriorityLevel) {
  21432. noOptimizationApplied = false;
  21433. allDone = allDone && optimization.apply(scene);
  21434. }
  21435. }
  21436. if (noOptimizationApplied) {
  21437. if (onFailure) {
  21438. onFailure();
  21439. }
  21440. return;
  21441. }
  21442. if (allDone) {
  21443. currentPriorityLevel++;
  21444. }
  21445. scene.executeWhenReady(function () {
  21446. setTimeout(function () {
  21447. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21448. }, options.trackerDuration);
  21449. });
  21450. };
  21451. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21452. if (!options) {
  21453. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21454. }
  21455. scene.executeWhenReady(function () {
  21456. setTimeout(function () {
  21457. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21458. }, options.trackerDuration);
  21459. });
  21460. };
  21461. return SceneOptimizer;
  21462. })();
  21463. BABYLON.SceneOptimizer = SceneOptimizer;
  21464. })(BABYLON || (BABYLON = {}));