babylon.2.0-alpha.debug.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189
  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.fogEnabled = true;
  11715. this._vertexDeclaration = [3, 4, 4, 4];
  11716. this._vertexStrideSize = 15 * 4;
  11717. this._capacity = capacity;
  11718. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11719. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11720. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11721. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11722. this._scene = scene;
  11723. this._scene.spriteManagers.push(this);
  11724. this._vertexDeclaration = [3, 4, 4, 4];
  11725. this._vertexStrideSize = 15 * 4;
  11726. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11727. var indices = [];
  11728. var index = 0;
  11729. for (var count = 0; count < capacity; count++) {
  11730. indices.push(index);
  11731. indices.push(index + 1);
  11732. indices.push(index + 2);
  11733. indices.push(index);
  11734. indices.push(index + 2);
  11735. indices.push(index + 3);
  11736. index += 4;
  11737. }
  11738. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11739. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11740. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11741. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11742. }
  11743. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11744. var arrayOffset = index * 15;
  11745. if (offsetX == 0)
  11746. offsetX = this._epsilon;
  11747. else if (offsetX == 1)
  11748. offsetX = 1 - this._epsilon;
  11749. if (offsetY == 0)
  11750. offsetY = this._epsilon;
  11751. else if (offsetY == 1)
  11752. offsetY = 1 - this._epsilon;
  11753. this._vertices[arrayOffset] = sprite.position.x;
  11754. this._vertices[arrayOffset + 1] = sprite.position.y;
  11755. this._vertices[arrayOffset + 2] = sprite.position.z;
  11756. this._vertices[arrayOffset + 3] = sprite.angle;
  11757. this._vertices[arrayOffset + 4] = sprite.size;
  11758. this._vertices[arrayOffset + 5] = offsetX;
  11759. this._vertices[arrayOffset + 6] = offsetY;
  11760. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11761. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11762. var offset = (sprite.cellIndex / rowSize) >> 0;
  11763. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11764. this._vertices[arrayOffset + 10] = offset;
  11765. this._vertices[arrayOffset + 11] = sprite.color.r;
  11766. this._vertices[arrayOffset + 12] = sprite.color.g;
  11767. this._vertices[arrayOffset + 13] = sprite.color.b;
  11768. this._vertices[arrayOffset + 14] = sprite.color.a;
  11769. };
  11770. SpriteManager.prototype.render = function () {
  11771. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11772. return;
  11773. var engine = this._scene.getEngine();
  11774. var baseSize = this._spriteTexture.getBaseSize();
  11775. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11776. var max = Math.min(this._capacity, this.sprites.length);
  11777. var rowSize = baseSize.width / this.cellSize;
  11778. var offset = 0;
  11779. for (var index = 0; index < max; index++) {
  11780. var sprite = this.sprites[index];
  11781. if (!sprite) {
  11782. continue;
  11783. }
  11784. sprite._animate(deltaTime);
  11785. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11786. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11787. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11788. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11789. }
  11790. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11791. var effect = this._effectBase;
  11792. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11793. effect = this._effectFog;
  11794. }
  11795. engine.enableEffect(effect);
  11796. var viewMatrix = this._scene.getViewMatrix();
  11797. effect.setTexture("diffuseSampler", this._spriteTexture);
  11798. effect.setMatrix("view", viewMatrix);
  11799. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11800. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11801. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11802. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11803. effect.setColor3("vFogColor", this._scene.fogColor);
  11804. }
  11805. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11806. effect.setBool("alphaTest", true);
  11807. engine.setColorWrite(false);
  11808. engine.draw(true, 0, max * 6);
  11809. engine.setColorWrite(true);
  11810. effect.setBool("alphaTest", false);
  11811. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11812. engine.draw(true, 0, max * 6);
  11813. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11814. };
  11815. SpriteManager.prototype.dispose = function () {
  11816. if (this._vertexBuffer) {
  11817. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11818. this._vertexBuffer = null;
  11819. }
  11820. if (this._indexBuffer) {
  11821. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11822. this._indexBuffer = null;
  11823. }
  11824. if (this._spriteTexture) {
  11825. this._spriteTexture.dispose();
  11826. this._spriteTexture = null;
  11827. }
  11828. var index = this._scene.spriteManagers.indexOf(this);
  11829. this._scene.spriteManagers.splice(index, 1);
  11830. if (this.onDispose) {
  11831. this.onDispose();
  11832. }
  11833. };
  11834. return SpriteManager;
  11835. })();
  11836. BABYLON.SpriteManager = SpriteManager;
  11837. })(BABYLON || (BABYLON = {}));
  11838. var BABYLON;
  11839. (function (BABYLON) {
  11840. var Sprite = (function () {
  11841. function Sprite(name, manager) {
  11842. this.name = name;
  11843. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11844. this.size = 1.0;
  11845. this.angle = 0;
  11846. this.cellIndex = 0;
  11847. this.invertU = 0;
  11848. this.invertV = 0;
  11849. this.animations = new Array();
  11850. this._animationStarted = false;
  11851. this._loopAnimation = false;
  11852. this._fromIndex = 0;
  11853. this._toIndex = 0;
  11854. this._delay = 0;
  11855. this._direction = 1;
  11856. this._frameCount = 0;
  11857. this._time = 0;
  11858. this._manager = manager;
  11859. this._manager.sprites.push(this);
  11860. this.position = BABYLON.Vector3.Zero();
  11861. }
  11862. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11863. this._fromIndex = from;
  11864. this._toIndex = to;
  11865. this._loopAnimation = loop;
  11866. this._delay = delay;
  11867. this._animationStarted = true;
  11868. this._direction = from < to ? 1 : -1;
  11869. this.cellIndex = from;
  11870. this._time = 0;
  11871. };
  11872. Sprite.prototype.stopAnimation = function () {
  11873. this._animationStarted = false;
  11874. };
  11875. Sprite.prototype._animate = function (deltaTime) {
  11876. if (!this._animationStarted)
  11877. return;
  11878. this._time += deltaTime;
  11879. if (this._time > this._delay) {
  11880. this._time = this._time % this._delay;
  11881. this.cellIndex += this._direction;
  11882. if (this.cellIndex == this._toIndex) {
  11883. if (this._loopAnimation) {
  11884. this.cellIndex = this._fromIndex;
  11885. } else {
  11886. this._animationStarted = false;
  11887. if (this.disposeWhenFinishedAnimating) {
  11888. this.dispose();
  11889. }
  11890. }
  11891. }
  11892. }
  11893. };
  11894. Sprite.prototype.dispose = function () {
  11895. for (var i = 0; i < this._manager.sprites.length; i++) {
  11896. if (this._manager.sprites[i] == this) {
  11897. this._manager.sprites.splice(i, 1);
  11898. }
  11899. }
  11900. };
  11901. return Sprite;
  11902. })();
  11903. BABYLON.Sprite = Sprite;
  11904. })(BABYLON || (BABYLON = {}));
  11905. var BABYLON;
  11906. (function (BABYLON) {
  11907. var Layer = (function () {
  11908. function Layer(name, imgUrl, scene, isBackground, color) {
  11909. this.name = name;
  11910. this._vertexDeclaration = [2];
  11911. this._vertexStrideSize = 2 * 4;
  11912. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11913. this.isBackground = isBackground === undefined ? true : isBackground;
  11914. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11915. this._scene = scene;
  11916. this._scene.layers.push(this);
  11917. var vertices = [];
  11918. vertices.push(1, 1);
  11919. vertices.push(-1, 1);
  11920. vertices.push(-1, -1);
  11921. vertices.push(1, -1);
  11922. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11923. var indices = [];
  11924. indices.push(0);
  11925. indices.push(1);
  11926. indices.push(2);
  11927. indices.push(0);
  11928. indices.push(2);
  11929. indices.push(3);
  11930. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11931. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11932. }
  11933. Layer.prototype.render = function () {
  11934. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11935. return;
  11936. var engine = this._scene.getEngine();
  11937. engine.enableEffect(this._effect);
  11938. engine.setState(false);
  11939. this._effect.setTexture("textureSampler", this.texture);
  11940. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11941. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11942. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11943. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11944. engine.draw(true, 0, 6);
  11945. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11946. };
  11947. Layer.prototype.dispose = function () {
  11948. if (this._vertexBuffer) {
  11949. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11950. this._vertexBuffer = null;
  11951. }
  11952. if (this._indexBuffer) {
  11953. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11954. this._indexBuffer = null;
  11955. }
  11956. if (this.texture) {
  11957. this.texture.dispose();
  11958. this.texture = null;
  11959. }
  11960. var index = this._scene.layers.indexOf(this);
  11961. this._scene.layers.splice(index, 1);
  11962. if (this.onDispose) {
  11963. this.onDispose();
  11964. }
  11965. };
  11966. return Layer;
  11967. })();
  11968. BABYLON.Layer = Layer;
  11969. })(BABYLON || (BABYLON = {}));
  11970. var BABYLON;
  11971. (function (BABYLON) {
  11972. var Particle = (function () {
  11973. function Particle() {
  11974. this.position = BABYLON.Vector3.Zero();
  11975. this.direction = BABYLON.Vector3.Zero();
  11976. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11977. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11978. this.lifeTime = 1.0;
  11979. this.age = 0;
  11980. this.size = 0;
  11981. this.angle = 0;
  11982. this.angularSpeed = 0;
  11983. }
  11984. return Particle;
  11985. })();
  11986. BABYLON.Particle = Particle;
  11987. })(BABYLON || (BABYLON = {}));
  11988. var BABYLON;
  11989. (function (BABYLON) {
  11990. var randomNumber = function (min, max) {
  11991. if (min == max) {
  11992. return (min);
  11993. }
  11994. var random = Math.random();
  11995. return ((random * (max - min)) + min);
  11996. };
  11997. var ParticleSystem = (function () {
  11998. function ParticleSystem(name, capacity, scene, customEffect) {
  11999. var _this = this;
  12000. this.name = name;
  12001. this.renderingGroupId = 0;
  12002. this.emitter = null;
  12003. this.emitRate = 10;
  12004. this.manualEmitCount = -1;
  12005. this.updateSpeed = 0.01;
  12006. this.targetStopDuration = 0;
  12007. this.disposeOnStop = false;
  12008. this.minEmitPower = 1;
  12009. this.maxEmitPower = 1;
  12010. this.minLifeTime = 1;
  12011. this.maxLifeTime = 1;
  12012. this.minSize = 1;
  12013. this.maxSize = 1;
  12014. this.minAngularSpeed = 0;
  12015. this.maxAngularSpeed = 0;
  12016. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12017. this.forceDepthWrite = false;
  12018. this.gravity = BABYLON.Vector3.Zero();
  12019. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12020. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12021. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12022. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12023. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12024. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12025. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12026. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12027. this.particles = new Array();
  12028. this._vertexDeclaration = [3, 4, 4];
  12029. this._vertexStrideSize = 11 * 4;
  12030. this._stockParticles = new Array();
  12031. this._newPartsExcess = 0;
  12032. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12033. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12034. this._scaledDirection = BABYLON.Vector3.Zero();
  12035. this._scaledGravity = BABYLON.Vector3.Zero();
  12036. this._currentRenderId = -1;
  12037. this._started = false;
  12038. this._stopped = false;
  12039. this._actualFrame = 0;
  12040. this.id = name;
  12041. this._capacity = capacity;
  12042. this._scene = scene;
  12043. this._customEffect = customEffect;
  12044. scene.particleSystems.push(this);
  12045. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12046. var indices = [];
  12047. var index = 0;
  12048. for (var count = 0; count < capacity; count++) {
  12049. indices.push(index);
  12050. indices.push(index + 1);
  12051. indices.push(index + 2);
  12052. indices.push(index);
  12053. indices.push(index + 2);
  12054. indices.push(index + 3);
  12055. index += 4;
  12056. }
  12057. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12058. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12059. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12060. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12061. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12062. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12063. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12064. };
  12065. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12066. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12067. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12068. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12069. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12070. };
  12071. }
  12072. ParticleSystem.prototype.getCapacity = function () {
  12073. return this._capacity;
  12074. };
  12075. ParticleSystem.prototype.isAlive = function () {
  12076. return this._alive;
  12077. };
  12078. ParticleSystem.prototype.isStarted = function () {
  12079. return this._started;
  12080. };
  12081. ParticleSystem.prototype.start = function () {
  12082. this._started = true;
  12083. this._stopped = false;
  12084. this._actualFrame = 0;
  12085. };
  12086. ParticleSystem.prototype.stop = function () {
  12087. this._stopped = true;
  12088. };
  12089. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12090. var offset = index * 11;
  12091. this._vertices[offset] = particle.position.x;
  12092. this._vertices[offset + 1] = particle.position.y;
  12093. this._vertices[offset + 2] = particle.position.z;
  12094. this._vertices[offset + 3] = particle.color.r;
  12095. this._vertices[offset + 4] = particle.color.g;
  12096. this._vertices[offset + 5] = particle.color.b;
  12097. this._vertices[offset + 6] = particle.color.a;
  12098. this._vertices[offset + 7] = particle.angle;
  12099. this._vertices[offset + 8] = particle.size;
  12100. this._vertices[offset + 9] = offsetX;
  12101. this._vertices[offset + 10] = offsetY;
  12102. };
  12103. ParticleSystem.prototype._update = function (newParticles) {
  12104. this._alive = this.particles.length > 0;
  12105. for (var index = 0; index < this.particles.length; index++) {
  12106. var particle = this.particles[index];
  12107. particle.age += this._scaledUpdateSpeed;
  12108. if (particle.age >= particle.lifeTime) {
  12109. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12110. index--;
  12111. continue;
  12112. } else {
  12113. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12114. particle.color.addInPlace(this._scaledColorStep);
  12115. if (particle.color.a < 0)
  12116. particle.color.a = 0;
  12117. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12118. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12119. particle.position.addInPlace(this._scaledDirection);
  12120. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12121. particle.direction.addInPlace(this._scaledGravity);
  12122. }
  12123. }
  12124. var worldMatrix;
  12125. if (this.emitter.position) {
  12126. worldMatrix = this.emitter.getWorldMatrix();
  12127. } else {
  12128. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12129. }
  12130. for (index = 0; index < newParticles; index++) {
  12131. if (this.particles.length == this._capacity) {
  12132. break;
  12133. }
  12134. if (this._stockParticles.length !== 0) {
  12135. particle = this._stockParticles.pop();
  12136. particle.age = 0;
  12137. } else {
  12138. particle = new BABYLON.Particle();
  12139. }
  12140. this.particles.push(particle);
  12141. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12142. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12143. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12144. particle.size = randomNumber(this.minSize, this.maxSize);
  12145. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12146. this.startPositionFunction(worldMatrix, particle.position);
  12147. var step = randomNumber(0, 1.0);
  12148. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12149. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12150. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12151. }
  12152. };
  12153. ParticleSystem.prototype._getEffect = function () {
  12154. if (this._customEffect) {
  12155. return this._customEffect;
  12156. }
  12157. ;
  12158. var defines = [];
  12159. if (this._scene.clipPlane) {
  12160. defines.push("#define CLIPPLANE");
  12161. }
  12162. var join = defines.join("\n");
  12163. if (this._cachedDefines != join) {
  12164. this._cachedDefines = join;
  12165. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12166. }
  12167. return this._effect;
  12168. };
  12169. ParticleSystem.prototype.animate = function () {
  12170. if (!this._started)
  12171. return;
  12172. var effect = this._getEffect();
  12173. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12174. return;
  12175. if (this._currentRenderId === this._scene.getRenderId()) {
  12176. return;
  12177. }
  12178. this._currentRenderId = this._scene.getRenderId();
  12179. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12180. var emitCout;
  12181. if (this.manualEmitCount > -1) {
  12182. emitCout = this.manualEmitCount;
  12183. this.manualEmitCount = 0;
  12184. } else {
  12185. emitCout = this.emitRate;
  12186. }
  12187. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12188. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12189. if (this._newPartsExcess > 1.0) {
  12190. newParticles += this._newPartsExcess >> 0;
  12191. this._newPartsExcess -= this._newPartsExcess >> 0;
  12192. }
  12193. this._alive = false;
  12194. if (!this._stopped) {
  12195. this._actualFrame += this._scaledUpdateSpeed;
  12196. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12197. this.stop();
  12198. } else {
  12199. newParticles = 0;
  12200. }
  12201. this._update(newParticles);
  12202. if (this._stopped) {
  12203. if (!this._alive) {
  12204. this._started = false;
  12205. if (this.disposeOnStop) {
  12206. this._scene._toBeDisposed.push(this);
  12207. }
  12208. }
  12209. }
  12210. var offset = 0;
  12211. for (var index = 0; index < this.particles.length; index++) {
  12212. var particle = this.particles[index];
  12213. this._appendParticleVertex(offset++, particle, 0, 0);
  12214. this._appendParticleVertex(offset++, particle, 1, 0);
  12215. this._appendParticleVertex(offset++, particle, 1, 1);
  12216. this._appendParticleVertex(offset++, particle, 0, 1);
  12217. }
  12218. var engine = this._scene.getEngine();
  12219. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12220. };
  12221. ParticleSystem.prototype.render = function () {
  12222. var effect = this._getEffect();
  12223. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12224. return 0;
  12225. var engine = this._scene.getEngine();
  12226. engine.enableEffect(effect);
  12227. var viewMatrix = this._scene.getViewMatrix();
  12228. effect.setTexture("diffuseSampler", this.particleTexture);
  12229. effect.setMatrix("view", viewMatrix);
  12230. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12231. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12232. if (this._scene.clipPlane) {
  12233. var clipPlane = this._scene.clipPlane;
  12234. var invView = viewMatrix.clone();
  12235. invView.invert();
  12236. effect.setMatrix("invView", invView);
  12237. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12238. }
  12239. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12240. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12241. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12242. } else {
  12243. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12244. }
  12245. if (this.forceDepthWrite) {
  12246. engine.setDepthWrite(true);
  12247. }
  12248. engine.draw(true, 0, this.particles.length * 6);
  12249. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12250. return this.particles.length;
  12251. };
  12252. ParticleSystem.prototype.dispose = function () {
  12253. if (this._vertexBuffer) {
  12254. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12255. this._vertexBuffer = null;
  12256. }
  12257. if (this._indexBuffer) {
  12258. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12259. this._indexBuffer = null;
  12260. }
  12261. if (this.particleTexture) {
  12262. this.particleTexture.dispose();
  12263. this.particleTexture = null;
  12264. }
  12265. var index = this._scene.particleSystems.indexOf(this);
  12266. this._scene.particleSystems.splice(index, 1);
  12267. if (this.onDispose) {
  12268. this.onDispose();
  12269. }
  12270. };
  12271. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12272. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12273. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12274. if (newEmitter === undefined) {
  12275. newEmitter = this.emitter;
  12276. }
  12277. result.emitter = newEmitter;
  12278. if (this.particleTexture) {
  12279. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12280. }
  12281. result.start();
  12282. return result;
  12283. };
  12284. ParticleSystem.BLENDMODE_ONEONE = 0;
  12285. ParticleSystem.BLENDMODE_STANDARD = 1;
  12286. return ParticleSystem;
  12287. })();
  12288. BABYLON.ParticleSystem = ParticleSystem;
  12289. })(BABYLON || (BABYLON = {}));
  12290. var BABYLON;
  12291. (function (BABYLON) {
  12292. var Animation = (function () {
  12293. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12294. this.name = name;
  12295. this.targetProperty = targetProperty;
  12296. this.framePerSecond = framePerSecond;
  12297. this.dataType = dataType;
  12298. this.loopMode = loopMode;
  12299. this._offsetsCache = {};
  12300. this._highLimitsCache = {};
  12301. this._stopped = false;
  12302. this.targetPropertyPath = targetProperty.split(".");
  12303. this.dataType = dataType;
  12304. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12305. }
  12306. Animation.prototype.isStopped = function () {
  12307. return this._stopped;
  12308. };
  12309. Animation.prototype.getKeys = function () {
  12310. return this._keys;
  12311. };
  12312. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12313. return startValue + (endValue - startValue) * gradient;
  12314. };
  12315. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12316. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12317. };
  12318. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12319. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12320. };
  12321. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12322. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12323. };
  12324. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12325. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12326. };
  12327. Animation.prototype.clone = function () {
  12328. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12329. clone.setKeys(this._keys);
  12330. return clone;
  12331. };
  12332. Animation.prototype.setKeys = function (values) {
  12333. this._keys = values.slice(0);
  12334. this._offsetsCache = {};
  12335. this._highLimitsCache = {};
  12336. };
  12337. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12338. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12339. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12340. }
  12341. this.currentFrame = currentFrame;
  12342. for (var key = 0; key < this._keys.length; key++) {
  12343. if (this._keys[key + 1].frame >= currentFrame) {
  12344. var startValue = this._keys[key].value;
  12345. var endValue = this._keys[key + 1].value;
  12346. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12347. switch (this.dataType) {
  12348. case Animation.ANIMATIONTYPE_FLOAT:
  12349. switch (loopMode) {
  12350. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12351. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12352. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12353. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12354. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12355. }
  12356. break;
  12357. case Animation.ANIMATIONTYPE_QUATERNION:
  12358. var quaternion = null;
  12359. switch (loopMode) {
  12360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12362. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12363. break;
  12364. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12365. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12366. break;
  12367. }
  12368. return quaternion;
  12369. case Animation.ANIMATIONTYPE_VECTOR3:
  12370. switch (loopMode) {
  12371. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12372. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12373. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12374. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12375. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12376. }
  12377. case Animation.ANIMATIONTYPE_VECTOR2:
  12378. switch (loopMode) {
  12379. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12380. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12381. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12382. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12383. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12384. }
  12385. case Animation.ANIMATIONTYPE_COLOR3:
  12386. switch (loopMode) {
  12387. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12388. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12389. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12390. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12391. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12392. }
  12393. case Animation.ANIMATIONTYPE_MATRIX:
  12394. switch (loopMode) {
  12395. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12396. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12397. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12398. return startValue;
  12399. }
  12400. default:
  12401. break;
  12402. }
  12403. break;
  12404. }
  12405. }
  12406. return this._keys[this._keys.length - 1].value;
  12407. };
  12408. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12409. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12410. this._stopped = true;
  12411. return false;
  12412. }
  12413. var returnValue = true;
  12414. if (this._keys[0].frame != 0) {
  12415. var newKey = {
  12416. frame: 0,
  12417. value: this._keys[0].value
  12418. };
  12419. this._keys.splice(0, 0, newKey);
  12420. }
  12421. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12422. from = this._keys[0].frame;
  12423. }
  12424. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12425. to = this._keys[this._keys.length - 1].frame;
  12426. }
  12427. var range = to - from;
  12428. var offsetValue;
  12429. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12430. if (ratio > range && !loop) {
  12431. returnValue = false;
  12432. highLimitValue = this._keys[this._keys.length - 1].value;
  12433. } else {
  12434. var highLimitValue = 0;
  12435. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12436. var keyOffset = to.toString() + from.toString();
  12437. if (!this._offsetsCache[keyOffset]) {
  12438. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12439. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12440. switch (this.dataType) {
  12441. case Animation.ANIMATIONTYPE_FLOAT:
  12442. this._offsetsCache[keyOffset] = toValue - fromValue;
  12443. break;
  12444. case Animation.ANIMATIONTYPE_QUATERNION:
  12445. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12446. break;
  12447. case Animation.ANIMATIONTYPE_VECTOR3:
  12448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12449. case Animation.ANIMATIONTYPE_VECTOR2:
  12450. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12451. case Animation.ANIMATIONTYPE_COLOR3:
  12452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12453. default:
  12454. break;
  12455. }
  12456. this._highLimitsCache[keyOffset] = toValue;
  12457. }
  12458. highLimitValue = this._highLimitsCache[keyOffset];
  12459. offsetValue = this._offsetsCache[keyOffset];
  12460. }
  12461. }
  12462. if (offsetValue === undefined) {
  12463. switch (this.dataType) {
  12464. case Animation.ANIMATIONTYPE_FLOAT:
  12465. offsetValue = 0;
  12466. break;
  12467. case Animation.ANIMATIONTYPE_QUATERNION:
  12468. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12469. break;
  12470. case Animation.ANIMATIONTYPE_VECTOR3:
  12471. offsetValue = BABYLON.Vector3.Zero();
  12472. break;
  12473. case Animation.ANIMATIONTYPE_VECTOR2:
  12474. offsetValue = BABYLON.Vector2.Zero();
  12475. break;
  12476. case Animation.ANIMATIONTYPE_COLOR3:
  12477. offsetValue = BABYLON.Color3.Black();
  12478. }
  12479. }
  12480. var repeatCount = (ratio / range) >> 0;
  12481. var currentFrame = returnValue ? from + ratio % range : to;
  12482. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12483. if (this.targetPropertyPath.length > 1) {
  12484. var property = this._target[this.targetPropertyPath[0]];
  12485. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12486. property = property[this.targetPropertyPath[index]];
  12487. }
  12488. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12489. } else {
  12490. this._target[this.targetPropertyPath[0]] = currentValue;
  12491. }
  12492. if (this._target.markAsDirty) {
  12493. this._target.markAsDirty(this.targetProperty);
  12494. }
  12495. if (!returnValue) {
  12496. this._stopped = true;
  12497. }
  12498. return returnValue;
  12499. };
  12500. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12501. get: function () {
  12502. return Animation._ANIMATIONTYPE_FLOAT;
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12508. get: function () {
  12509. return Animation._ANIMATIONTYPE_VECTOR3;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12515. get: function () {
  12516. return Animation._ANIMATIONTYPE_VECTOR2;
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12522. get: function () {
  12523. return Animation._ANIMATIONTYPE_QUATERNION;
  12524. },
  12525. enumerable: true,
  12526. configurable: true
  12527. });
  12528. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12529. get: function () {
  12530. return Animation._ANIMATIONTYPE_MATRIX;
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12536. get: function () {
  12537. return Animation._ANIMATIONTYPE_COLOR3;
  12538. },
  12539. enumerable: true,
  12540. configurable: true
  12541. });
  12542. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12543. get: function () {
  12544. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12545. },
  12546. enumerable: true,
  12547. configurable: true
  12548. });
  12549. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12550. get: function () {
  12551. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12557. get: function () {
  12558. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. Animation._ANIMATIONTYPE_FLOAT = 0;
  12564. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12565. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12566. Animation._ANIMATIONTYPE_MATRIX = 3;
  12567. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12568. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12569. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12570. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12571. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12572. return Animation;
  12573. })();
  12574. BABYLON.Animation = Animation;
  12575. })(BABYLON || (BABYLON = {}));
  12576. var BABYLON;
  12577. (function (BABYLON) {
  12578. var Animatable = (function () {
  12579. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12580. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12581. if (typeof toFrame === "undefined") { toFrame = 100; }
  12582. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12583. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12584. this.target = target;
  12585. this.fromFrame = fromFrame;
  12586. this.toFrame = toFrame;
  12587. this.loopAnimation = loopAnimation;
  12588. this.speedRatio = speedRatio;
  12589. this.onAnimationEnd = onAnimationEnd;
  12590. this._animations = new Array();
  12591. this._paused = false;
  12592. this.animationStarted = false;
  12593. if (animations) {
  12594. this.appendAnimations(target, animations);
  12595. }
  12596. this._scene = scene;
  12597. scene._activeAnimatables.push(this);
  12598. }
  12599. Animatable.prototype.appendAnimations = function (target, animations) {
  12600. for (var index = 0; index < animations.length; index++) {
  12601. var animation = animations[index];
  12602. animation._target = target;
  12603. this._animations.push(animation);
  12604. }
  12605. };
  12606. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12607. var animations = this._animations;
  12608. for (var index = 0; index < animations.length; index++) {
  12609. if (animations[index].targetProperty === property) {
  12610. return animations[index];
  12611. }
  12612. }
  12613. return null;
  12614. };
  12615. Animatable.prototype.pause = function () {
  12616. if (this._paused) {
  12617. return;
  12618. }
  12619. this._paused = true;
  12620. };
  12621. Animatable.prototype.restart = function () {
  12622. this._paused = false;
  12623. };
  12624. Animatable.prototype.stop = function () {
  12625. var index = this._scene._activeAnimatables.indexOf(this);
  12626. if (index > -1) {
  12627. this._scene._activeAnimatables.splice(index, 1);
  12628. }
  12629. if (this.onAnimationEnd) {
  12630. this.onAnimationEnd();
  12631. }
  12632. };
  12633. Animatable.prototype._animate = function (delay) {
  12634. if (this._paused) {
  12635. if (!this._pausedDelay) {
  12636. this._pausedDelay = delay;
  12637. }
  12638. return true;
  12639. }
  12640. if (!this._localDelayOffset) {
  12641. this._localDelayOffset = delay;
  12642. } else if (this._pausedDelay) {
  12643. this._localDelayOffset += delay - this._pausedDelay;
  12644. this._pausedDelay = null;
  12645. }
  12646. var running = false;
  12647. var animations = this._animations;
  12648. for (var index = 0; index < animations.length; index++) {
  12649. var animation = animations[index];
  12650. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12651. running = running || isRunning;
  12652. }
  12653. if (!running && this.onAnimationEnd) {
  12654. this.onAnimationEnd();
  12655. }
  12656. return running;
  12657. };
  12658. return Animatable;
  12659. })();
  12660. BABYLON.Animatable = Animatable;
  12661. })(BABYLON || (BABYLON = {}));
  12662. var BABYLON;
  12663. (function (BABYLON) {
  12664. var Octree = (function () {
  12665. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  12666. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  12667. this.maxDepth = maxDepth;
  12668. this.dynamicContent = new Array();
  12669. this._maxBlockCapacity = maxBlockCapacity || 64;
  12670. this._selectionContent = new BABYLON.SmartArray(1024);
  12671. this._creationFunc = creationFunc;
  12672. }
  12673. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12674. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12675. };
  12676. Octree.prototype.addMesh = function (entry) {
  12677. for (var index = 0; index < this.blocks.length; index++) {
  12678. var block = this.blocks[index];
  12679. block.addEntry(entry);
  12680. }
  12681. };
  12682. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12683. this._selectionContent.reset();
  12684. for (var index = 0; index < this.blocks.length; index++) {
  12685. var block = this.blocks[index];
  12686. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12687. }
  12688. if (allowDuplicate) {
  12689. this._selectionContent.concat(this.dynamicContent);
  12690. } else {
  12691. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12692. }
  12693. return this._selectionContent;
  12694. };
  12695. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12696. this._selectionContent.reset();
  12697. for (var index = 0; index < this.blocks.length; index++) {
  12698. var block = this.blocks[index];
  12699. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12700. }
  12701. if (allowDuplicate) {
  12702. this._selectionContent.concat(this.dynamicContent);
  12703. } else {
  12704. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12705. }
  12706. return this._selectionContent;
  12707. };
  12708. Octree.prototype.intersectsRay = function (ray) {
  12709. this._selectionContent.reset();
  12710. for (var index = 0; index < this.blocks.length; index++) {
  12711. var block = this.blocks[index];
  12712. block.intersectsRay(ray, this._selectionContent);
  12713. }
  12714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12715. return this._selectionContent;
  12716. };
  12717. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12718. target.blocks = new Array();
  12719. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12720. for (var x = 0; x < 2; x++) {
  12721. for (var y = 0; y < 2; y++) {
  12722. for (var z = 0; z < 2; z++) {
  12723. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12724. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12725. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12726. block.addEntries(entries);
  12727. target.blocks.push(block);
  12728. }
  12729. }
  12730. }
  12731. };
  12732. Octree.CreationFuncForMeshes = function (entry, block) {
  12733. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12734. block.entries.push(entry);
  12735. }
  12736. };
  12737. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12738. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12739. block.entries.push(entry);
  12740. }
  12741. };
  12742. return Octree;
  12743. })();
  12744. BABYLON.Octree = Octree;
  12745. })(BABYLON || (BABYLON = {}));
  12746. var BABYLON;
  12747. (function (BABYLON) {
  12748. var OctreeBlock = (function () {
  12749. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12750. this.entries = new Array();
  12751. this._boundingVectors = new Array();
  12752. this._capacity = capacity;
  12753. this._depth = depth;
  12754. this._maxDepth = maxDepth;
  12755. this._creationFunc = creationFunc;
  12756. this._minPoint = minPoint;
  12757. this._maxPoint = maxPoint;
  12758. this._boundingVectors.push(minPoint.clone());
  12759. this._boundingVectors.push(maxPoint.clone());
  12760. this._boundingVectors.push(minPoint.clone());
  12761. this._boundingVectors[2].x = maxPoint.x;
  12762. this._boundingVectors.push(minPoint.clone());
  12763. this._boundingVectors[3].y = maxPoint.y;
  12764. this._boundingVectors.push(minPoint.clone());
  12765. this._boundingVectors[4].z = maxPoint.z;
  12766. this._boundingVectors.push(maxPoint.clone());
  12767. this._boundingVectors[5].z = minPoint.z;
  12768. this._boundingVectors.push(maxPoint.clone());
  12769. this._boundingVectors[6].x = minPoint.x;
  12770. this._boundingVectors.push(maxPoint.clone());
  12771. this._boundingVectors[7].y = minPoint.y;
  12772. }
  12773. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12774. get: function () {
  12775. return this._capacity;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12781. get: function () {
  12782. return this._minPoint;
  12783. },
  12784. enumerable: true,
  12785. configurable: true
  12786. });
  12787. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12788. get: function () {
  12789. return this._maxPoint;
  12790. },
  12791. enumerable: true,
  12792. configurable: true
  12793. });
  12794. OctreeBlock.prototype.addEntry = function (entry) {
  12795. if (this.blocks) {
  12796. for (var index = 0; index < this.blocks.length; index++) {
  12797. var block = this.blocks[index];
  12798. block.addEntry(entry);
  12799. }
  12800. return;
  12801. }
  12802. this._creationFunc(entry, this);
  12803. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12804. this.createInnerBlocks();
  12805. }
  12806. };
  12807. OctreeBlock.prototype.addEntries = function (entries) {
  12808. for (var index = 0; index < entries.length; index++) {
  12809. var mesh = entries[index];
  12810. this.addEntry(mesh);
  12811. }
  12812. };
  12813. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12814. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12815. if (this.blocks) {
  12816. for (var index = 0; index < this.blocks.length; index++) {
  12817. var block = this.blocks[index];
  12818. block.select(frustumPlanes, selection, allowDuplicate);
  12819. }
  12820. return;
  12821. }
  12822. if (allowDuplicate) {
  12823. selection.concat(this.entries);
  12824. } else {
  12825. selection.concatWithNoDuplicate(this.entries);
  12826. }
  12827. }
  12828. };
  12829. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12830. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12831. if (this.blocks) {
  12832. for (var index = 0; index < this.blocks.length; index++) {
  12833. var block = this.blocks[index];
  12834. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12835. }
  12836. return;
  12837. }
  12838. if (allowDuplicate) {
  12839. selection.concat(this.entries);
  12840. } else {
  12841. selection.concatWithNoDuplicate(this.entries);
  12842. }
  12843. }
  12844. };
  12845. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12846. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12847. if (this.blocks) {
  12848. for (var index = 0; index < this.blocks.length; index++) {
  12849. var block = this.blocks[index];
  12850. block.intersectsRay(ray, selection);
  12851. }
  12852. return;
  12853. }
  12854. selection.concatWithNoDuplicate(this.entries);
  12855. }
  12856. };
  12857. OctreeBlock.prototype.createInnerBlocks = function () {
  12858. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12859. };
  12860. return OctreeBlock;
  12861. })();
  12862. BABYLON.OctreeBlock = OctreeBlock;
  12863. })(BABYLON || (BABYLON = {}));
  12864. var BABYLON;
  12865. (function (BABYLON) {
  12866. var Bone = (function () {
  12867. function Bone(name, skeleton, parentBone, matrix) {
  12868. this.name = name;
  12869. this.children = new Array();
  12870. this.animations = new Array();
  12871. this._worldTransform = new BABYLON.Matrix();
  12872. this._absoluteTransform = new BABYLON.Matrix();
  12873. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12874. this._skeleton = skeleton;
  12875. this._matrix = matrix;
  12876. this._baseMatrix = matrix;
  12877. skeleton.bones.push(this);
  12878. if (parentBone) {
  12879. this._parent = parentBone;
  12880. parentBone.children.push(this);
  12881. } else {
  12882. this._parent = null;
  12883. }
  12884. this._updateDifferenceMatrix();
  12885. }
  12886. Bone.prototype.getParent = function () {
  12887. return this._parent;
  12888. };
  12889. Bone.prototype.getLocalMatrix = function () {
  12890. return this._matrix;
  12891. };
  12892. Bone.prototype.getBaseMatrix = function () {
  12893. return this._baseMatrix;
  12894. };
  12895. Bone.prototype.getWorldMatrix = function () {
  12896. return this._worldTransform;
  12897. };
  12898. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12899. return this._invertedAbsoluteTransform;
  12900. };
  12901. Bone.prototype.getAbsoluteMatrix = function () {
  12902. var matrix = this._matrix.clone();
  12903. var parent = this._parent;
  12904. while (parent) {
  12905. matrix = matrix.multiply(parent.getLocalMatrix());
  12906. parent = parent.getParent();
  12907. }
  12908. return matrix;
  12909. };
  12910. Bone.prototype.updateMatrix = function (matrix) {
  12911. this._matrix = matrix;
  12912. this._skeleton._markAsDirty();
  12913. this._updateDifferenceMatrix();
  12914. };
  12915. Bone.prototype._updateDifferenceMatrix = function () {
  12916. if (this._parent) {
  12917. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12918. } else {
  12919. this._absoluteTransform.copyFrom(this._matrix);
  12920. }
  12921. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12922. for (var index = 0; index < this.children.length; index++) {
  12923. this.children[index]._updateDifferenceMatrix();
  12924. }
  12925. };
  12926. Bone.prototype.markAsDirty = function () {
  12927. this._skeleton._markAsDirty();
  12928. };
  12929. return Bone;
  12930. })();
  12931. BABYLON.Bone = Bone;
  12932. })(BABYLON || (BABYLON = {}));
  12933. var BABYLON;
  12934. (function (BABYLON) {
  12935. var Skeleton = (function () {
  12936. function Skeleton(name, id, scene) {
  12937. this.name = name;
  12938. this.id = id;
  12939. this.bones = new Array();
  12940. this._isDirty = true;
  12941. this._identity = BABYLON.Matrix.Identity();
  12942. this.bones = [];
  12943. this._scene = scene;
  12944. scene.skeletons.push(this);
  12945. }
  12946. Skeleton.prototype.getTransformMatrices = function () {
  12947. return this._transformMatrices;
  12948. };
  12949. Skeleton.prototype._markAsDirty = function () {
  12950. this._isDirty = true;
  12951. };
  12952. Skeleton.prototype.prepare = function () {
  12953. if (!this._isDirty) {
  12954. return;
  12955. }
  12956. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12957. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12958. }
  12959. for (var index = 0; index < this.bones.length; index++) {
  12960. var bone = this.bones[index];
  12961. var parentBone = bone.getParent();
  12962. if (parentBone) {
  12963. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12964. } else {
  12965. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12966. }
  12967. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12968. }
  12969. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12970. this._isDirty = false;
  12971. };
  12972. Skeleton.prototype.getAnimatables = function () {
  12973. if (!this._animatables || this._animatables.length != this.bones.length) {
  12974. this._animatables = [];
  12975. for (var index = 0; index < this.bones.length; index++) {
  12976. this._animatables.push(this.bones[index]);
  12977. }
  12978. }
  12979. return this._animatables;
  12980. };
  12981. Skeleton.prototype.clone = function (name, id) {
  12982. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12983. for (var index = 0; index < this.bones.length; index++) {
  12984. var source = this.bones[index];
  12985. var parentBone = null;
  12986. if (source.getParent()) {
  12987. var parentIndex = this.bones.indexOf(source.getParent());
  12988. parentBone = result.bones[parentIndex];
  12989. }
  12990. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12991. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12992. }
  12993. return result;
  12994. };
  12995. return Skeleton;
  12996. })();
  12997. BABYLON.Skeleton = Skeleton;
  12998. })(BABYLON || (BABYLON = {}));
  12999. var BABYLON;
  13000. (function (BABYLON) {
  13001. var PostProcess = (function () {
  13002. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13003. this.name = name;
  13004. this.width = -1;
  13005. this.height = -1;
  13006. this._reusable = false;
  13007. this._textures = new BABYLON.SmartArray(2);
  13008. this._currentRenderTextureInd = 0;
  13009. if (camera != null) {
  13010. this._camera = camera;
  13011. this._scene = camera.getScene();
  13012. camera.attachPostProcess(this);
  13013. this._engine = this._scene.getEngine();
  13014. } else {
  13015. this._engine = engine;
  13016. }
  13017. this._renderRatio = ratio;
  13018. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13019. this._reusable = reusable || false;
  13020. samplers = samplers || [];
  13021. samplers.push("textureSampler");
  13022. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13023. }
  13024. PostProcess.prototype.isReusable = function () {
  13025. return this._reusable;
  13026. };
  13027. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13028. camera = camera || this._camera;
  13029. var scene = camera.getScene();
  13030. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13031. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13032. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13033. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13034. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13035. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13036. if (this._textures.length > 0) {
  13037. for (var i = 0; i < this._textures.length; i++) {
  13038. this._engine._releaseTexture(this._textures.data[i]);
  13039. }
  13040. this._textures.reset();
  13041. }
  13042. this.width = desiredWidth;
  13043. this.height = desiredHeight;
  13044. 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 }));
  13045. if (this._reusable) {
  13046. 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 }));
  13047. }
  13048. if (this.onSizeChanged) {
  13049. this.onSizeChanged();
  13050. }
  13051. }
  13052. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13053. if (this.onActivate) {
  13054. this.onActivate(camera);
  13055. }
  13056. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13057. if (this._reusable) {
  13058. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13059. }
  13060. };
  13061. PostProcess.prototype.apply = function () {
  13062. if (!this._effect.isReady())
  13063. return null;
  13064. this._engine.enableEffect(this._effect);
  13065. this._engine.setState(false);
  13066. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13067. this._engine.setDepthBuffer(false);
  13068. this._engine.setDepthWrite(false);
  13069. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13070. if (this.onApply) {
  13071. this.onApply(this._effect);
  13072. }
  13073. return this._effect;
  13074. };
  13075. PostProcess.prototype.dispose = function (camera) {
  13076. camera = camera || this._camera;
  13077. if (this._textures.length > 0) {
  13078. for (var i = 0; i < this._textures.length; i++) {
  13079. this._engine._releaseTexture(this._textures.data[i]);
  13080. }
  13081. this._textures.reset();
  13082. }
  13083. camera.detachPostProcess(this);
  13084. var index = camera._postProcesses.indexOf(this);
  13085. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13086. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13087. }
  13088. };
  13089. return PostProcess;
  13090. })();
  13091. BABYLON.PostProcess = PostProcess;
  13092. })(BABYLON || (BABYLON = {}));
  13093. var BABYLON;
  13094. (function (BABYLON) {
  13095. var PostProcessManager = (function () {
  13096. function PostProcessManager(scene) {
  13097. this._vertexDeclaration = [2];
  13098. this._vertexStrideSize = 2 * 4;
  13099. this._scene = scene;
  13100. var vertices = [];
  13101. vertices.push(1, 1);
  13102. vertices.push(-1, 1);
  13103. vertices.push(-1, -1);
  13104. vertices.push(1, -1);
  13105. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13106. var indices = [];
  13107. indices.push(0);
  13108. indices.push(1);
  13109. indices.push(2);
  13110. indices.push(0);
  13111. indices.push(2);
  13112. indices.push(3);
  13113. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13114. }
  13115. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13116. var postProcesses = this._scene.activeCamera._postProcesses;
  13117. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13118. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13119. return false;
  13120. }
  13121. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13122. return true;
  13123. };
  13124. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13125. var postProcesses = this._scene.activeCamera._postProcesses;
  13126. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13127. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13128. return;
  13129. }
  13130. var engine = this._scene.getEngine();
  13131. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13132. if (index < postProcessesTakenIndices.length - 1) {
  13133. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13134. } else {
  13135. if (targetTexture) {
  13136. engine.bindFramebuffer(targetTexture);
  13137. } else {
  13138. engine.restoreDefaultFramebuffer();
  13139. }
  13140. }
  13141. if (doNotPresent) {
  13142. break;
  13143. }
  13144. var pp = postProcesses[postProcessesTakenIndices[index]];
  13145. var effect = pp.apply();
  13146. if (effect) {
  13147. if (pp.onBeforeRender) {
  13148. pp.onBeforeRender(effect);
  13149. }
  13150. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13151. engine.draw(true, 0, 6);
  13152. }
  13153. }
  13154. engine.setDepthBuffer(true);
  13155. engine.setDepthWrite(true);
  13156. };
  13157. PostProcessManager.prototype.dispose = function () {
  13158. if (this._vertexBuffer) {
  13159. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13160. this._vertexBuffer = null;
  13161. }
  13162. if (this._indexBuffer) {
  13163. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13164. this._indexBuffer = null;
  13165. }
  13166. };
  13167. return PostProcessManager;
  13168. })();
  13169. BABYLON.PostProcessManager = PostProcessManager;
  13170. })(BABYLON || (BABYLON = {}));
  13171. var __extends = this.__extends || function (d, b) {
  13172. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13173. function __() { this.constructor = d; }
  13174. __.prototype = b.prototype;
  13175. d.prototype = new __();
  13176. };
  13177. var BABYLON;
  13178. (function (BABYLON) {
  13179. var PassPostProcess = (function (_super) {
  13180. __extends(PassPostProcess, _super);
  13181. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13182. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13183. }
  13184. return PassPostProcess;
  13185. })(BABYLON.PostProcess);
  13186. BABYLON.PassPostProcess = PassPostProcess;
  13187. })(BABYLON || (BABYLON = {}));
  13188. var __extends = this.__extends || function (d, b) {
  13189. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13190. function __() { this.constructor = d; }
  13191. __.prototype = b.prototype;
  13192. d.prototype = new __();
  13193. };
  13194. var BABYLON;
  13195. (function (BABYLON) {
  13196. var BlurPostProcess = (function (_super) {
  13197. __extends(BlurPostProcess, _super);
  13198. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13199. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13200. var _this = this;
  13201. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13202. this.direction = direction;
  13203. this.blurWidth = blurWidth;
  13204. this.onApply = function (effect) {
  13205. effect.setFloat2("screenSize", _this.width, _this.height);
  13206. effect.setVector2("direction", _this.direction);
  13207. effect.setFloat("blurWidth", _this.blurWidth);
  13208. };
  13209. }
  13210. return BlurPostProcess;
  13211. })(BABYLON.PostProcess);
  13212. BABYLON.BlurPostProcess = BlurPostProcess;
  13213. })(BABYLON || (BABYLON = {}));
  13214. var __extends = this.__extends || function (d, b) {
  13215. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13216. function __() { this.constructor = d; }
  13217. __.prototype = b.prototype;
  13218. d.prototype = new __();
  13219. };
  13220. var BABYLON;
  13221. (function (BABYLON) {
  13222. var FilterPostProcess = (function (_super) {
  13223. __extends(FilterPostProcess, _super);
  13224. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13225. var _this = this;
  13226. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13227. this.kernelMatrix = kernelMatrix;
  13228. this.onApply = function (effect) {
  13229. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13230. };
  13231. }
  13232. return FilterPostProcess;
  13233. })(BABYLON.PostProcess);
  13234. BABYLON.FilterPostProcess = FilterPostProcess;
  13235. })(BABYLON || (BABYLON = {}));
  13236. var __extends = this.__extends || function (d, b) {
  13237. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13238. function __() { this.constructor = d; }
  13239. __.prototype = b.prototype;
  13240. d.prototype = new __();
  13241. };
  13242. var BABYLON;
  13243. (function (BABYLON) {
  13244. var RefractionPostProcess = (function (_super) {
  13245. __extends(RefractionPostProcess, _super);
  13246. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13247. var _this = this;
  13248. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13249. this.color = color;
  13250. this.depth = depth;
  13251. this.colorLevel = colorLevel;
  13252. this.onActivate = function (cam) {
  13253. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13254. };
  13255. this.onApply = function (effect) {
  13256. effect.setColor3("baseColor", _this.color);
  13257. effect.setFloat("depth", _this.depth);
  13258. effect.setFloat("colorLevel", _this.colorLevel);
  13259. effect.setTexture("refractionSampler", _this._refRexture);
  13260. };
  13261. }
  13262. RefractionPostProcess.prototype.dispose = function (camera) {
  13263. if (this._refRexture) {
  13264. this._refRexture.dispose();
  13265. }
  13266. _super.prototype.dispose.call(this, camera);
  13267. };
  13268. return RefractionPostProcess;
  13269. })(BABYLON.PostProcess);
  13270. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13271. })(BABYLON || (BABYLON = {}));
  13272. var __extends = this.__extends || function (d, b) {
  13273. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13274. function __() { this.constructor = d; }
  13275. __.prototype = b.prototype;
  13276. d.prototype = new __();
  13277. };
  13278. var BABYLON;
  13279. (function (BABYLON) {
  13280. var BlackAndWhitePostProcess = (function (_super) {
  13281. __extends(BlackAndWhitePostProcess, _super);
  13282. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13283. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13284. }
  13285. return BlackAndWhitePostProcess;
  13286. })(BABYLON.PostProcess);
  13287. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13288. })(BABYLON || (BABYLON = {}));
  13289. var __extends = this.__extends || function (d, b) {
  13290. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13291. function __() { this.constructor = d; }
  13292. __.prototype = b.prototype;
  13293. d.prototype = new __();
  13294. };
  13295. var BABYLON;
  13296. (function (BABYLON) {
  13297. var ConvolutionPostProcess = (function (_super) {
  13298. __extends(ConvolutionPostProcess, _super);
  13299. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13300. var _this = this;
  13301. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13302. this.kernel = kernel;
  13303. this.onApply = function (effect) {
  13304. effect.setFloat2("screenSize", _this.width, _this.height);
  13305. effect.setArray("kernel", _this.kernel);
  13306. };
  13307. }
  13308. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13309. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13310. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13311. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13312. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13313. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13314. return ConvolutionPostProcess;
  13315. })(BABYLON.PostProcess);
  13316. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13317. })(BABYLON || (BABYLON = {}));
  13318. var __extends = this.__extends || function (d, b) {
  13319. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13320. function __() { this.constructor = d; }
  13321. __.prototype = b.prototype;
  13322. d.prototype = new __();
  13323. };
  13324. var BABYLON;
  13325. (function (BABYLON) {
  13326. var FxaaPostProcess = (function (_super) {
  13327. __extends(FxaaPostProcess, _super);
  13328. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13329. var _this = this;
  13330. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13331. this.onSizeChanged = function () {
  13332. _this.texelWidth = 1.0 / _this.width;
  13333. _this.texelHeight = 1.0 / _this.height;
  13334. };
  13335. this.onApply = function (effect) {
  13336. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13337. };
  13338. }
  13339. return FxaaPostProcess;
  13340. })(BABYLON.PostProcess);
  13341. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13342. })(BABYLON || (BABYLON = {}));
  13343. var BABYLON;
  13344. (function (BABYLON) {
  13345. var LensFlare = (function () {
  13346. function LensFlare(size, position, color, imgUrl, system) {
  13347. this.size = size;
  13348. this.position = position;
  13349. this.dispose = function () {
  13350. if (this.texture) {
  13351. this.texture.dispose();
  13352. }
  13353. var index = this._system.lensFlares.indexOf(this);
  13354. this._system.lensFlares.splice(index, 1);
  13355. };
  13356. this.color = color || new BABYLON.Color3(1, 1, 1);
  13357. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13358. this._system = system;
  13359. system.lensFlares.push(this);
  13360. }
  13361. return LensFlare;
  13362. })();
  13363. BABYLON.LensFlare = LensFlare;
  13364. })(BABYLON || (BABYLON = {}));
  13365. var BABYLON;
  13366. (function (BABYLON) {
  13367. var LensFlareSystem = (function () {
  13368. function LensFlareSystem(name, emitter, scene) {
  13369. this.name = name;
  13370. this.lensFlares = new Array();
  13371. this.borderLimit = 300;
  13372. this._vertexDeclaration = [2];
  13373. this._vertexStrideSize = 2 * 4;
  13374. this._isEnabled = true;
  13375. this._scene = scene;
  13376. this._emitter = emitter;
  13377. scene.lensFlareSystems.push(this);
  13378. this.meshesSelectionPredicate = function (m) {
  13379. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13380. };
  13381. var vertices = [];
  13382. vertices.push(1, 1);
  13383. vertices.push(-1, 1);
  13384. vertices.push(-1, -1);
  13385. vertices.push(1, -1);
  13386. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13387. var indices = [];
  13388. indices.push(0);
  13389. indices.push(1);
  13390. indices.push(2);
  13391. indices.push(0);
  13392. indices.push(2);
  13393. indices.push(3);
  13394. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13395. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13396. }
  13397. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13398. get: function () {
  13399. return this._isEnabled;
  13400. },
  13401. set: function (value) {
  13402. this._isEnabled = value;
  13403. },
  13404. enumerable: true,
  13405. configurable: true
  13406. });
  13407. LensFlareSystem.prototype.getScene = function () {
  13408. return this._scene;
  13409. };
  13410. LensFlareSystem.prototype.getEmitter = function () {
  13411. return this._emitter;
  13412. };
  13413. LensFlareSystem.prototype.getEmitterPosition = function () {
  13414. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13415. };
  13416. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13417. var position = this.getEmitterPosition();
  13418. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13419. this._positionX = position.x;
  13420. this._positionY = position.y;
  13421. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13422. if (position.z > 0) {
  13423. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13424. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13425. return true;
  13426. }
  13427. }
  13428. return false;
  13429. };
  13430. LensFlareSystem.prototype._isVisible = function () {
  13431. if (!this._isEnabled) {
  13432. return false;
  13433. }
  13434. var emitterPosition = this.getEmitterPosition();
  13435. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13436. var distance = direction.length();
  13437. direction.normalize();
  13438. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13439. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13440. return !pickInfo.hit || pickInfo.distance > distance;
  13441. };
  13442. LensFlareSystem.prototype.render = function () {
  13443. if (!this._effect.isReady())
  13444. return false;
  13445. var engine = this._scene.getEngine();
  13446. var viewport = this._scene.activeCamera.viewport;
  13447. var globalViewport = viewport.toGlobal(engine);
  13448. if (!this.computeEffectivePosition(globalViewport)) {
  13449. return false;
  13450. }
  13451. if (!this._isVisible()) {
  13452. return false;
  13453. }
  13454. var awayX;
  13455. var awayY;
  13456. if (this._positionX < this.borderLimit + globalViewport.x) {
  13457. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13458. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13459. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13460. } else {
  13461. awayX = 0;
  13462. }
  13463. if (this._positionY < this.borderLimit + globalViewport.y) {
  13464. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13465. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13466. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13467. } else {
  13468. awayY = 0;
  13469. }
  13470. var away = (awayX > awayY) ? awayX : awayY;
  13471. if (away > this.borderLimit) {
  13472. away = this.borderLimit;
  13473. }
  13474. var intensity = 1.0 - (away / this.borderLimit);
  13475. if (intensity < 0) {
  13476. return false;
  13477. }
  13478. if (intensity > 1.0) {
  13479. intensity = 1.0;
  13480. }
  13481. var centerX = globalViewport.x + globalViewport.width / 2;
  13482. var centerY = globalViewport.y + globalViewport.height / 2;
  13483. var distX = centerX - this._positionX;
  13484. var distY = centerY - this._positionY;
  13485. engine.enableEffect(this._effect);
  13486. engine.setState(false);
  13487. engine.setDepthBuffer(false);
  13488. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13489. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13490. for (var index = 0; index < this.lensFlares.length; index++) {
  13491. var flare = this.lensFlares[index];
  13492. var x = centerX - (distX * flare.position);
  13493. var y = centerY - (distY * flare.position);
  13494. var cw = flare.size;
  13495. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13496. var cx = 2 * (x / globalViewport.width) - 1.0;
  13497. var cy = 1.0 - 2 * (y / globalViewport.height);
  13498. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13499. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13500. this._effect.setTexture("textureSampler", flare.texture);
  13501. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13502. engine.draw(true, 0, 6);
  13503. }
  13504. engine.setDepthBuffer(true);
  13505. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13506. return true;
  13507. };
  13508. LensFlareSystem.prototype.dispose = function () {
  13509. if (this._vertexBuffer) {
  13510. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13511. this._vertexBuffer = null;
  13512. }
  13513. if (this._indexBuffer) {
  13514. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13515. this._indexBuffer = null;
  13516. }
  13517. while (this.lensFlares.length) {
  13518. this.lensFlares[0].dispose();
  13519. }
  13520. var index = this._scene.lensFlareSystems.indexOf(this);
  13521. this._scene.lensFlareSystems.splice(index, 1);
  13522. };
  13523. return LensFlareSystem;
  13524. })();
  13525. BABYLON.LensFlareSystem = LensFlareSystem;
  13526. })(BABYLON || (BABYLON = {}));
  13527. var BABYLON;
  13528. (function (BABYLON) {
  13529. var IntersectionInfo = (function () {
  13530. function IntersectionInfo(bu, bv, distance) {
  13531. this.bu = bu;
  13532. this.bv = bv;
  13533. this.distance = distance;
  13534. this.faceId = 0;
  13535. }
  13536. return IntersectionInfo;
  13537. })();
  13538. BABYLON.IntersectionInfo = IntersectionInfo;
  13539. var PickingInfo = (function () {
  13540. function PickingInfo() {
  13541. this.hit = false;
  13542. this.distance = 0;
  13543. this.pickedPoint = null;
  13544. this.pickedMesh = null;
  13545. this.bu = 0;
  13546. this.bv = 0;
  13547. this.faceId = -1;
  13548. }
  13549. PickingInfo.prototype.getNormal = function () {
  13550. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13551. return null;
  13552. }
  13553. var indices = this.pickedMesh.getIndices();
  13554. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13555. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13556. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13557. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13558. normal0 = normal0.scale(this.bu);
  13559. normal1 = normal1.scale(this.bv);
  13560. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13561. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13562. };
  13563. PickingInfo.prototype.getTextureCoordinates = function () {
  13564. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13565. return null;
  13566. }
  13567. var indices = this.pickedMesh.getIndices();
  13568. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13569. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13570. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13571. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13572. uv0 = uv0.scale(this.bu);
  13573. uv1 = uv1.scale(this.bv);
  13574. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13575. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13576. };
  13577. return PickingInfo;
  13578. })();
  13579. BABYLON.PickingInfo = PickingInfo;
  13580. })(BABYLON || (BABYLON = {}));
  13581. var BABYLON;
  13582. (function (BABYLON) {
  13583. var FilesInput = (function () {
  13584. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13585. this.engine = p_engine;
  13586. this.canvas = p_canvas;
  13587. this.currentScene = p_scene;
  13588. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13589. this.progressCallback = p_progressCallback;
  13590. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13591. this.textureLoadingCallback = p_textureLoadingCallback;
  13592. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13593. }
  13594. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13595. var _this = this;
  13596. if (p_elementToMonitor) {
  13597. this.elementToMonitor = p_elementToMonitor;
  13598. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13599. _this.drag(e);
  13600. }, false);
  13601. this.elementToMonitor.addEventListener("dragover", function (e) {
  13602. _this.drag(e);
  13603. }, false);
  13604. this.elementToMonitor.addEventListener("drop", function (e) {
  13605. _this.drop(e);
  13606. }, false);
  13607. }
  13608. };
  13609. FilesInput.prototype.renderFunction = function () {
  13610. if (this.additionnalRenderLoopLogicCallback) {
  13611. this.additionnalRenderLoopLogicCallback();
  13612. }
  13613. if (this.currentScene) {
  13614. if (this.textureLoadingCallback) {
  13615. var remaining = this.currentScene.getWaitingItemsCount();
  13616. if (remaining > 0) {
  13617. this.textureLoadingCallback(remaining);
  13618. }
  13619. }
  13620. this.currentScene.render();
  13621. }
  13622. };
  13623. FilesInput.prototype.drag = function (e) {
  13624. e.stopPropagation();
  13625. e.preventDefault();
  13626. };
  13627. FilesInput.prototype.drop = function (eventDrop) {
  13628. eventDrop.stopPropagation();
  13629. eventDrop.preventDefault();
  13630. this.loadFiles(eventDrop);
  13631. };
  13632. FilesInput.prototype.loadFiles = function (event) {
  13633. var _this = this;
  13634. var that = this;
  13635. if (this.startingProcessingFilesCallback)
  13636. this.startingProcessingFilesCallback();
  13637. var sceneFileToLoad;
  13638. var filesToLoad;
  13639. if (event && event.dataTransfer && event.dataTransfer.files) {
  13640. filesToLoad = event.dataTransfer.files;
  13641. }
  13642. if (event && event.target && event.target.files) {
  13643. filesToLoad = event.target.files;
  13644. }
  13645. if (filesToLoad && filesToLoad.length > 0) {
  13646. for (var i = 0; i < filesToLoad.length; i++) {
  13647. switch (filesToLoad[i].type) {
  13648. case "image/jpeg":
  13649. case "image/png":
  13650. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13651. break;
  13652. case "image/targa":
  13653. case "image/vnd.ms-dds":
  13654. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13655. break;
  13656. default:
  13657. 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) {
  13658. sceneFileToLoad = filesToLoad[i];
  13659. }
  13660. break;
  13661. }
  13662. }
  13663. if (sceneFileToLoad) {
  13664. if (this.currentScene) {
  13665. this.engine.stopRenderLoop();
  13666. this.currentScene.dispose();
  13667. }
  13668. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  13669. that.currentScene = newScene;
  13670. that.currentScene.executeWhenReady(function () {
  13671. if (that.currentScene.activeCamera) {
  13672. that.currentScene.activeCamera.attachControl(that.canvas);
  13673. }
  13674. if (that.sceneLoadedCallback) {
  13675. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13676. }
  13677. that.engine.runRenderLoop(function () {
  13678. that.renderFunction();
  13679. });
  13680. });
  13681. }, function (progress) {
  13682. if (_this.progressCallback) {
  13683. _this.progressCallback(progress);
  13684. }
  13685. });
  13686. } else {
  13687. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13688. }
  13689. }
  13690. };
  13691. FilesInput.FilesTextures = new Array();
  13692. FilesInput.FilesToLoad = new Array();
  13693. return FilesInput;
  13694. })();
  13695. BABYLON.FilesInput = FilesInput;
  13696. })(BABYLON || (BABYLON = {}));
  13697. var BABYLON;
  13698. (function (BABYLON) {
  13699. var OimoJSPlugin = (function () {
  13700. function OimoJSPlugin() {
  13701. this._registeredMeshes = [];
  13702. /**
  13703. * Update the body position according to the mesh position
  13704. * @param mesh
  13705. */
  13706. this.updateBodyPosition = function (mesh) {
  13707. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13708. var registeredMesh = this._registeredMeshes[index];
  13709. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13710. var body = registeredMesh.body.body;
  13711. mesh.computeWorldMatrix(true);
  13712. var center = mesh.getBoundingInfo().boundingBox.center;
  13713. body.setPosition(center.x, center.y, center.z);
  13714. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13715. return;
  13716. }
  13717. if (registeredMesh.mesh.parent === mesh) {
  13718. mesh.computeWorldMatrix(true);
  13719. registeredMesh.mesh.computeWorldMatrix(true);
  13720. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13721. var absoluteRotation = mesh.rotation;
  13722. body = registeredMesh.body.body;
  13723. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13724. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13725. return;
  13726. }
  13727. }
  13728. };
  13729. }
  13730. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13731. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13732. };
  13733. OimoJSPlugin.prototype.initialize = function (iterations) {
  13734. this._world = new OIMO.World();
  13735. this._world.clear();
  13736. };
  13737. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13738. this._world.gravity = gravity;
  13739. };
  13740. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13741. var body = null;
  13742. this.unregisterMesh(mesh);
  13743. mesh.computeWorldMatrix(true);
  13744. switch (impostor) {
  13745. case BABYLON.PhysicsEngine.SphereImpostor:
  13746. var bbox = mesh.getBoundingInfo().boundingBox;
  13747. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13748. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13749. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13750. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13751. var deltaPosition = mesh.position.subtract(bbox.center);
  13752. body = new OIMO.Body({
  13753. type: 'sphere',
  13754. size: [size],
  13755. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13756. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13757. move: options.mass != 0,
  13758. config: [options.mass, options.friction, options.restitution],
  13759. world: this._world
  13760. });
  13761. this._registeredMeshes.push({
  13762. mesh: mesh,
  13763. body: body,
  13764. delta: deltaPosition
  13765. });
  13766. break;
  13767. case BABYLON.PhysicsEngine.PlaneImpostor:
  13768. case BABYLON.PhysicsEngine.BoxImpostor:
  13769. bbox = mesh.getBoundingInfo().boundingBox;
  13770. var min = bbox.minimumWorld;
  13771. var max = bbox.maximumWorld;
  13772. var box = max.subtract(min);
  13773. var sizeX = this._checkWithEpsilon(box.x);
  13774. var sizeY = this._checkWithEpsilon(box.y);
  13775. var sizeZ = this._checkWithEpsilon(box.z);
  13776. var deltaPosition = mesh.position.subtract(bbox.center);
  13777. body = new OIMO.Body({
  13778. type: 'box',
  13779. size: [sizeX, sizeY, sizeZ],
  13780. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13781. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13782. move: options.mass != 0,
  13783. config: [options.mass, options.friction, options.restitution],
  13784. world: this._world
  13785. });
  13786. this._registeredMeshes.push({
  13787. mesh: mesh,
  13788. body: body,
  13789. delta: deltaPosition
  13790. });
  13791. break;
  13792. }
  13793. return body;
  13794. };
  13795. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13796. var types = [], sizes = [], positions = [], rotations = [];
  13797. var initialMesh = parts[0].mesh;
  13798. for (var index = 0; index < parts.length; index++) {
  13799. var part = parts[index];
  13800. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13801. types.push(bodyParameters.type);
  13802. sizes.push.apply(sizes, bodyParameters.size);
  13803. positions.push.apply(positions, bodyParameters.pos);
  13804. rotations.push.apply(rotations, bodyParameters.rot);
  13805. }
  13806. var body = new OIMO.Body({
  13807. type: types,
  13808. size: sizes,
  13809. pos: positions,
  13810. rot: rotations,
  13811. move: options.mass != 0,
  13812. config: [options.mass, options.friction, options.restitution],
  13813. world: this._world
  13814. });
  13815. this._registeredMeshes.push({
  13816. mesh: initialMesh,
  13817. body: body
  13818. });
  13819. return body;
  13820. };
  13821. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13822. var bodyParameters = null;
  13823. var mesh = part.mesh;
  13824. switch (part.impostor) {
  13825. case BABYLON.PhysicsEngine.SphereImpostor:
  13826. var bbox = mesh.getBoundingInfo().boundingBox;
  13827. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13828. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13829. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13830. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13831. bodyParameters = {
  13832. type: 'sphere',
  13833. /* bug with oimo : sphere needs 3 sizes in this case */
  13834. size: [size, -1, -1],
  13835. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13836. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13837. };
  13838. break;
  13839. case BABYLON.PhysicsEngine.PlaneImpostor:
  13840. case BABYLON.PhysicsEngine.BoxImpostor:
  13841. bbox = mesh.getBoundingInfo().boundingBox;
  13842. var min = bbox.minimumWorld;
  13843. var max = bbox.maximumWorld;
  13844. var box = max.subtract(min);
  13845. var sizeX = this._checkWithEpsilon(box.x);
  13846. var sizeY = this._checkWithEpsilon(box.y);
  13847. var sizeZ = this._checkWithEpsilon(box.z);
  13848. var relativePosition = mesh.position;
  13849. bodyParameters = {
  13850. type: 'box',
  13851. size: [sizeX, sizeY, sizeZ],
  13852. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13853. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13854. };
  13855. break;
  13856. }
  13857. return bodyParameters;
  13858. };
  13859. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13860. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13861. var registeredMesh = this._registeredMeshes[index];
  13862. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13863. if (registeredMesh.body) {
  13864. this._world.removeRigidBody(registeredMesh.body.body);
  13865. this._unbindBody(registeredMesh.body);
  13866. }
  13867. this._registeredMeshes.splice(index, 1);
  13868. return;
  13869. }
  13870. }
  13871. };
  13872. OimoJSPlugin.prototype._unbindBody = function (body) {
  13873. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13874. var registeredMesh = this._registeredMeshes[index];
  13875. if (registeredMesh.body === body) {
  13876. registeredMesh.body = null;
  13877. }
  13878. }
  13879. };
  13880. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13881. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13882. var registeredMesh = this._registeredMeshes[index];
  13883. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13884. var mass = registeredMesh.body.body.massInfo.mass;
  13885. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13886. return;
  13887. }
  13888. }
  13889. };
  13890. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13891. var body1 = null, body2 = null;
  13892. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13893. var registeredMesh = this._registeredMeshes[index];
  13894. if (registeredMesh.mesh === mesh1) {
  13895. body1 = registeredMesh.body.body;
  13896. } else if (registeredMesh.mesh === mesh2) {
  13897. body2 = registeredMesh.body.body;
  13898. }
  13899. }
  13900. if (!body1 || !body2) {
  13901. return false;
  13902. }
  13903. if (!options) {
  13904. options = {};
  13905. }
  13906. new OIMO.Link({
  13907. type: options.type,
  13908. body1: body1,
  13909. body2: body2,
  13910. min: options.min,
  13911. max: options.max,
  13912. axe1: options.axe1,
  13913. axe2: options.axe2,
  13914. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13915. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13916. collision: options.collision,
  13917. spring: options.spring,
  13918. world: this._world
  13919. });
  13920. return true;
  13921. };
  13922. OimoJSPlugin.prototype.dispose = function () {
  13923. this._world.clear();
  13924. while (this._registeredMeshes.length) {
  13925. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13926. }
  13927. };
  13928. OimoJSPlugin.prototype.isSupported = function () {
  13929. return OIMO !== undefined;
  13930. };
  13931. OimoJSPlugin.prototype._getLastShape = function (body) {
  13932. var lastShape = body.shapes;
  13933. while (lastShape.next) {
  13934. lastShape = lastShape.next;
  13935. }
  13936. return lastShape;
  13937. };
  13938. OimoJSPlugin.prototype.runOneStep = function (time) {
  13939. this._world.step();
  13940. var i = this._registeredMeshes.length;
  13941. var m;
  13942. while (i--) {
  13943. var body = this._registeredMeshes[i].body.body;
  13944. var mesh = this._registeredMeshes[i].mesh;
  13945. var delta = this._registeredMeshes[i].delta;
  13946. if (!body.sleeping) {
  13947. if (body.shapes.next) {
  13948. var parentShape = this._getLastShape(body);
  13949. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13950. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13951. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13952. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13953. if (!mesh.rotationQuaternion) {
  13954. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13955. }
  13956. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13957. } else {
  13958. m = body.getMatrix();
  13959. mtx = BABYLON.Matrix.FromArray(m);
  13960. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13961. if (!delta) {
  13962. mesh.position.x = bodyX;
  13963. mesh.position.y = bodyY;
  13964. mesh.position.z = bodyZ;
  13965. } else {
  13966. mesh.position.x = bodyX + delta.x;
  13967. mesh.position.y = bodyY + delta.y;
  13968. mesh.position.z = bodyZ + delta.z;
  13969. }
  13970. if (!mesh.rotationQuaternion) {
  13971. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13972. }
  13973. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13974. }
  13975. }
  13976. }
  13977. };
  13978. return OimoJSPlugin;
  13979. })();
  13980. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13981. })(BABYLON || (BABYLON = {}));
  13982. var BABYLON;
  13983. (function (BABYLON) {
  13984. var PhysicsEngine = (function () {
  13985. function PhysicsEngine(plugin) {
  13986. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13987. }
  13988. PhysicsEngine.prototype._initialize = function (gravity) {
  13989. this._currentPlugin.initialize();
  13990. this._setGravity(gravity);
  13991. };
  13992. PhysicsEngine.prototype._runOneStep = function (delta) {
  13993. if (delta > 0.1) {
  13994. delta = 0.1;
  13995. } else if (delta <= 0) {
  13996. delta = 1.0 / 60.0;
  13997. }
  13998. this._currentPlugin.runOneStep(delta);
  13999. };
  14000. PhysicsEngine.prototype._setGravity = function (gravity) {
  14001. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14002. this._currentPlugin.setGravity(this.gravity);
  14003. };
  14004. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14005. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14006. };
  14007. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14008. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14009. };
  14010. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14011. this._currentPlugin.unregisterMesh(mesh);
  14012. };
  14013. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14014. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14015. };
  14016. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14017. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14018. };
  14019. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14020. this._currentPlugin.updateBodyPosition(mesh);
  14021. };
  14022. PhysicsEngine.prototype.dispose = function () {
  14023. this._currentPlugin.dispose();
  14024. };
  14025. PhysicsEngine.prototype.isSupported = function () {
  14026. return this._currentPlugin.isSupported();
  14027. };
  14028. PhysicsEngine.NoImpostor = 0;
  14029. PhysicsEngine.SphereImpostor = 1;
  14030. PhysicsEngine.BoxImpostor = 2;
  14031. PhysicsEngine.PlaneImpostor = 3;
  14032. PhysicsEngine.MeshImpostor = 4;
  14033. PhysicsEngine.CapsuleImpostor = 5;
  14034. PhysicsEngine.ConeImpostor = 6;
  14035. PhysicsEngine.CylinderImpostor = 7;
  14036. PhysicsEngine.ConvexHullImpostor = 8;
  14037. PhysicsEngine.Epsilon = 0.001;
  14038. return PhysicsEngine;
  14039. })();
  14040. BABYLON.PhysicsEngine = PhysicsEngine;
  14041. })(BABYLON || (BABYLON = {}));
  14042. var BABYLON;
  14043. (function (BABYLON) {
  14044. var serializeLight = function (light) {
  14045. var serializationObject = {};
  14046. serializationObject.name = light.name;
  14047. serializationObject.id = light.id;
  14048. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14049. if (light instanceof BABYLON.PointLight) {
  14050. serializationObject.type = 0;
  14051. serializationObject.position = light.position.asArray();
  14052. } else if (light instanceof BABYLON.DirectionalLight) {
  14053. serializationObject.type = 1;
  14054. var directionalLight = light;
  14055. serializationObject.position = directionalLight.position.asArray();
  14056. serializationObject.direction = directionalLight.direction.asArray();
  14057. } else if (light instanceof BABYLON.SpotLight) {
  14058. serializationObject.type = 2;
  14059. var spotLight = light;
  14060. serializationObject.position = spotLight.position.asArray();
  14061. serializationObject.direction = spotLight.position.asArray();
  14062. serializationObject.angle = spotLight.angle;
  14063. serializationObject.exponent = spotLight.exponent;
  14064. } else if (light instanceof BABYLON.HemisphericLight) {
  14065. serializationObject.type = 3;
  14066. var hemisphericLight = light;
  14067. serializationObject.direction = hemisphericLight.direction.asArray();
  14068. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14069. }
  14070. if (light.intensity) {
  14071. serializationObject.intensity = light.intensity;
  14072. }
  14073. serializationObject.range = light.range;
  14074. serializationObject.diffuse = light.diffuse.asArray();
  14075. serializationObject.specular = light.specular.asArray();
  14076. return serializationObject;
  14077. };
  14078. var serializeFresnelParameter = function (fresnelParameter) {
  14079. var serializationObject = {};
  14080. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14081. serializationObject.leftColor = fresnelParameter.leftColor;
  14082. serializationObject.rightColor = fresnelParameter.rightColor;
  14083. serializationObject.bias = fresnelParameter.bias;
  14084. serializationObject.power = fresnelParameter.power;
  14085. return serializationObject;
  14086. };
  14087. var serializeCamera = function (camera) {
  14088. var serializationObject = {};
  14089. serializationObject.name = camera.name;
  14090. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14091. serializationObject.id = camera.id;
  14092. serializationObject.position = camera.position.asArray();
  14093. if (camera.parent) {
  14094. serializationObject.parentId = camera.parent.id;
  14095. }
  14096. serializationObject.rotation = camera.rotation.asArray();
  14097. if (camera.lockedTarget && camera.lockedTarget.id) {
  14098. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14099. }
  14100. serializationObject.fov = camera.fov;
  14101. serializationObject.minZ = camera.minZ;
  14102. serializationObject.maxZ = camera.maxZ;
  14103. serializationObject.speed = camera.speed;
  14104. serializationObject.inertia = camera.inertia;
  14105. serializationObject.checkCollisions = camera.checkCollisions;
  14106. serializationObject.applyGravity = camera.applyGravity;
  14107. if (camera.ellipsoid) {
  14108. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14109. }
  14110. appendAnimations(camera, serializationObject);
  14111. serializationObject.layerMask = camera.layerMask;
  14112. return serializationObject;
  14113. };
  14114. var appendAnimations = function (source, destination) {
  14115. if (source.animations) {
  14116. destination.animations = [];
  14117. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14118. var animation = source.animations[animationIndex];
  14119. destination.animations.push(serializeAnimation(animation));
  14120. }
  14121. }
  14122. };
  14123. var serializeAnimation = function (animation) {
  14124. var serializationObject = {};
  14125. serializationObject.name = animation.name;
  14126. serializationObject.property = animation.targetProperty;
  14127. serializationObject.framePerSecond = animation.framePerSecond;
  14128. serializationObject.dataType = animation.dataType;
  14129. serializationObject.loopBehavior = animation.loopMode;
  14130. var dataType = animation.dataType;
  14131. serializationObject.keys = [];
  14132. var keys = animation.getKeys();
  14133. for (var index = 0; index < keys.length; index++) {
  14134. var animationKey = keys[index];
  14135. var key = {};
  14136. key.frame = animationKey.frame;
  14137. switch (dataType) {
  14138. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14139. key.values = [animationKey.value];
  14140. break;
  14141. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14142. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14143. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14144. key.values = animationKey.value.asArray();
  14145. break;
  14146. }
  14147. serializationObject.keys.push(key);
  14148. }
  14149. return serializationObject;
  14150. };
  14151. var serializeMultiMaterial = function (material) {
  14152. var serializationObject = {};
  14153. serializationObject.name = material.name;
  14154. serializationObject.id = material.id;
  14155. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14156. serializationObject.materials = [];
  14157. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14158. var subMat = material.subMaterials[matIndex];
  14159. if (subMat) {
  14160. serializationObject.materials.push(subMat.id);
  14161. } else {
  14162. serializationObject.materials.push(null);
  14163. }
  14164. }
  14165. return serializationObject;
  14166. };
  14167. var serializeMaterial = function (material) {
  14168. var serializationObject = {};
  14169. serializationObject.name = material.name;
  14170. serializationObject.ambient = material.ambientColor.asArray();
  14171. serializationObject.diffuse = material.diffuseColor.asArray();
  14172. serializationObject.specular = material.specularColor.asArray();
  14173. serializationObject.specularPower = material.specularPower;
  14174. serializationObject.emissive = material.emissiveColor.asArray();
  14175. serializationObject.alpha = material.alpha;
  14176. serializationObject.id = material.id;
  14177. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14178. serializationObject.backFaceCulling = material.backFaceCulling;
  14179. if (material.diffuseTexture) {
  14180. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14181. }
  14182. if (material.diffuseFresnelParameters) {
  14183. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14184. }
  14185. if (material.ambientTexture) {
  14186. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14187. }
  14188. if (material.opacityTexture) {
  14189. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14190. }
  14191. if (material.opacityFresnelParameters) {
  14192. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14193. }
  14194. if (material.reflectionTexture) {
  14195. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14196. }
  14197. if (material.reflectionFresnelParameters) {
  14198. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14199. }
  14200. if (material.emissiveTexture) {
  14201. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14202. }
  14203. if (material.emissiveFresnelParameters) {
  14204. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14205. }
  14206. if (material.specularTexture) {
  14207. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14208. }
  14209. if (material.bumpTexture) {
  14210. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14211. }
  14212. return serializationObject;
  14213. };
  14214. var serializeTexture = function (texture) {
  14215. var serializationObject = {};
  14216. if (!texture.name) {
  14217. return null;
  14218. }
  14219. if (texture instanceof BABYLON.CubeTexture) {
  14220. serializationObject.name = texture.name;
  14221. serializationObject.hasAlpha = texture.hasAlpha;
  14222. serializationObject.level = texture.level;
  14223. serializationObject.coordinatesMode = texture.coordinatesMode;
  14224. return serializationObject;
  14225. }
  14226. if (texture instanceof BABYLON.MirrorTexture) {
  14227. var mirrorTexture = texture;
  14228. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14229. serializationObject.renderList = [];
  14230. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14231. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14232. }
  14233. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14234. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14235. var renderTargetTexture = texture;
  14236. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14237. serializationObject.renderList = [];
  14238. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14239. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14240. }
  14241. }
  14242. var regularTexture = texture;
  14243. serializationObject.name = texture.name;
  14244. serializationObject.hasAlpha = texture.hasAlpha;
  14245. serializationObject.level = texture.level;
  14246. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14247. serializationObject.coordinatesMode = texture.coordinatesMode;
  14248. serializationObject.uOffset = regularTexture.uOffset;
  14249. serializationObject.vOffset = regularTexture.vOffset;
  14250. serializationObject.uScale = regularTexture.uScale;
  14251. serializationObject.vScale = regularTexture.vScale;
  14252. serializationObject.uAng = regularTexture.uAng;
  14253. serializationObject.vAng = regularTexture.vAng;
  14254. serializationObject.wAng = regularTexture.wAng;
  14255. serializationObject.wrapU = texture.wrapU;
  14256. serializationObject.wrapV = texture.wrapV;
  14257. appendAnimations(texture, serializationObject);
  14258. return serializationObject;
  14259. };
  14260. var serializeSkeleton = function (skeleton) {
  14261. var serializationObject = {};
  14262. serializationObject.name = skeleton.name;
  14263. serializationObject.id = skeleton.id;
  14264. serializationObject.bones = [];
  14265. for (var index = 0; index < skeleton.bones.length; index++) {
  14266. var bone = skeleton.bones[index];
  14267. var serializedBone = {
  14268. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14269. name: bone.name,
  14270. matrix: bone.getLocalMatrix().toArray()
  14271. };
  14272. serializationObject.bones.push(serializedBone);
  14273. if (bone.animations && bone.animations.length > 0) {
  14274. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14275. }
  14276. }
  14277. return serializationObject;
  14278. };
  14279. var serializeParticleSystem = function (particleSystem) {
  14280. var serializationObject = {};
  14281. serializationObject.emitterId = particleSystem.emitter.id;
  14282. serializationObject.capacity = particleSystem.getCapacity();
  14283. if (particleSystem.particleTexture) {
  14284. serializationObject.textureName = particleSystem.particleTexture.name;
  14285. }
  14286. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14287. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14288. serializationObject.minSize = particleSystem.minSize;
  14289. serializationObject.maxSize = particleSystem.maxSize;
  14290. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14291. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14292. serializationObject.emitRate = particleSystem.emitRate;
  14293. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14294. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14295. serializationObject.gravity = particleSystem.gravity.asArray();
  14296. serializationObject.direction1 = particleSystem.direction1.asArray();
  14297. serializationObject.direction2 = particleSystem.direction2.asArray();
  14298. serializationObject.color1 = particleSystem.color1.asArray();
  14299. serializationObject.color2 = particleSystem.color2.asArray();
  14300. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14301. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14302. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14303. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14304. serializationObject.blendMode = particleSystem.blendMode;
  14305. return serializationObject;
  14306. };
  14307. var serializeLensFlareSystem = function (lensFlareSystem) {
  14308. var serializationObject = {};
  14309. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14310. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14311. serializationObject.flares = [];
  14312. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14313. var flare = lensFlareSystem.lensFlares[index];
  14314. serializationObject.flares.push({
  14315. size: flare.size,
  14316. position: flare.position,
  14317. color: flare.color.asArray(),
  14318. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14319. });
  14320. }
  14321. return serializationObject;
  14322. };
  14323. var serializeShadowGenerator = function (light) {
  14324. var serializationObject = {};
  14325. var shadowGenerator = light.getShadowGenerator();
  14326. serializationObject.lightId = light.id;
  14327. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14328. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14329. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14330. serializationObject.renderList = [];
  14331. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14332. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14333. serializationObject.renderList.push(mesh.id);
  14334. }
  14335. return serializationObject;
  14336. };
  14337. var serializedGeometries = [];
  14338. var serializeGeometry = function (geometry, serializationGeometries) {
  14339. if (serializedGeometries[geometry.id]) {
  14340. return;
  14341. }
  14342. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14343. serializationGeometries.boxes.push(serializeBox(geometry));
  14344. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14345. serializationGeometries.spheres.push(serializeSphere(geometry));
  14346. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14347. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14348. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14349. serializationGeometries.toruses.push(serializeTorus(geometry));
  14350. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14351. serializationGeometries.grounds.push(serializeGround(geometry));
  14352. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14353. serializationGeometries.planes.push(serializePlane(geometry));
  14354. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14355. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14356. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14357. throw new Error("Unknow primitive type");
  14358. } else {
  14359. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14360. }
  14361. serializedGeometries[geometry.id] = true;
  14362. };
  14363. var serializeGeometryBase = function (geometry) {
  14364. var serializationObject = {};
  14365. serializationObject.id = geometry.id;
  14366. if (BABYLON.Tags.HasTags(geometry)) {
  14367. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14368. }
  14369. return serializationObject;
  14370. };
  14371. var serializeVertexData = function (vertexData) {
  14372. var serializationObject = serializeGeometryBase(vertexData);
  14373. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14374. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14375. }
  14376. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14377. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14378. }
  14379. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14380. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14381. }
  14382. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14383. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14384. }
  14385. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14386. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14387. }
  14388. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14389. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14390. serializationObject.matricesIndices._isExpanded = true;
  14391. }
  14392. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14393. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14394. }
  14395. serializationObject.indices = vertexData.getIndices();
  14396. return serializationObject;
  14397. };
  14398. var serializePrimitive = function (primitive) {
  14399. var serializationObject = serializeGeometryBase(primitive);
  14400. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14401. return serializationObject;
  14402. };
  14403. var serializeBox = function (box) {
  14404. var serializationObject = serializePrimitive(box);
  14405. serializationObject.size = box.size;
  14406. return serializationObject;
  14407. };
  14408. var serializeSphere = function (sphere) {
  14409. var serializationObject = serializePrimitive(sphere);
  14410. serializationObject.segments = sphere.segments;
  14411. serializationObject.diameter = sphere.diameter;
  14412. return serializationObject;
  14413. };
  14414. var serializeCylinder = function (cylinder) {
  14415. var serializationObject = serializePrimitive(cylinder);
  14416. serializationObject.height = cylinder.height;
  14417. serializationObject.diameterTop = cylinder.diameterTop;
  14418. serializationObject.diameterBottom = cylinder.diameterBottom;
  14419. serializationObject.tessellation = cylinder.tessellation;
  14420. return serializationObject;
  14421. };
  14422. var serializeTorus = function (torus) {
  14423. var serializationObject = serializePrimitive(torus);
  14424. serializationObject.diameter = torus.diameter;
  14425. serializationObject.thickness = torus.thickness;
  14426. serializationObject.tessellation = torus.tessellation;
  14427. return serializationObject;
  14428. };
  14429. var serializeGround = function (ground) {
  14430. var serializationObject = serializePrimitive(ground);
  14431. serializationObject.width = ground.width;
  14432. serializationObject.height = ground.height;
  14433. serializationObject.subdivisions = ground.subdivisions;
  14434. return serializationObject;
  14435. };
  14436. var serializePlane = function (plane) {
  14437. var serializationObject = serializePrimitive(plane);
  14438. serializationObject.size = plane.size;
  14439. return serializationObject;
  14440. };
  14441. var serializeTorusKnot = function (torusKnot) {
  14442. var serializationObject = serializePrimitive(torusKnot);
  14443. serializationObject.radius = torusKnot.radius;
  14444. serializationObject.tube = torusKnot.tube;
  14445. serializationObject.radialSegments = torusKnot.radialSegments;
  14446. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14447. serializationObject.p = torusKnot.p;
  14448. serializationObject.q = torusKnot.q;
  14449. return serializationObject;
  14450. };
  14451. var serializeMesh = function (mesh, serializationScene) {
  14452. var serializationObject = {};
  14453. serializationObject.name = mesh.name;
  14454. serializationObject.id = mesh.id;
  14455. if (BABYLON.Tags.HasTags(mesh)) {
  14456. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14457. }
  14458. serializationObject.position = mesh.position.asArray();
  14459. if (mesh.rotationQuaternion) {
  14460. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14461. } else if (mesh.rotation) {
  14462. serializationObject.rotation = mesh.rotation.asArray();
  14463. }
  14464. serializationObject.scaling = mesh.scaling.asArray();
  14465. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14466. serializationObject.isEnabled = mesh.isEnabled();
  14467. serializationObject.isVisible = mesh.isVisible;
  14468. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14469. serializationObject.pickable = mesh.isPickable;
  14470. serializationObject.receiveShadows = mesh.receiveShadows;
  14471. serializationObject.billboardMode = mesh.billboardMode;
  14472. serializationObject.visibility = mesh.visibility;
  14473. serializationObject.checkCollisions = mesh.checkCollisions;
  14474. if (mesh.parent) {
  14475. serializationObject.parentId = mesh.parent.id;
  14476. }
  14477. var geometry = mesh._geometry;
  14478. if (geometry) {
  14479. var geometryId = geometry.id;
  14480. serializationObject.geometryId = geometryId;
  14481. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14482. serializeGeometry(geometry, serializationScene.geometries);
  14483. }
  14484. serializationObject.subMeshes = [];
  14485. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14486. var subMesh = mesh.subMeshes[subIndex];
  14487. serializationObject.subMeshes.push({
  14488. materialIndex: subMesh.materialIndex,
  14489. verticesStart: subMesh.verticesStart,
  14490. verticesCount: subMesh.verticesCount,
  14491. indexStart: subMesh.indexStart,
  14492. indexCount: subMesh.indexCount
  14493. });
  14494. }
  14495. }
  14496. if (mesh.material) {
  14497. serializationObject.materialId = mesh.material.id;
  14498. } else {
  14499. mesh.material = null;
  14500. }
  14501. if (mesh.skeleton) {
  14502. serializationObject.skeletonId = mesh.skeleton.id;
  14503. }
  14504. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14505. serializationObject.physicsMass = mesh.getPhysicsMass();
  14506. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14507. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14508. switch (mesh.getPhysicsImpostor()) {
  14509. case BABYLON.PhysicsEngine.BoxImpostor:
  14510. serializationObject.physicsImpostor = 1;
  14511. break;
  14512. case BABYLON.PhysicsEngine.SphereImpostor:
  14513. serializationObject.physicsImpostor = 2;
  14514. break;
  14515. }
  14516. }
  14517. serializationObject.instances = [];
  14518. for (var index = 0; index < mesh.instances.length; index++) {
  14519. var instance = mesh.instances[index];
  14520. var serializationInstance = {
  14521. name: instance.name,
  14522. position: instance.position,
  14523. rotation: instance.rotation,
  14524. rotationQuaternion: instance.rotationQuaternion,
  14525. scaling: instance.scaling
  14526. };
  14527. serializationObject.instances.push(serializationInstance);
  14528. appendAnimations(instance, serializationInstance);
  14529. }
  14530. appendAnimations(mesh, serializationObject);
  14531. serializationObject.layerMask = mesh.layerMask;
  14532. return serializationObject;
  14533. };
  14534. var SceneSerializer = (function () {
  14535. function SceneSerializer() {
  14536. }
  14537. SceneSerializer.Serialize = function (scene) {
  14538. var serializationObject = {};
  14539. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14540. serializationObject.autoClear = scene.autoClear;
  14541. serializationObject.clearColor = scene.clearColor.asArray();
  14542. serializationObject.ambientColor = scene.ambientColor.asArray();
  14543. serializationObject.gravity = scene.gravity.asArray();
  14544. if (scene.fogMode && scene.fogMode !== 0) {
  14545. serializationObject.fogMode = scene.fogMode;
  14546. serializationObject.fogColor = scene.fogColor.asArray();
  14547. serializationObject.fogStart = scene.fogStart;
  14548. serializationObject.fogEnd = scene.fogEnd;
  14549. serializationObject.fogDensity = scene.fogDensity;
  14550. }
  14551. serializationObject.lights = [];
  14552. for (var index = 0; index < scene.lights.length; index++) {
  14553. var light = scene.lights[index];
  14554. serializationObject.lights.push(serializeLight(light));
  14555. }
  14556. serializationObject.cameras = [];
  14557. for (index = 0; index < scene.cameras.length; index++) {
  14558. var camera = scene.cameras[index];
  14559. if (camera instanceof BABYLON.FreeCamera) {
  14560. serializationObject.cameras.push(serializeCamera(camera));
  14561. }
  14562. }
  14563. if (scene.activeCamera) {
  14564. serializationObject.activeCameraID = scene.activeCamera.id;
  14565. }
  14566. serializationObject.materials = [];
  14567. serializationObject.multiMaterials = [];
  14568. for (index = 0; index < scene.materials.length; index++) {
  14569. var material = scene.materials[index];
  14570. if (material instanceof BABYLON.StandardMaterial) {
  14571. serializationObject.materials.push(serializeMaterial(material));
  14572. } else if (material instanceof BABYLON.MultiMaterial) {
  14573. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14574. }
  14575. }
  14576. serializationObject.skeletons = [];
  14577. for (index = 0; index < scene.skeletons.length; index++) {
  14578. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14579. }
  14580. serializationObject.geometries = {};
  14581. serializationObject.geometries.boxes = [];
  14582. serializationObject.geometries.spheres = [];
  14583. serializationObject.geometries.cylinders = [];
  14584. serializationObject.geometries.toruses = [];
  14585. serializationObject.geometries.grounds = [];
  14586. serializationObject.geometries.planes = [];
  14587. serializationObject.geometries.torusKnots = [];
  14588. serializationObject.geometries.vertexData = [];
  14589. serializedGeometries = [];
  14590. var geometries = scene.getGeometries();
  14591. for (var index = 0; index < geometries.length; index++) {
  14592. var geometry = geometries[index];
  14593. if (geometry.isReady()) {
  14594. serializeGeometry(geometry, serializationObject.geometries);
  14595. }
  14596. }
  14597. serializationObject.meshes = [];
  14598. for (index = 0; index < scene.meshes.length; index++) {
  14599. var abstractMesh = scene.meshes[index];
  14600. if (abstractMesh instanceof BABYLON.Mesh) {
  14601. var mesh = abstractMesh;
  14602. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14603. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14604. }
  14605. }
  14606. }
  14607. serializationObject.particleSystems = [];
  14608. for (index = 0; index < scene.particleSystems.length; index++) {
  14609. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14610. }
  14611. serializationObject.lensFlareSystems = [];
  14612. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14613. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14614. }
  14615. serializationObject.shadowGenerators = [];
  14616. for (index = 0; index < scene.lights.length; index++) {
  14617. light = scene.lights[index];
  14618. if (light.getShadowGenerator()) {
  14619. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14620. }
  14621. }
  14622. return serializationObject;
  14623. };
  14624. return SceneSerializer;
  14625. })();
  14626. BABYLON.SceneSerializer = SceneSerializer;
  14627. })(BABYLON || (BABYLON = {}));
  14628. var BABYLON;
  14629. (function (BABYLON) {
  14630. var SceneLoader = (function () {
  14631. function SceneLoader() {
  14632. }
  14633. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14634. get: function () {
  14635. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14636. },
  14637. set: function (value) {
  14638. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14639. },
  14640. enumerable: true,
  14641. configurable: true
  14642. });
  14643. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14644. get: function () {
  14645. return SceneLoader._ShowLoadingScreen;
  14646. },
  14647. set: function (value) {
  14648. SceneLoader._ShowLoadingScreen = value;
  14649. },
  14650. enumerable: true,
  14651. configurable: true
  14652. });
  14653. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14654. var dotPosition = sceneFilename.lastIndexOf(".");
  14655. var queryStringPosition = sceneFilename.indexOf("?");
  14656. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  14657. for (var index = 0; index < this._registeredPlugins.length; index++) {
  14658. var plugin = this._registeredPlugins[index];
  14659. if (plugin.extensions.indexOf(extension) !== -1) {
  14660. return plugin;
  14661. }
  14662. }
  14663. return this._registeredPlugins[this._registeredPlugins.length - 1];
  14664. };
  14665. SceneLoader.RegisterPlugin = function (plugin) {
  14666. plugin.extensions = plugin.extensions.toLowerCase();
  14667. SceneLoader._registeredPlugins.push(plugin);
  14668. };
  14669. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14670. var _this = this;
  14671. var manifestChecked = function (success) {
  14672. scene.database = database;
  14673. var plugin = _this._getPluginForFilename(sceneFilename);
  14674. var importMeshFromData = function (data) {
  14675. var meshes = [];
  14676. var particleSystems = [];
  14677. var skeletons = [];
  14678. try {
  14679. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14680. if (onerror) {
  14681. onerror(scene);
  14682. }
  14683. return;
  14684. }
  14685. } catch (e) {
  14686. if (onerror) {
  14687. onerror(scene);
  14688. }
  14689. return;
  14690. }
  14691. if (onsuccess) {
  14692. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14693. onsuccess(meshes, particleSystems, skeletons);
  14694. }
  14695. };
  14696. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14697. importMeshFromData(sceneFilename.substr(5));
  14698. return;
  14699. }
  14700. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14701. importMeshFromData(data);
  14702. }, progressCallBack, database);
  14703. };
  14704. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14705. };
  14706. /**
  14707. * Load a scene
  14708. * @param rootUrl a string that defines the root url for scene and resources
  14709. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14710. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14711. */
  14712. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14713. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14714. };
  14715. /**
  14716. * Append a scene
  14717. * @param rootUrl a string that defines the root url for scene and resources
  14718. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14719. * @param scene is the instance of BABYLON.Scene to append to
  14720. */
  14721. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14722. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14723. var database;
  14724. if (SceneLoader.ShowLoadingScreen) {
  14725. scene.getEngine().displayLoadingUI();
  14726. }
  14727. var loadSceneFromData = function (data) {
  14728. scene.database = database;
  14729. if (!plugin.load(scene, data, rootUrl)) {
  14730. if (onerror) {
  14731. onerror(scene);
  14732. }
  14733. scene.getEngine().hideLoadingUI();
  14734. return;
  14735. }
  14736. if (onsuccess) {
  14737. onsuccess(scene);
  14738. }
  14739. if (SceneLoader.ShowLoadingScreen) {
  14740. scene.executeWhenReady(function () {
  14741. scene.getEngine().hideLoadingUI();
  14742. });
  14743. }
  14744. };
  14745. var manifestChecked = function (success) {
  14746. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14747. };
  14748. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14749. loadSceneFromData(sceneFilename.substr(5));
  14750. return;
  14751. }
  14752. if (rootUrl.indexOf("file:") === -1) {
  14753. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14754. } else {
  14755. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14756. }
  14757. };
  14758. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14759. SceneLoader._ShowLoadingScreen = true;
  14760. SceneLoader._registeredPlugins = new Array();
  14761. return SceneLoader;
  14762. })();
  14763. BABYLON.SceneLoader = SceneLoader;
  14764. ;
  14765. })(BABYLON || (BABYLON = {}));
  14766. var BABYLON;
  14767. (function (BABYLON) {
  14768. (function (Internals) {
  14769. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14770. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14771. texture.name = parsedTexture.name;
  14772. texture.hasAlpha = parsedTexture.hasAlpha;
  14773. texture.level = parsedTexture.level;
  14774. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14775. return texture;
  14776. };
  14777. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14778. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14779. return null;
  14780. }
  14781. if (parsedTexture.isCube) {
  14782. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14783. }
  14784. var texture;
  14785. if (parsedTexture.mirrorPlane) {
  14786. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14787. texture._waitingRenderList = parsedTexture.renderList;
  14788. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14789. } else if (parsedTexture.isRenderTarget) {
  14790. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14791. texture._waitingRenderList = parsedTexture.renderList;
  14792. } else {
  14793. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14794. }
  14795. texture.name = parsedTexture.name;
  14796. texture.hasAlpha = parsedTexture.hasAlpha;
  14797. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14798. texture.level = parsedTexture.level;
  14799. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14800. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14801. texture.uOffset = parsedTexture.uOffset;
  14802. texture.vOffset = parsedTexture.vOffset;
  14803. texture.uScale = parsedTexture.uScale;
  14804. texture.vScale = parsedTexture.vScale;
  14805. texture.uAng = parsedTexture.uAng;
  14806. texture.vAng = parsedTexture.vAng;
  14807. texture.wAng = parsedTexture.wAng;
  14808. texture.wrapU = parsedTexture.wrapU;
  14809. texture.wrapV = parsedTexture.wrapV;
  14810. if (parsedTexture.animations) {
  14811. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14812. var parsedAnimation = parsedTexture.animations[animationIndex];
  14813. texture.animations.push(parseAnimation(parsedAnimation));
  14814. }
  14815. }
  14816. return texture;
  14817. };
  14818. var parseSkeleton = function (parsedSkeleton, scene) {
  14819. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14820. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14821. var parsedBone = parsedSkeleton.bones[index];
  14822. var parentBone = null;
  14823. if (parsedBone.parentBoneIndex > -1) {
  14824. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14825. }
  14826. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14827. if (parsedBone.animation) {
  14828. bone.animations.push(parseAnimation(parsedBone.animation));
  14829. }
  14830. }
  14831. return skeleton;
  14832. };
  14833. var parseFresnelParameters = function (parsedFresnelParameters) {
  14834. var fresnelParameters = new BABYLON.FresnelParameters();
  14835. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14836. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14837. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14838. fresnelParameters.bias = parsedFresnelParameters.bias;
  14839. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14840. return fresnelParameters;
  14841. };
  14842. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14843. var material;
  14844. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14845. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14846. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14847. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14848. material.specularPower = parsedMaterial.specularPower;
  14849. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14850. material.alpha = parsedMaterial.alpha;
  14851. material.id = parsedMaterial.id;
  14852. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14853. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14854. material.wireframe = parsedMaterial.wireframe;
  14855. if (parsedMaterial.diffuseTexture) {
  14856. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14857. }
  14858. if (parsedMaterial.diffuseFresnelParameters) {
  14859. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14860. }
  14861. if (parsedMaterial.ambientTexture) {
  14862. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14863. }
  14864. if (parsedMaterial.opacityTexture) {
  14865. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14866. }
  14867. if (parsedMaterial.opacityFresnelParameters) {
  14868. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14869. }
  14870. if (parsedMaterial.reflectionTexture) {
  14871. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14872. }
  14873. if (parsedMaterial.reflectionFresnelParameters) {
  14874. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14875. }
  14876. if (parsedMaterial.emissiveTexture) {
  14877. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14878. }
  14879. if (parsedMaterial.emissiveFresnelParameters) {
  14880. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14881. }
  14882. if (parsedMaterial.specularTexture) {
  14883. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14884. }
  14885. if (parsedMaterial.bumpTexture) {
  14886. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14887. }
  14888. return material;
  14889. };
  14890. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14891. for (var index = 0; index < parsedData.materials.length; index++) {
  14892. var parsedMaterial = parsedData.materials[index];
  14893. if (parsedMaterial.id === id) {
  14894. return parseMaterial(parsedMaterial, scene, rootUrl);
  14895. }
  14896. }
  14897. return null;
  14898. };
  14899. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14900. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14901. multiMaterial.id = parsedMultiMaterial.id;
  14902. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14903. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14904. var subMatId = parsedMultiMaterial.materials[matIndex];
  14905. if (subMatId) {
  14906. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14907. } else {
  14908. multiMaterial.subMaterials.push(null);
  14909. }
  14910. }
  14911. return multiMaterial;
  14912. };
  14913. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14914. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14915. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14916. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14917. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14918. var parsedFlare = parsedLensFlareSystem.flares[index];
  14919. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14920. }
  14921. return lensFlareSystem;
  14922. };
  14923. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14924. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14925. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14926. if (parsedParticleSystem.textureName) {
  14927. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14928. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14929. }
  14930. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14931. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14932. particleSystem.minSize = parsedParticleSystem.minSize;
  14933. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14934. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14935. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14936. particleSystem.emitter = emitter;
  14937. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14938. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14939. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14940. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14941. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14942. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14943. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14944. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14945. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14946. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14947. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14948. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14949. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14950. particleSystem.start();
  14951. return particleSystem;
  14952. };
  14953. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14954. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14955. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14956. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14957. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14958. shadowGenerator.getShadowMap().renderList.push(mesh);
  14959. }
  14960. if (parsedShadowGenerator.usePoissonSampling) {
  14961. shadowGenerator.usePoissonSampling = true;
  14962. } else {
  14963. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14964. }
  14965. return shadowGenerator;
  14966. };
  14967. var parseAnimation = function (parsedAnimation) {
  14968. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14969. var dataType = parsedAnimation.dataType;
  14970. var keys = [];
  14971. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14972. var key = parsedAnimation.keys[index];
  14973. var data;
  14974. switch (dataType) {
  14975. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14976. data = key.values[0];
  14977. break;
  14978. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14979. data = BABYLON.Quaternion.FromArray(key.values);
  14980. break;
  14981. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14982. data = BABYLON.Matrix.FromArray(key.values);
  14983. break;
  14984. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14985. default:
  14986. data = BABYLON.Vector3.FromArray(key.values);
  14987. break;
  14988. }
  14989. keys.push({
  14990. frame: key.frame,
  14991. value: data
  14992. });
  14993. }
  14994. animation.setKeys(keys);
  14995. return animation;
  14996. };
  14997. var parseLight = function (parsedLight, scene) {
  14998. var light;
  14999. switch (parsedLight.type) {
  15000. case 0:
  15001. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15002. break;
  15003. case 1:
  15004. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15005. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15006. break;
  15007. case 2:
  15008. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15009. break;
  15010. case 3:
  15011. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15012. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15013. break;
  15014. }
  15015. light.id = parsedLight.id;
  15016. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15017. if (parsedLight.intensity !== undefined) {
  15018. light.intensity = parsedLight.intensity;
  15019. }
  15020. if (parsedLight.range) {
  15021. light.range = parsedLight.range;
  15022. }
  15023. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15024. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15025. if (parsedLight.excludedMeshesIds) {
  15026. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15027. }
  15028. if (parsedLight.includedOnlyMeshesIds) {
  15029. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15030. }
  15031. if (parsedLight.animations) {
  15032. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15033. var parsedAnimation = parsedLight.animations[animationIndex];
  15034. light.animations.push(parseAnimation(parsedAnimation));
  15035. }
  15036. }
  15037. if (parsedLight.autoAnimate) {
  15038. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15039. }
  15040. };
  15041. var parseCamera = function (parsedCamera, scene) {
  15042. var camera;
  15043. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15044. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15045. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15046. var alpha = parsedCamera.alpha;
  15047. var beta = parsedCamera.beta;
  15048. var radius = parsedCamera.radius;
  15049. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15050. var eye_space = parsedCamera.eye_space;
  15051. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15052. } else {
  15053. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15054. }
  15055. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15056. var eye_space = parsedCamera.eye_space;
  15057. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15058. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15059. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15060. } else if (parsedCamera.type === "FollowCamera") {
  15061. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15062. camera.heightOffset = parsedCamera.heightOffset;
  15063. camera.radius = parsedCamera.radius;
  15064. camera.rotationOffset = parsedCamera.rotationOffset;
  15065. if (lockedTargetMesh)
  15066. camera.target = lockedTargetMesh;
  15067. } else if (parsedCamera.type === "GamepadCamera") {
  15068. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15069. } else if (parsedCamera.type === "OculusCamera") {
  15070. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15071. } else if (parsedCamera.type === "TouchCamera") {
  15072. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15073. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15074. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15075. } else if (parsedCamera.type === "WebVRCamera") {
  15076. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15077. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15078. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15079. } else {
  15080. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15081. }
  15082. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15083. camera.lockedTarget = lockedTargetMesh;
  15084. }
  15085. camera.id = parsedCamera.id;
  15086. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15087. if (parsedCamera.parentId) {
  15088. camera._waitingParentId = parsedCamera.parentId;
  15089. }
  15090. if (parsedCamera.target) {
  15091. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15092. } else {
  15093. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15094. }
  15095. camera.fov = parsedCamera.fov;
  15096. camera.minZ = parsedCamera.minZ;
  15097. camera.maxZ = parsedCamera.maxZ;
  15098. camera.speed = parsedCamera.speed;
  15099. camera.inertia = parsedCamera.inertia;
  15100. camera.checkCollisions = parsedCamera.checkCollisions;
  15101. camera.applyGravity = parsedCamera.applyGravity;
  15102. if (parsedCamera.ellipsoid) {
  15103. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15104. }
  15105. if (parsedCamera.animations) {
  15106. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15107. var parsedAnimation = parsedCamera.animations[animationIndex];
  15108. camera.animations.push(parseAnimation(parsedAnimation));
  15109. }
  15110. }
  15111. if (parsedCamera.autoAnimate) {
  15112. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15113. }
  15114. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15115. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15116. } else {
  15117. camera.layerMask = 0xFFFFFFFF;
  15118. }
  15119. return camera;
  15120. };
  15121. var parseGeometry = function (parsedGeometry, scene) {
  15122. var id = parsedGeometry.id;
  15123. return scene.getGeometryByID(id);
  15124. };
  15125. var parseBox = function (parsedBox, scene) {
  15126. if (parseGeometry(parsedBox, scene)) {
  15127. return null;
  15128. }
  15129. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15130. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15131. scene.pushGeometry(box, true);
  15132. return box;
  15133. };
  15134. var parseSphere = function (parsedSphere, scene) {
  15135. if (parseGeometry(parsedSphere, scene)) {
  15136. return null;
  15137. }
  15138. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15139. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15140. scene.pushGeometry(sphere, true);
  15141. return sphere;
  15142. };
  15143. var parseCylinder = function (parsedCylinder, scene) {
  15144. if (parseGeometry(parsedCylinder, scene)) {
  15145. return null;
  15146. }
  15147. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15148. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15149. scene.pushGeometry(cylinder, true);
  15150. return cylinder;
  15151. };
  15152. var parseTorus = function (parsedTorus, scene) {
  15153. if (parseGeometry(parsedTorus, scene)) {
  15154. return null;
  15155. }
  15156. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15157. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15158. scene.pushGeometry(torus, true);
  15159. return torus;
  15160. };
  15161. var parseGround = function (parsedGround, scene) {
  15162. if (parseGeometry(parsedGround, scene)) {
  15163. return null;
  15164. }
  15165. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15166. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15167. scene.pushGeometry(ground, true);
  15168. return ground;
  15169. };
  15170. var parsePlane = function (parsedPlane, scene) {
  15171. if (parseGeometry(parsedPlane, scene)) {
  15172. return null;
  15173. }
  15174. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15175. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15176. scene.pushGeometry(plane, true);
  15177. return plane;
  15178. };
  15179. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15180. if (parseGeometry(parsedTorusKnot, scene)) {
  15181. return null;
  15182. }
  15183. 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);
  15184. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15185. scene.pushGeometry(torusKnot, true);
  15186. return torusKnot;
  15187. };
  15188. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15189. if (parseGeometry(parsedVertexData, scene)) {
  15190. return null;
  15191. }
  15192. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15193. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15194. if (parsedVertexData.delayLoadingFile) {
  15195. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15196. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15197. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15198. geometry._delayInfo = [];
  15199. if (parsedVertexData.hasUVs) {
  15200. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15201. }
  15202. if (parsedVertexData.hasUVs2) {
  15203. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15204. }
  15205. if (parsedVertexData.hasColors) {
  15206. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15207. }
  15208. if (parsedVertexData.hasMatricesIndices) {
  15209. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15210. }
  15211. if (parsedVertexData.hasMatricesWeights) {
  15212. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15213. }
  15214. geometry._delayLoadingFunction = importVertexData;
  15215. } else {
  15216. importVertexData(parsedVertexData, geometry);
  15217. }
  15218. scene.pushGeometry(geometry, true);
  15219. return geometry;
  15220. };
  15221. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15222. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15223. mesh.id = parsedMesh.id;
  15224. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15225. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15226. if (parsedMesh.rotationQuaternion) {
  15227. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15228. } else if (parsedMesh.rotation) {
  15229. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15230. }
  15231. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15232. if (parsedMesh.localMatrix) {
  15233. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15234. } else if (parsedMesh.pivotMatrix) {
  15235. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15236. }
  15237. mesh.setEnabled(parsedMesh.isEnabled);
  15238. mesh.isVisible = parsedMesh.isVisible;
  15239. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15240. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15241. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15242. if (parsedMesh.pickable !== undefined) {
  15243. mesh.isPickable = parsedMesh.pickable;
  15244. }
  15245. mesh.receiveShadows = parsedMesh.receiveShadows;
  15246. mesh.billboardMode = parsedMesh.billboardMode;
  15247. if (parsedMesh.visibility !== undefined) {
  15248. mesh.visibility = parsedMesh.visibility;
  15249. }
  15250. mesh.checkCollisions = parsedMesh.checkCollisions;
  15251. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15252. if (parsedMesh.parentId) {
  15253. mesh._waitingParentId = parsedMesh.parentId;
  15254. }
  15255. if (parsedMesh.delayLoadingFile) {
  15256. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15257. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15258. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15259. if (parsedMesh._binaryInfo) {
  15260. mesh._binaryInfo = parsedMesh._binaryInfo;
  15261. }
  15262. mesh._delayInfo = [];
  15263. if (parsedMesh.hasUVs) {
  15264. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15265. }
  15266. if (parsedMesh.hasUVs2) {
  15267. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15268. }
  15269. if (parsedMesh.hasColors) {
  15270. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15271. }
  15272. if (parsedMesh.hasMatricesIndices) {
  15273. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15274. }
  15275. if (parsedMesh.hasMatricesWeights) {
  15276. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15277. }
  15278. mesh._delayLoadingFunction = importGeometry;
  15279. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15280. mesh._checkDelayState();
  15281. }
  15282. } else {
  15283. importGeometry(parsedMesh, mesh);
  15284. }
  15285. if (parsedMesh.materialId) {
  15286. mesh.setMaterialByID(parsedMesh.materialId);
  15287. } else {
  15288. mesh.material = null;
  15289. }
  15290. if (parsedMesh.skeletonId > -1) {
  15291. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15292. }
  15293. if (parsedMesh.physicsImpostor) {
  15294. if (!scene.isPhysicsEnabled()) {
  15295. scene.enablePhysics();
  15296. }
  15297. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15298. }
  15299. if (parsedMesh.animations) {
  15300. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15301. var parsedAnimation = parsedMesh.animations[animationIndex];
  15302. mesh.animations.push(parseAnimation(parsedAnimation));
  15303. }
  15304. }
  15305. if (parsedMesh.autoAnimate) {
  15306. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15307. }
  15308. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15309. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15310. } else {
  15311. mesh.layerMask = 0xFFFFFFFF;
  15312. }
  15313. if (parsedMesh.instances) {
  15314. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15315. var parsedInstance = parsedMesh.instances[index];
  15316. var instance = mesh.createInstance(parsedInstance.name);
  15317. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15318. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15319. if (parsedInstance.rotationQuaternion) {
  15320. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15321. } else if (parsedInstance.rotation) {
  15322. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15323. }
  15324. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15325. instance.checkCollisions = mesh.checkCollisions;
  15326. if (parsedMesh.animations) {
  15327. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15328. parsedAnimation = parsedMesh.animations[animationIndex];
  15329. instance.animations.push(parseAnimation(parsedAnimation));
  15330. }
  15331. }
  15332. }
  15333. }
  15334. return mesh;
  15335. };
  15336. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15337. names = (names instanceof Array) ? names : [names];
  15338. for (var i in names) {
  15339. if (mesh.name === names[i]) {
  15340. hierarchyIds.push(mesh.id);
  15341. return true;
  15342. }
  15343. }
  15344. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15345. hierarchyIds.push(mesh.id);
  15346. return true;
  15347. }
  15348. return false;
  15349. };
  15350. var importVertexData = function (parsedVertexData, geometry) {
  15351. var vertexData = new BABYLON.VertexData();
  15352. var positions = parsedVertexData.positions;
  15353. if (positions) {
  15354. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15355. }
  15356. var normals = parsedVertexData.normals;
  15357. if (normals) {
  15358. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15359. }
  15360. var uvs = parsedVertexData.uvs;
  15361. if (uvs) {
  15362. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15363. }
  15364. var uv2s = parsedVertexData.uv2s;
  15365. if (uv2s) {
  15366. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15367. }
  15368. var colors = parsedVertexData.colors;
  15369. if (colors) {
  15370. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15371. }
  15372. var matricesIndices = parsedVertexData.matricesIndices;
  15373. if (matricesIndices) {
  15374. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15375. }
  15376. var matricesWeights = parsedVertexData.matricesWeights;
  15377. if (matricesWeights) {
  15378. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15379. }
  15380. var indices = parsedVertexData.indices;
  15381. if (indices) {
  15382. vertexData.indices = indices;
  15383. }
  15384. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15385. };
  15386. var importGeometry = function (parsedGeometry, mesh) {
  15387. var scene = mesh.getScene();
  15388. var geometryId = parsedGeometry.geometryId;
  15389. if (geometryId) {
  15390. var geometry = scene.getGeometryByID(geometryId);
  15391. if (geometry) {
  15392. geometry.applyToMesh(mesh);
  15393. }
  15394. } else if (parsedGeometry instanceof ArrayBuffer) {
  15395. var binaryInfo = mesh._binaryInfo;
  15396. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15397. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15398. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15399. }
  15400. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15401. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15402. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15403. }
  15404. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15405. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15406. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15407. }
  15408. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15409. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15410. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15411. }
  15412. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15413. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15414. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15415. }
  15416. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15417. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15419. }
  15420. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15421. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15423. }
  15424. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15425. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15426. mesh.setIndices(indicesData);
  15427. }
  15428. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15429. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15430. mesh.subMeshes = [];
  15431. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15432. var materialIndex = subMeshesData[(i * 5) + 0];
  15433. var verticesStart = subMeshesData[(i * 5) + 1];
  15434. var verticesCount = subMeshesData[(i * 5) + 2];
  15435. var indexStart = subMeshesData[(i * 5) + 3];
  15436. var indexCount = subMeshesData[(i * 5) + 4];
  15437. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15438. }
  15439. }
  15440. return;
  15441. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15442. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15443. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15444. if (parsedGeometry.uvs) {
  15445. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15446. }
  15447. if (parsedGeometry.uvs2) {
  15448. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15449. }
  15450. if (parsedGeometry.colors) {
  15451. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15452. }
  15453. if (parsedGeometry.matricesIndices) {
  15454. if (!parsedGeometry.matricesIndices._isExpanded) {
  15455. var floatIndices = [];
  15456. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15457. var matricesIndex = parsedGeometry.matricesIndices[i];
  15458. floatIndices.push(matricesIndex & 0x000000FF);
  15459. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15460. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15461. floatIndices.push(matricesIndex >> 24);
  15462. }
  15463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15464. } else {
  15465. delete parsedGeometry.matricesIndices._isExpanded;
  15466. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15467. }
  15468. }
  15469. if (parsedGeometry.matricesWeights) {
  15470. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15471. }
  15472. mesh.setIndices(parsedGeometry.indices);
  15473. }
  15474. if (parsedGeometry.subMeshes) {
  15475. mesh.subMeshes = [];
  15476. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15477. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15478. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15479. }
  15480. }
  15481. if (mesh._shouldGenerateFlatShading) {
  15482. mesh.convertToFlatShadedMesh();
  15483. delete mesh._shouldGenerateFlatShading;
  15484. }
  15485. mesh.computeWorldMatrix(true);
  15486. if (scene._selectionOctree) {
  15487. scene._selectionOctree.addMesh(mesh);
  15488. }
  15489. };
  15490. BABYLON.SceneLoader.RegisterPlugin({
  15491. extensions: ".babylon",
  15492. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15493. var parsedData = JSON.parse(data);
  15494. var loadedSkeletonsIds = [];
  15495. var loadedMaterialsIds = [];
  15496. var hierarchyIds = [];
  15497. for (var index = 0; index < parsedData.meshes.length; index++) {
  15498. var parsedMesh = parsedData.meshes[index];
  15499. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15500. if (meshesNames instanceof Array) {
  15501. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15502. }
  15503. if (parsedMesh.materialId) {
  15504. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15505. if (!materialFound) {
  15506. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15507. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15508. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15509. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15510. var subMatId = parsedMultiMaterial.materials[matIndex];
  15511. loadedMaterialsIds.push(subMatId);
  15512. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15513. }
  15514. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15515. parseMultiMaterial(parsedMultiMaterial, scene);
  15516. materialFound = true;
  15517. break;
  15518. }
  15519. }
  15520. }
  15521. if (!materialFound) {
  15522. loadedMaterialsIds.push(parsedMesh.materialId);
  15523. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15524. }
  15525. }
  15526. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15527. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15528. if (!skeletonAlreadyLoaded) {
  15529. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15530. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15531. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15532. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15533. loadedSkeletonsIds.push(parsedSkeleton.id);
  15534. }
  15535. }
  15536. }
  15537. }
  15538. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15539. meshes.push(mesh);
  15540. }
  15541. }
  15542. for (index = 0; index < scene.meshes.length; index++) {
  15543. var currentMesh = scene.meshes[index];
  15544. if (currentMesh._waitingParentId) {
  15545. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15546. currentMesh._waitingParentId = undefined;
  15547. }
  15548. }
  15549. if (parsedData.particleSystems) {
  15550. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15551. var parsedParticleSystem = parsedData.particleSystems[index];
  15552. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15553. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15554. }
  15555. }
  15556. }
  15557. return true;
  15558. },
  15559. load: function (scene, data, rootUrl) {
  15560. var parsedData = JSON.parse(data);
  15561. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15562. scene.autoClear = parsedData.autoClear;
  15563. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15564. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15565. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15566. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15567. scene.fogMode = parsedData.fogMode;
  15568. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15569. scene.fogStart = parsedData.fogStart;
  15570. scene.fogEnd = parsedData.fogEnd;
  15571. scene.fogDensity = parsedData.fogDensity;
  15572. }
  15573. for (var index = 0; index < parsedData.lights.length; index++) {
  15574. var parsedLight = parsedData.lights[index];
  15575. parseLight(parsedLight, scene);
  15576. }
  15577. if (parsedData.materials) {
  15578. for (index = 0; index < parsedData.materials.length; index++) {
  15579. var parsedMaterial = parsedData.materials[index];
  15580. parseMaterial(parsedMaterial, scene, rootUrl);
  15581. }
  15582. }
  15583. if (parsedData.multiMaterials) {
  15584. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15585. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15586. parseMultiMaterial(parsedMultiMaterial, scene);
  15587. }
  15588. }
  15589. if (parsedData.skeletons) {
  15590. for (index = 0; index < parsedData.skeletons.length; index++) {
  15591. var parsedSkeleton = parsedData.skeletons[index];
  15592. parseSkeleton(parsedSkeleton, scene);
  15593. }
  15594. }
  15595. var geometries = parsedData.geometries;
  15596. if (geometries) {
  15597. var boxes = geometries.boxes;
  15598. if (boxes) {
  15599. for (index = 0; index < boxes.length; index++) {
  15600. var parsedBox = boxes[index];
  15601. parseBox(parsedBox, scene);
  15602. }
  15603. }
  15604. var spheres = geometries.spheres;
  15605. if (spheres) {
  15606. for (index = 0; index < spheres.length; index++) {
  15607. var parsedSphere = spheres[index];
  15608. parseSphere(parsedSphere, scene);
  15609. }
  15610. }
  15611. var cylinders = geometries.cylinders;
  15612. if (cylinders) {
  15613. for (index = 0; index < cylinders.length; index++) {
  15614. var parsedCylinder = cylinders[index];
  15615. parseCylinder(parsedCylinder, scene);
  15616. }
  15617. }
  15618. var toruses = geometries.toruses;
  15619. if (toruses) {
  15620. for (index = 0; index < toruses.length; index++) {
  15621. var parsedTorus = toruses[index];
  15622. parseTorus(parsedTorus, scene);
  15623. }
  15624. }
  15625. var grounds = geometries.grounds;
  15626. if (grounds) {
  15627. for (index = 0; index < grounds.length; index++) {
  15628. var parsedGround = grounds[index];
  15629. parseGround(parsedGround, scene);
  15630. }
  15631. }
  15632. var planes = geometries.planes;
  15633. if (planes) {
  15634. for (index = 0; index < planes.length; index++) {
  15635. var parsedPlane = planes[index];
  15636. parsePlane(parsedPlane, scene);
  15637. }
  15638. }
  15639. var torusKnots = geometries.torusKnots;
  15640. if (torusKnots) {
  15641. for (index = 0; index < torusKnots.length; index++) {
  15642. var parsedTorusKnot = torusKnots[index];
  15643. parseTorusKnot(parsedTorusKnot, scene);
  15644. }
  15645. }
  15646. var vertexData = geometries.vertexData;
  15647. if (vertexData) {
  15648. for (index = 0; index < vertexData.length; index++) {
  15649. var parsedVertexData = vertexData[index];
  15650. parseVertexData(parsedVertexData, scene, rootUrl);
  15651. }
  15652. }
  15653. }
  15654. for (index = 0; index < parsedData.meshes.length; index++) {
  15655. var parsedMesh = parsedData.meshes[index];
  15656. parseMesh(parsedMesh, scene, rootUrl);
  15657. }
  15658. for (index = 0; index < parsedData.cameras.length; index++) {
  15659. var parsedCamera = parsedData.cameras[index];
  15660. parseCamera(parsedCamera, scene);
  15661. }
  15662. if (parsedData.activeCameraID) {
  15663. scene.setActiveCameraByID(parsedData.activeCameraID);
  15664. }
  15665. for (index = 0; index < scene.cameras.length; index++) {
  15666. var camera = scene.cameras[index];
  15667. if (camera._waitingParentId) {
  15668. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  15669. camera._waitingParentId = undefined;
  15670. }
  15671. }
  15672. for (index = 0; index < scene.meshes.length; index++) {
  15673. var mesh = scene.meshes[index];
  15674. if (mesh._waitingParentId) {
  15675. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15676. mesh._waitingParentId = undefined;
  15677. }
  15678. }
  15679. if (parsedData.particleSystems) {
  15680. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15681. var parsedParticleSystem = parsedData.particleSystems[index];
  15682. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15683. }
  15684. }
  15685. if (parsedData.lensFlareSystems) {
  15686. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15687. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15688. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15689. }
  15690. }
  15691. if (parsedData.shadowGenerators) {
  15692. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15693. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15694. parseShadowGenerator(parsedShadowGenerator, scene);
  15695. }
  15696. }
  15697. return true;
  15698. }
  15699. });
  15700. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15701. var Internals = BABYLON.Internals;
  15702. })(BABYLON || (BABYLON = {}));
  15703. var BABYLON;
  15704. (function (BABYLON) {
  15705. var currentCSGMeshId = 0;
  15706. var Vertex = (function () {
  15707. function Vertex(pos, normal, uv) {
  15708. this.pos = pos;
  15709. this.normal = normal;
  15710. this.uv = uv;
  15711. }
  15712. Vertex.prototype.clone = function () {
  15713. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15714. };
  15715. Vertex.prototype.flip = function () {
  15716. this.normal = this.normal.scale(-1);
  15717. };
  15718. Vertex.prototype.interpolate = function (other, t) {
  15719. 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));
  15720. };
  15721. return Vertex;
  15722. })();
  15723. var Plane = (function () {
  15724. function Plane(normal, w) {
  15725. this.normal = normal;
  15726. this.w = w;
  15727. }
  15728. Plane.FromPoints = function (a, b, c) {
  15729. var v0 = c.subtract(a);
  15730. var v1 = b.subtract(a);
  15731. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15732. return null;
  15733. }
  15734. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15735. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15736. };
  15737. Plane.prototype.clone = function () {
  15738. return new Plane(this.normal.clone(), this.w);
  15739. };
  15740. Plane.prototype.flip = function () {
  15741. this.normal.scaleInPlace(-1);
  15742. this.w = -this.w;
  15743. };
  15744. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15745. var COPLANAR = 0;
  15746. var FRONT = 1;
  15747. var BACK = 2;
  15748. var SPANNING = 3;
  15749. var polygonType = 0;
  15750. var types = [];
  15751. for (var i = 0; i < polygon.vertices.length; i++) {
  15752. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15753. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15754. polygonType |= type;
  15755. types.push(type);
  15756. }
  15757. switch (polygonType) {
  15758. case COPLANAR:
  15759. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15760. break;
  15761. case FRONT:
  15762. front.push(polygon);
  15763. break;
  15764. case BACK:
  15765. back.push(polygon);
  15766. break;
  15767. case SPANNING:
  15768. var f = [], b = [];
  15769. for (i = 0; i < polygon.vertices.length; i++) {
  15770. var j = (i + 1) % polygon.vertices.length;
  15771. var ti = types[i], tj = types[j];
  15772. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15773. if (ti != BACK)
  15774. f.push(vi);
  15775. if (ti != FRONT)
  15776. b.push(ti != BACK ? vi.clone() : vi);
  15777. if ((ti | tj) == SPANNING) {
  15778. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15779. var v = vi.interpolate(vj, t);
  15780. f.push(v);
  15781. b.push(v.clone());
  15782. }
  15783. }
  15784. if (f.length >= 3) {
  15785. var poly = new Polygon(f, polygon.shared);
  15786. if (poly.plane)
  15787. front.push(poly);
  15788. }
  15789. if (b.length >= 3) {
  15790. poly = new Polygon(b, polygon.shared);
  15791. if (poly.plane)
  15792. back.push(poly);
  15793. }
  15794. break;
  15795. }
  15796. };
  15797. Plane.EPSILON = 1e-5;
  15798. return Plane;
  15799. })();
  15800. var Polygon = (function () {
  15801. function Polygon(vertices, shared) {
  15802. this.vertices = vertices;
  15803. this.shared = shared;
  15804. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15805. }
  15806. Polygon.prototype.clone = function () {
  15807. var vertices = this.vertices.map(function (v) {
  15808. return v.clone();
  15809. });
  15810. return new Polygon(vertices, this.shared);
  15811. };
  15812. Polygon.prototype.flip = function () {
  15813. this.vertices.reverse().map(function (v) {
  15814. v.flip();
  15815. });
  15816. this.plane.flip();
  15817. };
  15818. return Polygon;
  15819. })();
  15820. var Node = (function () {
  15821. function Node(polygons) {
  15822. this.plane = null;
  15823. this.front = null;
  15824. this.back = null;
  15825. this.polygons = [];
  15826. if (polygons) {
  15827. this.build(polygons);
  15828. }
  15829. }
  15830. Node.prototype.clone = function () {
  15831. var node = new Node();
  15832. node.plane = this.plane && this.plane.clone();
  15833. node.front = this.front && this.front.clone();
  15834. node.back = this.back && this.back.clone();
  15835. node.polygons = this.polygons.map(function (p) {
  15836. return p.clone();
  15837. });
  15838. return node;
  15839. };
  15840. Node.prototype.invert = function () {
  15841. for (var i = 0; i < this.polygons.length; i++) {
  15842. this.polygons[i].flip();
  15843. }
  15844. if (this.plane) {
  15845. this.plane.flip();
  15846. }
  15847. if (this.front) {
  15848. this.front.invert();
  15849. }
  15850. if (this.back) {
  15851. this.back.invert();
  15852. }
  15853. var temp = this.front;
  15854. this.front = this.back;
  15855. this.back = temp;
  15856. };
  15857. Node.prototype.clipPolygons = function (polygons) {
  15858. if (!this.plane)
  15859. return polygons.slice();
  15860. var front = [], back = [];
  15861. for (var i = 0; i < polygons.length; i++) {
  15862. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15863. }
  15864. if (this.front) {
  15865. front = this.front.clipPolygons(front);
  15866. }
  15867. if (this.back) {
  15868. back = this.back.clipPolygons(back);
  15869. } else {
  15870. back = [];
  15871. }
  15872. return front.concat(back);
  15873. };
  15874. Node.prototype.clipTo = function (bsp) {
  15875. this.polygons = bsp.clipPolygons(this.polygons);
  15876. if (this.front)
  15877. this.front.clipTo(bsp);
  15878. if (this.back)
  15879. this.back.clipTo(bsp);
  15880. };
  15881. Node.prototype.allPolygons = function () {
  15882. var polygons = this.polygons.slice();
  15883. if (this.front)
  15884. polygons = polygons.concat(this.front.allPolygons());
  15885. if (this.back)
  15886. polygons = polygons.concat(this.back.allPolygons());
  15887. return polygons;
  15888. };
  15889. Node.prototype.build = function (polygons) {
  15890. if (!polygons.length)
  15891. return;
  15892. if (!this.plane)
  15893. this.plane = polygons[0].plane.clone();
  15894. var front = [], back = [];
  15895. for (var i = 0; i < polygons.length; i++) {
  15896. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15897. }
  15898. if (front.length) {
  15899. if (!this.front)
  15900. this.front = new Node();
  15901. this.front.build(front);
  15902. }
  15903. if (back.length) {
  15904. if (!this.back)
  15905. this.back = new Node();
  15906. this.back.build(back);
  15907. }
  15908. };
  15909. return Node;
  15910. })();
  15911. var CSG = (function () {
  15912. function CSG() {
  15913. this.polygons = new Array();
  15914. }
  15915. CSG.FromMesh = function (mesh) {
  15916. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15917. if (mesh instanceof BABYLON.Mesh) {
  15918. mesh.computeWorldMatrix(true);
  15919. var matrix = mesh.getWorldMatrix();
  15920. var meshPosition = mesh.position.clone();
  15921. var meshRotation = mesh.rotation.clone();
  15922. var meshScaling = mesh.scaling.clone();
  15923. } else {
  15924. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15925. }
  15926. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15927. var subMeshes = mesh.subMeshes;
  15928. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15929. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15930. vertices = [];
  15931. for (var j = 0; j < 3; j++) {
  15932. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15933. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15934. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15935. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15936. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15937. vertex = new Vertex(position, normal, uv);
  15938. vertices.push(vertex);
  15939. }
  15940. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15941. if (polygon.plane)
  15942. polygons.push(polygon);
  15943. }
  15944. }
  15945. var csg = CSG.FromPolygons(polygons);
  15946. csg.matrix = matrix;
  15947. csg.position = meshPosition;
  15948. csg.rotation = meshRotation;
  15949. csg.scaling = meshScaling;
  15950. currentCSGMeshId++;
  15951. return csg;
  15952. };
  15953. CSG.FromPolygons = function (polygons) {
  15954. var csg = new BABYLON.CSG();
  15955. csg.polygons = polygons;
  15956. return csg;
  15957. };
  15958. CSG.prototype.clone = function () {
  15959. var csg = new BABYLON.CSG();
  15960. csg.polygons = this.polygons.map(function (p) {
  15961. return p.clone();
  15962. });
  15963. csg.copyTransformAttributes(this);
  15964. return csg;
  15965. };
  15966. CSG.prototype.toPolygons = function () {
  15967. return this.polygons;
  15968. };
  15969. CSG.prototype.union = function (csg) {
  15970. var a = new Node(this.clone().polygons);
  15971. var b = new Node(csg.clone().polygons);
  15972. a.clipTo(b);
  15973. b.clipTo(a);
  15974. b.invert();
  15975. b.clipTo(a);
  15976. b.invert();
  15977. a.build(b.allPolygons());
  15978. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15979. };
  15980. CSG.prototype.unionInPlace = function (csg) {
  15981. var a = new Node(this.polygons);
  15982. var b = new Node(csg.polygons);
  15983. a.clipTo(b);
  15984. b.clipTo(a);
  15985. b.invert();
  15986. b.clipTo(a);
  15987. b.invert();
  15988. a.build(b.allPolygons());
  15989. this.polygons = a.allPolygons();
  15990. };
  15991. CSG.prototype.subtract = function (csg) {
  15992. var a = new Node(this.clone().polygons);
  15993. var b = new Node(csg.clone().polygons);
  15994. a.invert();
  15995. a.clipTo(b);
  15996. b.clipTo(a);
  15997. b.invert();
  15998. b.clipTo(a);
  15999. b.invert();
  16000. a.build(b.allPolygons());
  16001. a.invert();
  16002. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16003. };
  16004. CSG.prototype.subtractInPlace = function (csg) {
  16005. var a = new Node(this.polygons);
  16006. var b = new Node(csg.polygons);
  16007. a.invert();
  16008. a.clipTo(b);
  16009. b.clipTo(a);
  16010. b.invert();
  16011. b.clipTo(a);
  16012. b.invert();
  16013. a.build(b.allPolygons());
  16014. a.invert();
  16015. this.polygons = a.allPolygons();
  16016. };
  16017. CSG.prototype.intersect = function (csg) {
  16018. var a = new Node(this.clone().polygons);
  16019. var b = new Node(csg.clone().polygons);
  16020. a.invert();
  16021. b.clipTo(a);
  16022. b.invert();
  16023. a.clipTo(b);
  16024. b.clipTo(a);
  16025. a.build(b.allPolygons());
  16026. a.invert();
  16027. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16028. };
  16029. CSG.prototype.intersectInPlace = function (csg) {
  16030. var a = new Node(this.polygons);
  16031. var b = new Node(csg.polygons);
  16032. a.invert();
  16033. b.clipTo(a);
  16034. b.invert();
  16035. a.clipTo(b);
  16036. b.clipTo(a);
  16037. a.build(b.allPolygons());
  16038. a.invert();
  16039. this.polygons = a.allPolygons();
  16040. };
  16041. CSG.prototype.inverse = function () {
  16042. var csg = this.clone();
  16043. csg.inverseInPlace();
  16044. return csg;
  16045. };
  16046. CSG.prototype.inverseInPlace = function () {
  16047. this.polygons.map(function (p) {
  16048. p.flip();
  16049. });
  16050. };
  16051. CSG.prototype.copyTransformAttributes = function (csg) {
  16052. this.matrix = csg.matrix;
  16053. this.position = csg.position;
  16054. this.rotation = csg.rotation;
  16055. this.scaling = csg.scaling;
  16056. return this;
  16057. };
  16058. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16059. var matrix = this.matrix.clone();
  16060. matrix.invert();
  16061. 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;
  16062. if (keepSubMeshes) {
  16063. polygons.sort(function (a, b) {
  16064. if (a.shared.meshId === b.shared.meshId) {
  16065. return a.shared.subMeshId - b.shared.subMeshId;
  16066. } else {
  16067. return a.shared.meshId - b.shared.meshId;
  16068. }
  16069. });
  16070. }
  16071. for (var i = 0, il = polygons.length; i < il; i++) {
  16072. polygon = polygons[i];
  16073. if (!subMesh_dict[polygon.shared.meshId]) {
  16074. subMesh_dict[polygon.shared.meshId] = {};
  16075. }
  16076. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16077. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16078. indexStart: +Infinity,
  16079. indexEnd: -Infinity,
  16080. materialIndex: polygon.shared.materialIndex
  16081. };
  16082. }
  16083. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16084. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16085. polygonIndices[0] = 0;
  16086. polygonIndices[1] = j - 1;
  16087. polygonIndices[2] = j;
  16088. for (var k = 0; k < 3; k++) {
  16089. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16090. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16091. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16092. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16093. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16094. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16095. 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)) {
  16096. vertices.push(vertex.x, vertex.y, vertex.z);
  16097. uvs.push(uv.x, uv.y);
  16098. normals.push(normal.x, normal.y, normal.z);
  16099. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16100. }
  16101. indices.push(vertex_idx);
  16102. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16103. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16104. currentIndex++;
  16105. }
  16106. }
  16107. }
  16108. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16109. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16110. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16111. mesh.setIndices(indices);
  16112. if (keepSubMeshes) {
  16113. var materialIndexOffset = 0, materialMaxIndex;
  16114. mesh.subMeshes.length = 0;
  16115. for (var m in subMesh_dict) {
  16116. materialMaxIndex = -1;
  16117. for (var sm in subMesh_dict[m]) {
  16118. subMesh_obj = subMesh_dict[m][sm];
  16119. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16120. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16121. }
  16122. materialIndexOffset += ++materialMaxIndex;
  16123. }
  16124. }
  16125. return mesh;
  16126. };
  16127. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16128. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16129. mesh.material = material;
  16130. mesh.position.copyFrom(this.position);
  16131. mesh.rotation.copyFrom(this.rotation);
  16132. mesh.scaling.copyFrom(this.scaling);
  16133. mesh.computeWorldMatrix(true);
  16134. return mesh;
  16135. };
  16136. return CSG;
  16137. })();
  16138. BABYLON.CSG = CSG;
  16139. })(BABYLON || (BABYLON = {}));
  16140. var __extends = this.__extends || function (d, b) {
  16141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16142. function __() { this.constructor = d; }
  16143. __.prototype = b.prototype;
  16144. d.prototype = new __();
  16145. };
  16146. var BABYLON;
  16147. (function (BABYLON) {
  16148. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16149. __extends(OculusDistortionCorrectionPostProcess, _super);
  16150. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16151. var _this = this;
  16152. _super.call(this, name, "oculusDistortionCorrection", [
  16153. 'LensCenter',
  16154. 'Scale',
  16155. 'ScaleIn',
  16156. 'HmdWarpParam'
  16157. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16158. this._isRightEye = isRightEye;
  16159. this._distortionFactors = cameraSettings.DistortionK;
  16160. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16161. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16162. this.onSizeChanged = function () {
  16163. _this.aspectRatio = _this.width * .5 / _this.height;
  16164. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16165. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16166. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16167. };
  16168. this.onApply = function (effect) {
  16169. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16170. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16171. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16172. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16173. };
  16174. }
  16175. return OculusDistortionCorrectionPostProcess;
  16176. })(BABYLON.PostProcess);
  16177. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16178. })(BABYLON || (BABYLON = {}));
  16179. var BABYLON;
  16180. (function (BABYLON) {
  16181. (function (JoystickAxis) {
  16182. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16183. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16184. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16185. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16186. var JoystickAxis = BABYLON.JoystickAxis;
  16187. var VirtualJoystick = (function () {
  16188. function VirtualJoystick(leftJoystick) {
  16189. var _this = this;
  16190. if (leftJoystick) {
  16191. this._leftJoystick = true;
  16192. } else {
  16193. this._leftJoystick = false;
  16194. }
  16195. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16196. VirtualJoystick._globalJoystickIndex++;
  16197. this._axisTargetedByLeftAndRight = 0 /* X */;
  16198. this._axisTargetedByUpAndDown = 1 /* Y */;
  16199. this.reverseLeftRight = false;
  16200. this.reverseUpDown = false;
  16201. this._touches = new BABYLON.VirtualJoystick.Collection();
  16202. this.deltaPosition = BABYLON.Vector3.Zero();
  16203. this._joystickSensibility = 25;
  16204. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16205. this._rotationSpeed = 25;
  16206. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16207. this._rotateOnAxisRelativeToMesh = false;
  16208. if (!VirtualJoystick.vjCanvas) {
  16209. window.addEventListener("resize", function () {
  16210. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16211. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16212. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16213. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16214. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16215. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16216. }, false);
  16217. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16218. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16219. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16220. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16221. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16222. VirtualJoystick.vjCanvas.style.width = "100%";
  16223. VirtualJoystick.vjCanvas.style.height = "100%";
  16224. VirtualJoystick.vjCanvas.style.position = "absolute";
  16225. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16226. VirtualJoystick.vjCanvas.style.top = "0px";
  16227. VirtualJoystick.vjCanvas.style.left = "0px";
  16228. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16229. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16230. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16231. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16232. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16233. document.body.appendChild(VirtualJoystick.vjCanvas);
  16234. }
  16235. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16236. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16237. this.pressed = false;
  16238. this._joystickColor = "cyan";
  16239. this._joystickPointerID = -1;
  16240. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16241. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16242. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16243. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16244. _this._onPointerDown(evt);
  16245. }, false);
  16246. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16247. _this._onPointerMove(evt);
  16248. }, false);
  16249. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16250. _this._onPointerUp(evt);
  16251. }, false);
  16252. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16253. _this._onPointerUp(evt);
  16254. }, false);
  16255. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16256. evt.preventDefault();
  16257. }, false);
  16258. requestAnimationFrame(function () {
  16259. _this._drawVirtualJoystick();
  16260. });
  16261. }
  16262. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16263. this._joystickSensibility = newJoystickSensibility;
  16264. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16265. };
  16266. VirtualJoystick.prototype._onPointerDown = function (e) {
  16267. var positionOnScreenCondition;
  16268. e.preventDefault();
  16269. if (this._leftJoystick === true) {
  16270. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16271. } else {
  16272. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16273. }
  16274. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16275. this._joystickPointerID = e.pointerId;
  16276. this._joystickPointerStartPos.x = e.clientX;
  16277. this._joystickPointerStartPos.y = e.clientY;
  16278. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16279. this._deltaJoystickVector.x = 0;
  16280. this._deltaJoystickVector.y = 0;
  16281. this.pressed = true;
  16282. this._touches.add(e.pointerId.toString(), e);
  16283. } else {
  16284. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16285. this._action();
  16286. this._touches.add(e.pointerId.toString(), e);
  16287. }
  16288. }
  16289. };
  16290. VirtualJoystick.prototype._onPointerMove = function (e) {
  16291. if (this._joystickPointerID == e.pointerId) {
  16292. this._joystickPointerPos.x = e.clientX;
  16293. this._joystickPointerPos.y = e.clientY;
  16294. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16295. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16296. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16297. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16298. switch (this._axisTargetedByLeftAndRight) {
  16299. case 0 /* X */:
  16300. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16301. break;
  16302. case 1 /* Y */:
  16303. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16304. break;
  16305. case 2 /* Z */:
  16306. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16307. break;
  16308. }
  16309. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16310. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16311. switch (this._axisTargetedByUpAndDown) {
  16312. case 0 /* X */:
  16313. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16314. break;
  16315. case 1 /* Y */:
  16316. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16317. break;
  16318. case 2 /* Z */:
  16319. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16320. break;
  16321. }
  16322. } else {
  16323. if (this._touches.item(e.pointerId.toString())) {
  16324. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16325. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16326. }
  16327. }
  16328. };
  16329. VirtualJoystick.prototype._onPointerUp = function (e) {
  16330. this._clearCanvas();
  16331. if (this._joystickPointerID == e.pointerId) {
  16332. this._joystickPointerID = -1;
  16333. this.pressed = false;
  16334. }
  16335. this._deltaJoystickVector.x = 0;
  16336. this._deltaJoystickVector.y = 0;
  16337. this._touches.remove(e.pointerId.toString());
  16338. };
  16339. /**
  16340. * Change the color of the virtual joystick
  16341. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16342. */
  16343. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16344. this._joystickColor = newColor;
  16345. };
  16346. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16347. this._action = action;
  16348. };
  16349. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16350. switch (axis) {
  16351. case 0 /* X */:
  16352. case 1 /* Y */:
  16353. case 2 /* Z */:
  16354. this._axisTargetedByLeftAndRight = axis;
  16355. break;
  16356. default:
  16357. this._axisTargetedByLeftAndRight = 0 /* X */;
  16358. break;
  16359. }
  16360. };
  16361. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16362. switch (axis) {
  16363. case 0 /* X */:
  16364. case 1 /* Y */:
  16365. case 2 /* Z */:
  16366. this._axisTargetedByUpAndDown = axis;
  16367. break;
  16368. default:
  16369. this._axisTargetedByUpAndDown = 1 /* Y */;
  16370. break;
  16371. }
  16372. };
  16373. VirtualJoystick.prototype._clearCanvas = function () {
  16374. if (this._leftJoystick) {
  16375. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16376. } else {
  16377. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16378. }
  16379. };
  16380. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16381. var _this = this;
  16382. if (this.pressed) {
  16383. this._clearCanvas();
  16384. this._touches.forEach(function (touch) {
  16385. if (touch.pointerId === _this._joystickPointerID) {
  16386. VirtualJoystick.vjCanvasContext.beginPath();
  16387. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16388. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16389. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16390. VirtualJoystick.vjCanvasContext.stroke();
  16391. VirtualJoystick.vjCanvasContext.beginPath();
  16392. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16393. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16394. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16395. VirtualJoystick.vjCanvasContext.stroke();
  16396. VirtualJoystick.vjCanvasContext.beginPath();
  16397. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16398. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16399. VirtualJoystick.vjCanvasContext.stroke();
  16400. } else {
  16401. VirtualJoystick.vjCanvasContext.beginPath();
  16402. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16403. VirtualJoystick.vjCanvasContext.beginPath();
  16404. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16405. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16406. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16407. VirtualJoystick.vjCanvasContext.stroke();
  16408. }
  16409. ;
  16410. });
  16411. }
  16412. requestAnimationFrame(function () {
  16413. _this._drawVirtualJoystick();
  16414. });
  16415. };
  16416. VirtualJoystick.prototype.releaseCanvas = function () {
  16417. if (VirtualJoystick.vjCanvas) {
  16418. document.body.removeChild(VirtualJoystick.vjCanvas);
  16419. VirtualJoystick.vjCanvas = null;
  16420. }
  16421. };
  16422. VirtualJoystick._globalJoystickIndex = 0;
  16423. return VirtualJoystick;
  16424. })();
  16425. BABYLON.VirtualJoystick = VirtualJoystick;
  16426. })(BABYLON || (BABYLON = {}));
  16427. var BABYLON;
  16428. (function (BABYLON) {
  16429. (function (VirtualJoystick) {
  16430. var Collection = (function () {
  16431. function Collection() {
  16432. this._count = 0;
  16433. this._collection = new Array();
  16434. }
  16435. Collection.prototype.Count = function () {
  16436. return this._count;
  16437. };
  16438. Collection.prototype.add = function (key, item) {
  16439. if (this._collection[key] != undefined) {
  16440. return undefined;
  16441. }
  16442. this._collection[key] = item;
  16443. return ++this._count;
  16444. };
  16445. Collection.prototype.remove = function (key) {
  16446. if (this._collection[key] == undefined) {
  16447. return undefined;
  16448. }
  16449. delete this._collection[key];
  16450. return --this._count;
  16451. };
  16452. Collection.prototype.item = function (key) {
  16453. return this._collection[key];
  16454. };
  16455. Collection.prototype.forEach = function (block) {
  16456. var key;
  16457. for (key in this._collection) {
  16458. if (this._collection.hasOwnProperty(key)) {
  16459. block(this._collection[key]);
  16460. }
  16461. }
  16462. };
  16463. return Collection;
  16464. })();
  16465. VirtualJoystick.Collection = Collection;
  16466. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16467. var VirtualJoystick = BABYLON.VirtualJoystick;
  16468. })(BABYLON || (BABYLON = {}));
  16469. var __extends = this.__extends || function (d, b) {
  16470. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16471. function __() { this.constructor = d; }
  16472. __.prototype = b.prototype;
  16473. d.prototype = new __();
  16474. };
  16475. var BABYLON;
  16476. (function (BABYLON) {
  16477. var OculusRiftDevKit2013_Metric = {
  16478. HResolution: 1280,
  16479. VResolution: 800,
  16480. HScreenSize: 0.149759993,
  16481. VScreenSize: 0.0935999975,
  16482. VScreenCenter: 0.0467999987,
  16483. EyeToScreenDistance: 0.0410000011,
  16484. LensSeparationDistance: 0.0635000020,
  16485. InterpupillaryDistance: 0.0640000030,
  16486. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16487. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16488. PostProcessScaleFactor: 1.714605507808412,
  16489. LensCenterOffset: 0.151976421
  16490. };
  16491. var _OculusInnerCamera = (function (_super) {
  16492. __extends(_OculusInnerCamera, _super);
  16493. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16494. _super.call(this, name, position, scene);
  16495. this._workMatrix = new BABYLON.Matrix();
  16496. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16497. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16498. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16499. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16500. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16501. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16502. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16503. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16504. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16505. }
  16506. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16507. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16508. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16509. return this._projectionMatrix;
  16510. };
  16511. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16512. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16513. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16514. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16515. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16516. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16517. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16518. return this._viewMatrix;
  16519. };
  16520. return _OculusInnerCamera;
  16521. })(BABYLON.FreeCamera);
  16522. var OculusCamera = (function (_super) {
  16523. __extends(OculusCamera, _super);
  16524. function OculusCamera(name, position, scene) {
  16525. _super.call(this, name, position, scene);
  16526. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16527. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16528. this.subCameras.push(this._leftCamera);
  16529. this.subCameras.push(this._rightCamera);
  16530. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16531. }
  16532. OculusCamera.prototype._update = function () {
  16533. this._leftCamera.position.copyFrom(this.position);
  16534. this._rightCamera.position.copyFrom(this.position);
  16535. this._updateCamera(this._leftCamera);
  16536. this._updateCamera(this._rightCamera);
  16537. _super.prototype._update.call(this);
  16538. };
  16539. OculusCamera.prototype._updateCamera = function (camera) {
  16540. camera.minZ = this.minZ;
  16541. camera.maxZ = this.maxZ;
  16542. camera.rotation.x = this.rotation.x;
  16543. camera.rotation.y = this.rotation.y;
  16544. camera.rotation.z = this.rotation.z;
  16545. };
  16546. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16547. var yaw = evt.alpha / 180 * Math.PI;
  16548. var pitch = evt.beta / 180 * Math.PI;
  16549. var roll = evt.gamma / 180 * Math.PI;
  16550. if (!this._offsetOrientation) {
  16551. this._offsetOrientation = {
  16552. yaw: yaw,
  16553. pitch: pitch,
  16554. roll: roll
  16555. };
  16556. return;
  16557. } else {
  16558. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16559. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16560. this.rotation.z += this._offsetOrientation.roll - roll;
  16561. this._offsetOrientation.yaw = yaw;
  16562. this._offsetOrientation.pitch = pitch;
  16563. this._offsetOrientation.roll = roll;
  16564. }
  16565. };
  16566. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16567. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16568. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16569. };
  16570. OculusCamera.prototype.detachControl = function (element) {
  16571. _super.prototype.detachControl.call(this, element);
  16572. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16573. };
  16574. return OculusCamera;
  16575. })(BABYLON.FreeCamera);
  16576. BABYLON.OculusCamera = OculusCamera;
  16577. })(BABYLON || (BABYLON = {}));
  16578. var __extends = this.__extends || function (d, b) {
  16579. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16580. function __() { this.constructor = d; }
  16581. __.prototype = b.prototype;
  16582. d.prototype = new __();
  16583. };
  16584. var BABYLON;
  16585. (function (BABYLON) {
  16586. var OculusRiftDevKit2013_Metric = {
  16587. HResolution: 1280,
  16588. VResolution: 800,
  16589. HScreenSize: 0.149759993,
  16590. VScreenSize: 0.0935999975,
  16591. VScreenCenter: 0.0467999987,
  16592. EyeToScreenDistance: 0.0410000011,
  16593. LensSeparationDistance: 0.0635000020,
  16594. InterpupillaryDistance: 0.0640000030,
  16595. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16596. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16597. PostProcessScaleFactor: 1.714605507808412,
  16598. LensCenterOffset: 0.151976421
  16599. };
  16600. var _OculusInnerGamepadCamera = (function (_super) {
  16601. __extends(_OculusInnerGamepadCamera, _super);
  16602. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16603. _super.call(this, name, position, scene);
  16604. this._workMatrix = new BABYLON.Matrix();
  16605. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16606. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16607. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16608. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16609. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16610. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16611. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16612. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16613. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16614. }
  16615. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16616. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16617. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16618. return this._projectionMatrix;
  16619. };
  16620. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16621. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16622. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16623. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16624. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16625. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16626. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16627. return this._viewMatrix;
  16628. };
  16629. return _OculusInnerGamepadCamera;
  16630. })(BABYLON.FreeCamera);
  16631. var OculusGamepadCamera = (function (_super) {
  16632. __extends(OculusGamepadCamera, _super);
  16633. function OculusGamepadCamera(name, position, scene) {
  16634. var _this = this;
  16635. _super.call(this, name, position, scene);
  16636. this.angularSensibility = 200;
  16637. this.moveSensibility = 75;
  16638. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16639. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16640. this.subCameras.push(this._leftCamera);
  16641. this.subCameras.push(this._rightCamera);
  16642. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16643. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16644. _this._onNewGameConnected(gamepad);
  16645. });
  16646. }
  16647. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16648. if (gamepad.index === 0) {
  16649. this._gamepad = gamepad;
  16650. }
  16651. };
  16652. OculusGamepadCamera.prototype._update = function () {
  16653. this._leftCamera.position.copyFrom(this.position);
  16654. this._rightCamera.position.copyFrom(this.position);
  16655. this._updateCamera(this._leftCamera);
  16656. this._updateCamera(this._rightCamera);
  16657. _super.prototype._update.call(this);
  16658. };
  16659. OculusGamepadCamera.prototype._checkInputs = function () {
  16660. if (!this._gamepad) {
  16661. return;
  16662. }
  16663. var LSValues = this._gamepad.leftStick;
  16664. var normalizedLX = LSValues.x / this.moveSensibility;
  16665. var normalizedLY = LSValues.y / this.moveSensibility;
  16666. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16667. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16668. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16669. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  16670. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16671. };
  16672. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16673. camera.minZ = this.minZ;
  16674. camera.maxZ = this.maxZ;
  16675. camera.rotation.x = this.rotation.x;
  16676. camera.rotation.y = this.rotation.y;
  16677. camera.rotation.z = this.rotation.z;
  16678. };
  16679. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16680. var yaw = evt.alpha / 180 * Math.PI;
  16681. var pitch = evt.beta / 180 * Math.PI;
  16682. var roll = evt.gamma / 180 * Math.PI;
  16683. if (!this._offsetOrientation) {
  16684. this._offsetOrientation = {
  16685. yaw: yaw,
  16686. pitch: pitch,
  16687. roll: roll
  16688. };
  16689. return;
  16690. } else {
  16691. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16692. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16693. this.rotation.z += this._offsetOrientation.roll - roll;
  16694. this._offsetOrientation.yaw = yaw;
  16695. this._offsetOrientation.pitch = pitch;
  16696. this._offsetOrientation.roll = roll;
  16697. }
  16698. };
  16699. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16700. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16701. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16702. };
  16703. OculusGamepadCamera.prototype.detachControl = function (element) {
  16704. _super.prototype.detachControl.call(this, element);
  16705. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16706. };
  16707. OculusGamepadCamera.prototype.dispose = function () {
  16708. this._gamepads.dispose();
  16709. _super.prototype.dispose.call(this);
  16710. };
  16711. return OculusGamepadCamera;
  16712. })(BABYLON.FreeCamera);
  16713. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16714. })(BABYLON || (BABYLON = {}));
  16715. var __extends = this.__extends || function (d, b) {
  16716. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16717. function __() { this.constructor = d; }
  16718. __.prototype = b.prototype;
  16719. d.prototype = new __();
  16720. };
  16721. var BABYLON;
  16722. (function (BABYLON) {
  16723. var VirtualJoysticksCamera = (function (_super) {
  16724. __extends(VirtualJoysticksCamera, _super);
  16725. function VirtualJoysticksCamera(name, position, scene) {
  16726. _super.call(this, name, position, scene);
  16727. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16728. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16729. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16730. this._leftjoystick.setJoystickSensibility(0.15);
  16731. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16732. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16733. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16734. this._rightjoystick.reverseUpDown = true;
  16735. this._rightjoystick.setJoystickSensibility(0.05);
  16736. this._rightjoystick.setJoystickColor("yellow");
  16737. }
  16738. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16739. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16740. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16741. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16742. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16743. if (!this._leftjoystick.pressed) {
  16744. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16745. }
  16746. if (!this._rightjoystick.pressed) {
  16747. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16748. }
  16749. };
  16750. VirtualJoysticksCamera.prototype.dispose = function () {
  16751. this._leftjoystick.releaseCanvas();
  16752. _super.prototype.dispose.call(this);
  16753. };
  16754. return VirtualJoysticksCamera;
  16755. })(BABYLON.FreeCamera);
  16756. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16757. })(BABYLON || (BABYLON = {}));
  16758. var __extends = this.__extends || function (d, b) {
  16759. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16760. function __() { this.constructor = d; }
  16761. __.prototype = b.prototype;
  16762. d.prototype = new __();
  16763. };
  16764. var BABYLON;
  16765. (function (BABYLON) {
  16766. var ShaderMaterial = (function (_super) {
  16767. __extends(ShaderMaterial, _super);
  16768. function ShaderMaterial(name, scene, shaderPath, options) {
  16769. _super.call(this, name, scene);
  16770. this._textures = new Array();
  16771. this._floats = new Array();
  16772. this._floatsArrays = {};
  16773. this._colors3 = new Array();
  16774. this._colors4 = new Array();
  16775. this._vectors2 = new Array();
  16776. this._vectors3 = new Array();
  16777. this._matrices = new Array();
  16778. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16779. this._shaderPath = shaderPath;
  16780. options.needAlphaBlending = options.needAlphaBlending || false;
  16781. options.needAlphaTesting = options.needAlphaTesting || false;
  16782. options.attributes = options.attributes || ["position", "normal", "uv"];
  16783. options.uniforms = options.uniforms || ["worldViewProjection"];
  16784. options.samplers = options.samplers || [];
  16785. this._options = options;
  16786. }
  16787. ShaderMaterial.prototype.needAlphaBlending = function () {
  16788. return this._options.needAlphaBlending;
  16789. };
  16790. ShaderMaterial.prototype.needAlphaTesting = function () {
  16791. return this._options.needAlphaTesting;
  16792. };
  16793. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16794. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16795. this._options.uniforms.push(uniformName);
  16796. }
  16797. };
  16798. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16799. if (this._options.samplers.indexOf(name) === -1) {
  16800. this._options.samplers.push(name);
  16801. }
  16802. this._textures[name] = texture;
  16803. return this;
  16804. };
  16805. ShaderMaterial.prototype.setFloat = function (name, value) {
  16806. this._checkUniform(name);
  16807. this._floats[name] = value;
  16808. return this;
  16809. };
  16810. ShaderMaterial.prototype.setFloats = function (name, value) {
  16811. this._checkUniform(name);
  16812. this._floatsArrays[name] = value;
  16813. return this;
  16814. };
  16815. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16816. this._checkUniform(name);
  16817. this._colors3[name] = value;
  16818. return this;
  16819. };
  16820. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16821. this._checkUniform(name);
  16822. this._colors4[name] = value;
  16823. return this;
  16824. };
  16825. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16826. this._checkUniform(name);
  16827. this._vectors2[name] = value;
  16828. return this;
  16829. };
  16830. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16831. this._checkUniform(name);
  16832. this._vectors3[name] = value;
  16833. return this;
  16834. };
  16835. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16836. this._checkUniform(name);
  16837. this._matrices[name] = value;
  16838. return this;
  16839. };
  16840. ShaderMaterial.prototype.isReady = function () {
  16841. var engine = this.getScene().getEngine();
  16842. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16843. if (!this._effect.isReady()) {
  16844. return false;
  16845. }
  16846. return true;
  16847. };
  16848. ShaderMaterial.prototype.bind = function (world) {
  16849. if (this._options.uniforms.indexOf("world") !== -1) {
  16850. this._effect.setMatrix("world", world);
  16851. }
  16852. if (this._options.uniforms.indexOf("view") !== -1) {
  16853. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16854. }
  16855. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16856. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16857. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16858. }
  16859. if (this._options.uniforms.indexOf("projection") !== -1) {
  16860. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16861. }
  16862. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16863. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16864. }
  16865. for (var name in this._textures) {
  16866. this._effect.setTexture(name, this._textures[name]);
  16867. }
  16868. for (name in this._floats) {
  16869. this._effect.setFloat(name, this._floats[name]);
  16870. }
  16871. for (name in this._floatsArrays) {
  16872. this._effect.setArray(name, this._floatsArrays[name]);
  16873. }
  16874. for (name in this._colors3) {
  16875. this._effect.setColor3(name, this._colors3[name]);
  16876. }
  16877. for (name in this._colors4) {
  16878. var color = this._colors4[name];
  16879. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16880. }
  16881. for (name in this._vectors2) {
  16882. this._effect.setVector2(name, this._vectors2[name]);
  16883. }
  16884. for (name in this._vectors3) {
  16885. this._effect.setVector3(name, this._vectors3[name]);
  16886. }
  16887. for (name in this._matrices) {
  16888. this._effect.setMatrix(name, this._matrices[name]);
  16889. }
  16890. };
  16891. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16892. for (var name in this._textures) {
  16893. this._textures[name].dispose();
  16894. }
  16895. this._textures = [];
  16896. _super.prototype.dispose.call(this, forceDisposeEffect);
  16897. };
  16898. return ShaderMaterial;
  16899. })(BABYLON.Material);
  16900. BABYLON.ShaderMaterial = ShaderMaterial;
  16901. })(BABYLON || (BABYLON = {}));
  16902. var BABYLON;
  16903. (function (BABYLON) {
  16904. var VertexData = (function () {
  16905. function VertexData() {
  16906. }
  16907. VertexData.prototype.set = function (data, kind) {
  16908. switch (kind) {
  16909. case BABYLON.VertexBuffer.PositionKind:
  16910. this.positions = data;
  16911. break;
  16912. case BABYLON.VertexBuffer.NormalKind:
  16913. this.normals = data;
  16914. break;
  16915. case BABYLON.VertexBuffer.UVKind:
  16916. this.uvs = data;
  16917. break;
  16918. case BABYLON.VertexBuffer.UV2Kind:
  16919. this.uv2s = data;
  16920. break;
  16921. case BABYLON.VertexBuffer.ColorKind:
  16922. this.colors = data;
  16923. break;
  16924. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16925. this.matricesIndices = data;
  16926. break;
  16927. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16928. this.matricesWeights = data;
  16929. break;
  16930. }
  16931. };
  16932. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16933. this._applyTo(mesh, updatable);
  16934. };
  16935. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16936. this._applyTo(geometry, updatable);
  16937. };
  16938. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16939. this._update(mesh);
  16940. };
  16941. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16942. this._update(geometry);
  16943. };
  16944. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16945. if (this.positions) {
  16946. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16947. }
  16948. if (this.normals) {
  16949. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16950. }
  16951. if (this.uvs) {
  16952. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16953. }
  16954. if (this.uv2s) {
  16955. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16956. }
  16957. if (this.colors) {
  16958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16959. }
  16960. if (this.matricesIndices) {
  16961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16962. }
  16963. if (this.matricesWeights) {
  16964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16965. }
  16966. if (this.indices) {
  16967. meshOrGeometry.setIndices(this.indices);
  16968. }
  16969. };
  16970. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16971. if (this.positions) {
  16972. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16973. }
  16974. if (this.normals) {
  16975. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16976. }
  16977. if (this.uvs) {
  16978. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16979. }
  16980. if (this.uv2s) {
  16981. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16982. }
  16983. if (this.colors) {
  16984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16985. }
  16986. if (this.matricesIndices) {
  16987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16988. }
  16989. if (this.matricesWeights) {
  16990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16991. }
  16992. if (this.indices) {
  16993. meshOrGeometry.setIndices(this.indices);
  16994. }
  16995. };
  16996. VertexData.prototype.transform = function (matrix) {
  16997. var transformed = BABYLON.Vector3.Zero();
  16998. if (this.positions) {
  16999. var position = BABYLON.Vector3.Zero();
  17000. for (var index = 0; index < this.positions.length; index += 3) {
  17001. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17002. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17003. this.positions[index] = transformed.x;
  17004. this.positions[index + 1] = transformed.y;
  17005. this.positions[index + 2] = transformed.z;
  17006. }
  17007. }
  17008. if (this.normals) {
  17009. var normal = BABYLON.Vector3.Zero();
  17010. for (index = 0; index < this.normals.length; index += 3) {
  17011. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17012. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17013. this.normals[index] = transformed.x;
  17014. this.normals[index + 1] = transformed.y;
  17015. this.normals[index + 2] = transformed.z;
  17016. }
  17017. }
  17018. };
  17019. VertexData.prototype.merge = function (other) {
  17020. if (other.indices) {
  17021. if (!this.indices) {
  17022. this.indices = [];
  17023. }
  17024. var offset = this.positions ? this.positions.length / 3 : 0;
  17025. for (var index = 0; index < other.indices.length; index++) {
  17026. this.indices.push(other.indices[index] + offset);
  17027. }
  17028. }
  17029. if (other.positions) {
  17030. if (!this.positions) {
  17031. this.positions = [];
  17032. }
  17033. for (index = 0; index < other.positions.length; index++) {
  17034. this.positions.push(other.positions[index]);
  17035. }
  17036. }
  17037. if (other.normals) {
  17038. if (!this.normals) {
  17039. this.normals = [];
  17040. }
  17041. for (index = 0; index < other.normals.length; index++) {
  17042. this.normals.push(other.normals[index]);
  17043. }
  17044. }
  17045. if (other.uvs) {
  17046. if (!this.uvs) {
  17047. this.uvs = [];
  17048. }
  17049. for (index = 0; index < other.uvs.length; index++) {
  17050. this.uvs.push(other.uvs[index]);
  17051. }
  17052. }
  17053. if (other.uv2s) {
  17054. if (!this.uv2s) {
  17055. this.uv2s = [];
  17056. }
  17057. for (index = 0; index < other.uv2s.length; index++) {
  17058. this.uv2s.push(other.uv2s[index]);
  17059. }
  17060. }
  17061. if (other.matricesIndices) {
  17062. if (!this.matricesIndices) {
  17063. this.matricesIndices = [];
  17064. }
  17065. for (index = 0; index < other.matricesIndices.length; index++) {
  17066. this.matricesIndices.push(other.matricesIndices[index]);
  17067. }
  17068. }
  17069. if (other.matricesWeights) {
  17070. if (!this.matricesWeights) {
  17071. this.matricesWeights = [];
  17072. }
  17073. for (index = 0; index < other.matricesWeights.length; index++) {
  17074. this.matricesWeights.push(other.matricesWeights[index]);
  17075. }
  17076. }
  17077. if (other.colors) {
  17078. if (!this.colors) {
  17079. this.colors = [];
  17080. }
  17081. for (index = 0; index < other.colors.length; index++) {
  17082. this.colors.push(other.colors[index]);
  17083. }
  17084. }
  17085. };
  17086. VertexData.ExtractFromMesh = function (mesh) {
  17087. return VertexData._ExtractFrom(mesh);
  17088. };
  17089. VertexData.ExtractFromGeometry = function (geometry) {
  17090. return VertexData._ExtractFrom(geometry);
  17091. };
  17092. VertexData._ExtractFrom = function (meshOrGeometry) {
  17093. var result = new BABYLON.VertexData();
  17094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17095. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17096. }
  17097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17098. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17099. }
  17100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17101. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17102. }
  17103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17104. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17105. }
  17106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17107. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17108. }
  17109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17110. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17111. }
  17112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17113. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17114. }
  17115. result.indices = meshOrGeometry.getIndices();
  17116. return result;
  17117. };
  17118. VertexData.CreateBox = function (size) {
  17119. var normalsSource = [
  17120. new BABYLON.Vector3(0, 0, 1),
  17121. new BABYLON.Vector3(0, 0, -1),
  17122. new BABYLON.Vector3(1, 0, 0),
  17123. new BABYLON.Vector3(-1, 0, 0),
  17124. new BABYLON.Vector3(0, 1, 0),
  17125. new BABYLON.Vector3(0, -1, 0)
  17126. ];
  17127. var indices = [];
  17128. var positions = [];
  17129. var normals = [];
  17130. var uvs = [];
  17131. size = size || 1;
  17132. for (var index = 0; index < normalsSource.length; index++) {
  17133. var normal = normalsSource[index];
  17134. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17135. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17136. var verticesLength = positions.length / 3;
  17137. indices.push(verticesLength);
  17138. indices.push(verticesLength + 1);
  17139. indices.push(verticesLength + 2);
  17140. indices.push(verticesLength);
  17141. indices.push(verticesLength + 2);
  17142. indices.push(verticesLength + 3);
  17143. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17144. positions.push(vertex.x, vertex.y, vertex.z);
  17145. normals.push(normal.x, normal.y, normal.z);
  17146. uvs.push(1.0, 1.0);
  17147. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17148. positions.push(vertex.x, vertex.y, vertex.z);
  17149. normals.push(normal.x, normal.y, normal.z);
  17150. uvs.push(0.0, 1.0);
  17151. vertex = normal.add(side1).add(side2).scale(size / 2);
  17152. positions.push(vertex.x, vertex.y, vertex.z);
  17153. normals.push(normal.x, normal.y, normal.z);
  17154. uvs.push(0.0, 0.0);
  17155. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17156. positions.push(vertex.x, vertex.y, vertex.z);
  17157. normals.push(normal.x, normal.y, normal.z);
  17158. uvs.push(1.0, 0.0);
  17159. }
  17160. var vertexData = new BABYLON.VertexData();
  17161. vertexData.indices = indices;
  17162. vertexData.positions = positions;
  17163. vertexData.normals = normals;
  17164. vertexData.uvs = uvs;
  17165. return vertexData;
  17166. };
  17167. VertexData.CreateSphere = function (segments, diameter) {
  17168. segments = segments || 32;
  17169. diameter = diameter || 1;
  17170. var radius = diameter / 2;
  17171. var totalZRotationSteps = 2 + segments;
  17172. var totalYRotationSteps = 2 * totalZRotationSteps;
  17173. var indices = [];
  17174. var positions = [];
  17175. var normals = [];
  17176. var uvs = [];
  17177. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17178. var normalizedZ = zRotationStep / totalZRotationSteps;
  17179. var angleZ = (normalizedZ * Math.PI);
  17180. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17181. var normalizedY = yRotationStep / totalYRotationSteps;
  17182. var angleY = normalizedY * Math.PI * 2;
  17183. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17184. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17185. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17186. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17187. var vertex = complete.scale(radius);
  17188. var normal = BABYLON.Vector3.Normalize(vertex);
  17189. positions.push(vertex.x, vertex.y, vertex.z);
  17190. normals.push(normal.x, normal.y, normal.z);
  17191. uvs.push(normalizedZ, normalizedY);
  17192. }
  17193. if (zRotationStep > 0) {
  17194. var verticesCount = positions.length / 3;
  17195. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17196. indices.push((firstIndex));
  17197. indices.push((firstIndex + 1));
  17198. indices.push(firstIndex + totalYRotationSteps + 1);
  17199. indices.push((firstIndex + totalYRotationSteps + 1));
  17200. indices.push((firstIndex + 1));
  17201. indices.push((firstIndex + totalYRotationSteps + 2));
  17202. }
  17203. }
  17204. }
  17205. var vertexData = new BABYLON.VertexData();
  17206. vertexData.indices = indices;
  17207. vertexData.positions = positions;
  17208. vertexData.normals = normals;
  17209. vertexData.uvs = uvs;
  17210. return vertexData;
  17211. };
  17212. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17213. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17214. var radiusTop = diameterTop / 2;
  17215. var radiusBottom = diameterBottom / 2;
  17216. var indices = [];
  17217. var positions = [];
  17218. var normals = [];
  17219. var uvs = [];
  17220. height = height || 1;
  17221. diameterTop = diameterTop || 0.5;
  17222. diameterBottom = diameterBottom || 1;
  17223. tessellation = tessellation || 16;
  17224. subdivisions = subdivisions || 1;
  17225. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17226. var getCircleVector = function (i) {
  17227. var angle = (i * 2.0 * Math.PI / tessellation);
  17228. var dx = Math.cos(angle);
  17229. var dz = Math.sin(angle);
  17230. return new BABYLON.Vector3(dx, 0, dz);
  17231. };
  17232. var createCylinderCap = function (isTop) {
  17233. var radius = isTop ? radiusTop : radiusBottom;
  17234. if (radius == 0) {
  17235. return;
  17236. }
  17237. var vbase = positions.length / 3;
  17238. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17239. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17240. if (!isTop) {
  17241. offset.scaleInPlace(-1);
  17242. textureScale.x = -textureScale.x;
  17243. }
  17244. for (i = 0; i < tessellation; i++) {
  17245. var circleVector = getCircleVector(i);
  17246. var position = circleVector.scale(radius).add(offset);
  17247. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17248. positions.push(position.x, position.y, position.z);
  17249. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17250. }
  17251. for (var i = 0; i < tessellation - 2; i++) {
  17252. if (!isTop) {
  17253. indices.push(vbase);
  17254. indices.push(vbase + (i + 2) % tessellation);
  17255. indices.push(vbase + (i + 1) % tessellation);
  17256. } else {
  17257. indices.push(vbase);
  17258. indices.push(vbase + (i + 1) % tessellation);
  17259. indices.push(vbase + (i + 2) % tessellation);
  17260. }
  17261. }
  17262. };
  17263. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17264. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17265. var stride = tessellation + 1;
  17266. for (var i = 0; i <= tessellation; i++) {
  17267. var circleVector = getCircleVector(i);
  17268. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17269. var position, radius = radiusBottom;
  17270. for (var s = 0; s <= subdivisions; s++) {
  17271. position = circleVector.scale(radius);
  17272. position.addInPlace(base.add(offset.scale(s)));
  17273. textureCoordinate.y += 1 / subdivisions;
  17274. radius += (radiusTop - radiusBottom) / subdivisions;
  17275. positions.push(position.x, position.y, position.z);
  17276. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17277. }
  17278. }
  17279. subdivisions += 1;
  17280. for (var s = 0; s < subdivisions - 1; s++) {
  17281. for (var i = 0; i <= tessellation; i++) {
  17282. indices.push(i * subdivisions + s);
  17283. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17284. indices.push(i * subdivisions + (s + 1));
  17285. indices.push(i * subdivisions + (s + 1));
  17286. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17287. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17288. }
  17289. }
  17290. createCylinderCap(true);
  17291. createCylinderCap(false);
  17292. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17293. var vertexData = new BABYLON.VertexData();
  17294. vertexData.indices = indices;
  17295. vertexData.positions = positions;
  17296. vertexData.normals = normals;
  17297. vertexData.uvs = uvs;
  17298. return vertexData;
  17299. };
  17300. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17301. var indices = [];
  17302. var positions = [];
  17303. var normals = [];
  17304. var uvs = [];
  17305. diameter = diameter || 1;
  17306. thickness = thickness || 0.5;
  17307. tessellation = tessellation || 16;
  17308. var stride = tessellation + 1;
  17309. for (var i = 0; i <= tessellation; i++) {
  17310. var u = i / tessellation;
  17311. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17312. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17313. for (var j = 0; j <= tessellation; j++) {
  17314. var v = 1 - j / tessellation;
  17315. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17316. var dx = Math.cos(innerAngle);
  17317. var dy = Math.sin(innerAngle);
  17318. var normal = new BABYLON.Vector3(dx, dy, 0);
  17319. var position = normal.scale(thickness / 2);
  17320. var textureCoordinate = new BABYLON.Vector2(u, v);
  17321. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17322. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17323. positions.push(position.x, position.y, position.z);
  17324. normals.push(normal.x, normal.y, normal.z);
  17325. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17326. var nextI = (i + 1) % stride;
  17327. var nextJ = (j + 1) % stride;
  17328. indices.push(i * stride + j);
  17329. indices.push(i * stride + nextJ);
  17330. indices.push(nextI * stride + j);
  17331. indices.push(i * stride + nextJ);
  17332. indices.push(nextI * stride + nextJ);
  17333. indices.push(nextI * stride + j);
  17334. }
  17335. }
  17336. var vertexData = new BABYLON.VertexData();
  17337. vertexData.indices = indices;
  17338. vertexData.positions = positions;
  17339. vertexData.normals = normals;
  17340. vertexData.uvs = uvs;
  17341. return vertexData;
  17342. };
  17343. VertexData.CreateLines = function (points) {
  17344. var indices = [];
  17345. var positions = [];
  17346. for (var index = 0; index < points.length; index++) {
  17347. positions.push(points[index].x, points[index].y, points[index].z);
  17348. if (index > 0) {
  17349. indices.push(index - 1);
  17350. indices.push(index);
  17351. }
  17352. }
  17353. var vertexData = new BABYLON.VertexData();
  17354. vertexData.indices = indices;
  17355. vertexData.positions = positions;
  17356. return vertexData;
  17357. };
  17358. VertexData.CreateGround = function (width, height, subdivisions) {
  17359. var indices = [];
  17360. var positions = [];
  17361. var normals = [];
  17362. var uvs = [];
  17363. var row, col;
  17364. width = width || 1;
  17365. height = height || 1;
  17366. subdivisions = subdivisions || 1;
  17367. for (row = 0; row <= subdivisions; row++) {
  17368. for (col = 0; col <= subdivisions; col++) {
  17369. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17370. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17371. positions.push(position.x, position.y, position.z);
  17372. normals.push(normal.x, normal.y, normal.z);
  17373. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17374. }
  17375. }
  17376. for (row = 0; row < subdivisions; row++) {
  17377. for (col = 0; col < subdivisions; col++) {
  17378. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17379. indices.push(col + 1 + row * (subdivisions + 1));
  17380. indices.push(col + row * (subdivisions + 1));
  17381. indices.push(col + (row + 1) * (subdivisions + 1));
  17382. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17383. indices.push(col + row * (subdivisions + 1));
  17384. }
  17385. }
  17386. var vertexData = new BABYLON.VertexData();
  17387. vertexData.indices = indices;
  17388. vertexData.positions = positions;
  17389. vertexData.normals = normals;
  17390. vertexData.uvs = uvs;
  17391. return vertexData;
  17392. };
  17393. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17394. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17395. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17396. var indices = [];
  17397. var positions = [];
  17398. var normals = [];
  17399. var uvs = [];
  17400. var row, col, tileRow, tileCol;
  17401. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17402. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17403. precision.w = (precision.w < 1) ? 1 : precision.w;
  17404. precision.h = (precision.h < 1) ? 1 : precision.h;
  17405. var tileSize = {
  17406. 'w': (xmax - xmin) / subdivisions.w,
  17407. 'h': (zmax - zmin) / subdivisions.h
  17408. };
  17409. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17410. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17411. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17412. }
  17413. }
  17414. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17415. var base = positions.length / 3;
  17416. var rowLength = precision.w + 1;
  17417. for (row = 0; row < precision.h; row++) {
  17418. for (col = 0; col < precision.w; col++) {
  17419. var square = [
  17420. base + col + row * rowLength,
  17421. base + (col + 1) + row * rowLength,
  17422. base + (col + 1) + (row + 1) * rowLength,
  17423. base + col + (row + 1) * rowLength
  17424. ];
  17425. indices.push(square[1]);
  17426. indices.push(square[2]);
  17427. indices.push(square[3]);
  17428. indices.push(square[0]);
  17429. indices.push(square[1]);
  17430. indices.push(square[3]);
  17431. }
  17432. }
  17433. var position = BABYLON.Vector3.Zero();
  17434. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17435. for (row = 0; row <= precision.h; row++) {
  17436. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17437. for (col = 0; col <= precision.w; col++) {
  17438. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17439. position.y = 0;
  17440. positions.push(position.x, position.y, position.z);
  17441. normals.push(normal.x, normal.y, normal.z);
  17442. uvs.push(col / precision.w, row / precision.h);
  17443. }
  17444. }
  17445. }
  17446. var vertexData = new BABYLON.VertexData();
  17447. vertexData.indices = indices;
  17448. vertexData.positions = positions;
  17449. vertexData.normals = normals;
  17450. vertexData.uvs = uvs;
  17451. return vertexData;
  17452. };
  17453. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17454. var indices = [];
  17455. var positions = [];
  17456. var normals = [];
  17457. var uvs = [];
  17458. var row, col;
  17459. for (row = 0; row <= subdivisions; row++) {
  17460. for (col = 0; col <= subdivisions; col++) {
  17461. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17462. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17463. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17464. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17465. var r = buffer[pos] / 255.0;
  17466. var g = buffer[pos + 1] / 255.0;
  17467. var b = buffer[pos + 2] / 255.0;
  17468. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17469. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17470. positions.push(position.x, position.y, position.z);
  17471. normals.push(0, 0, 0);
  17472. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17473. }
  17474. }
  17475. for (row = 0; row < subdivisions; row++) {
  17476. for (col = 0; col < subdivisions; col++) {
  17477. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17478. indices.push(col + 1 + row * (subdivisions + 1));
  17479. indices.push(col + row * (subdivisions + 1));
  17480. indices.push(col + (row + 1) * (subdivisions + 1));
  17481. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17482. indices.push(col + row * (subdivisions + 1));
  17483. }
  17484. }
  17485. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17486. var vertexData = new BABYLON.VertexData();
  17487. vertexData.indices = indices;
  17488. vertexData.positions = positions;
  17489. vertexData.normals = normals;
  17490. vertexData.uvs = uvs;
  17491. return vertexData;
  17492. };
  17493. VertexData.CreatePlane = function (size) {
  17494. var indices = [];
  17495. var positions = [];
  17496. var normals = [];
  17497. var uvs = [];
  17498. size = size || 1;
  17499. var halfSize = size / 2.0;
  17500. positions.push(-halfSize, -halfSize, 0);
  17501. normals.push(0, 0, -1.0);
  17502. uvs.push(0.0, 0.0);
  17503. positions.push(halfSize, -halfSize, 0);
  17504. normals.push(0, 0, -1.0);
  17505. uvs.push(1.0, 0.0);
  17506. positions.push(halfSize, halfSize, 0);
  17507. normals.push(0, 0, -1.0);
  17508. uvs.push(1.0, 1.0);
  17509. positions.push(-halfSize, halfSize, 0);
  17510. normals.push(0, 0, -1.0);
  17511. uvs.push(0.0, 1.0);
  17512. indices.push(0);
  17513. indices.push(1);
  17514. indices.push(2);
  17515. indices.push(0);
  17516. indices.push(2);
  17517. indices.push(3);
  17518. var vertexData = new BABYLON.VertexData();
  17519. vertexData.indices = indices;
  17520. vertexData.positions = positions;
  17521. vertexData.normals = normals;
  17522. vertexData.uvs = uvs;
  17523. return vertexData;
  17524. };
  17525. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17526. var indices = [];
  17527. var positions = [];
  17528. var normals = [];
  17529. var uvs = [];
  17530. radius = radius || 2;
  17531. tube = tube || 0.5;
  17532. radialSegments = radialSegments || 32;
  17533. tubularSegments = tubularSegments || 32;
  17534. p = p || 2;
  17535. q = q || 3;
  17536. var getPos = function (angle) {
  17537. var cu = Math.cos(angle);
  17538. var su = Math.sin(angle);
  17539. var quOverP = q / p * angle;
  17540. var cs = Math.cos(quOverP);
  17541. var tx = radius * (2 + cs) * 0.5 * cu;
  17542. var ty = radius * (2 + cs) * su * 0.5;
  17543. var tz = radius * Math.sin(quOverP) * 0.5;
  17544. return new BABYLON.Vector3(tx, ty, tz);
  17545. };
  17546. for (var i = 0; i <= radialSegments; i++) {
  17547. var modI = i % radialSegments;
  17548. var u = modI / radialSegments * 2 * p * Math.PI;
  17549. var p1 = getPos(u);
  17550. var p2 = getPos(u + 0.01);
  17551. var tang = p2.subtract(p1);
  17552. var n = p2.add(p1);
  17553. var bitan = BABYLON.Vector3.Cross(tang, n);
  17554. n = BABYLON.Vector3.Cross(bitan, tang);
  17555. bitan.normalize();
  17556. n.normalize();
  17557. for (var j = 0; j < tubularSegments; j++) {
  17558. var modJ = j % tubularSegments;
  17559. var v = modJ / tubularSegments * 2 * Math.PI;
  17560. var cx = -tube * Math.cos(v);
  17561. var cy = tube * Math.sin(v);
  17562. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17563. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17564. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17565. uvs.push(i / radialSegments);
  17566. uvs.push(j / tubularSegments);
  17567. }
  17568. }
  17569. for (i = 0; i < radialSegments; i++) {
  17570. for (j = 0; j < tubularSegments; j++) {
  17571. var jNext = (j + 1) % tubularSegments;
  17572. var a = i * tubularSegments + j;
  17573. var b = (i + 1) * tubularSegments + j;
  17574. var c = (i + 1) * tubularSegments + jNext;
  17575. var d = i * tubularSegments + jNext;
  17576. indices.push(d);
  17577. indices.push(b);
  17578. indices.push(a);
  17579. indices.push(d);
  17580. indices.push(c);
  17581. indices.push(b);
  17582. }
  17583. }
  17584. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17585. var vertexData = new BABYLON.VertexData();
  17586. vertexData.indices = indices;
  17587. vertexData.positions = positions;
  17588. vertexData.normals = normals;
  17589. vertexData.uvs = uvs;
  17590. return vertexData;
  17591. };
  17592. VertexData.ComputeNormals = function (positions, indices, normals) {
  17593. var positionVectors = [];
  17594. var facesOfVertices = [];
  17595. var index;
  17596. for (index = 0; index < positions.length; index += 3) {
  17597. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17598. positionVectors.push(vector3);
  17599. facesOfVertices.push([]);
  17600. }
  17601. var facesNormals = [];
  17602. for (index = 0; index < indices.length / 3; index++) {
  17603. var i1 = indices[index * 3];
  17604. var i2 = indices[index * 3 + 1];
  17605. var i3 = indices[index * 3 + 2];
  17606. var p1 = positionVectors[i1];
  17607. var p2 = positionVectors[i2];
  17608. var p3 = positionVectors[i3];
  17609. var p1p2 = p1.subtract(p2);
  17610. var p3p2 = p3.subtract(p2);
  17611. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17612. facesOfVertices[i1].push(index);
  17613. facesOfVertices[i2].push(index);
  17614. facesOfVertices[i3].push(index);
  17615. }
  17616. for (index = 0; index < positionVectors.length; index++) {
  17617. var faces = facesOfVertices[index];
  17618. var normal = BABYLON.Vector3.Zero();
  17619. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17620. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17621. }
  17622. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17623. normals[index * 3] = normal.x;
  17624. normals[index * 3 + 1] = normal.y;
  17625. normals[index * 3 + 2] = normal.z;
  17626. }
  17627. };
  17628. return VertexData;
  17629. })();
  17630. BABYLON.VertexData = VertexData;
  17631. })(BABYLON || (BABYLON = {}));
  17632. var __extends = this.__extends || function (d, b) {
  17633. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17634. function __() { this.constructor = d; }
  17635. __.prototype = b.prototype;
  17636. d.prototype = new __();
  17637. };
  17638. var BABYLON;
  17639. (function (BABYLON) {
  17640. var buildCamera = function (that, name) {
  17641. that._leftCamera.isIntermediate = true;
  17642. that.subCameras.push(that._leftCamera);
  17643. that.subCameras.push(that._rightCamera);
  17644. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17645. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17646. that._anaglyphPostProcess.onApply = function (effect) {
  17647. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17648. };
  17649. that._update();
  17650. };
  17651. var AnaglyphArcRotateCamera = (function (_super) {
  17652. __extends(AnaglyphArcRotateCamera, _super);
  17653. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17654. _super.call(this, name, alpha, beta, radius, target, scene);
  17655. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17656. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17657. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17658. buildCamera(this, name);
  17659. }
  17660. AnaglyphArcRotateCamera.prototype._update = function () {
  17661. this._updateCamera(this._leftCamera);
  17662. this._updateCamera(this._rightCamera);
  17663. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17664. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17665. _super.prototype._update.call(this);
  17666. };
  17667. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17668. camera.beta = this.beta;
  17669. camera.radius = this.radius;
  17670. camera.minZ = this.minZ;
  17671. camera.maxZ = this.maxZ;
  17672. camera.fov = this.fov;
  17673. camera.target = this.target;
  17674. };
  17675. return AnaglyphArcRotateCamera;
  17676. })(BABYLON.ArcRotateCamera);
  17677. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17678. var AnaglyphFreeCamera = (function (_super) {
  17679. __extends(AnaglyphFreeCamera, _super);
  17680. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17681. _super.call(this, name, position, scene);
  17682. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17683. this._transformMatrix = new BABYLON.Matrix();
  17684. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17685. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17686. buildCamera(this, name);
  17687. }
  17688. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17689. var target = this.getTarget();
  17690. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17691. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17692. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17693. };
  17694. AnaglyphFreeCamera.prototype._update = function () {
  17695. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17696. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17697. this._updateCamera(this._leftCamera);
  17698. this._updateCamera(this._rightCamera);
  17699. _super.prototype._update.call(this);
  17700. };
  17701. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17702. camera.minZ = this.minZ;
  17703. camera.maxZ = this.maxZ;
  17704. camera.fov = this.fov;
  17705. camera.viewport = this.viewport;
  17706. camera.setTarget(this.getTarget());
  17707. };
  17708. return AnaglyphFreeCamera;
  17709. })(BABYLON.FreeCamera);
  17710. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17711. })(BABYLON || (BABYLON = {}));
  17712. var __extends = this.__extends || function (d, b) {
  17713. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17714. function __() { this.constructor = d; }
  17715. __.prototype = b.prototype;
  17716. d.prototype = new __();
  17717. };
  17718. var BABYLON;
  17719. (function (BABYLON) {
  17720. var AnaglyphPostProcess = (function (_super) {
  17721. __extends(AnaglyphPostProcess, _super);
  17722. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17723. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17724. }
  17725. return AnaglyphPostProcess;
  17726. })(BABYLON.PostProcess);
  17727. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17728. })(BABYLON || (BABYLON = {}));
  17729. var BABYLON;
  17730. (function (BABYLON) {
  17731. var Tags = (function () {
  17732. function Tags() {
  17733. }
  17734. Tags.EnableFor = function (obj) {
  17735. obj._tags = obj._tags || {};
  17736. obj.hasTags = function () {
  17737. return Tags.HasTags(obj);
  17738. };
  17739. obj.addTags = function (tagsString) {
  17740. return Tags.AddTagsTo(obj, tagsString);
  17741. };
  17742. obj.removeTags = function (tagsString) {
  17743. return Tags.RemoveTagsFrom(obj, tagsString);
  17744. };
  17745. obj.matchesTagsQuery = function (tagsQuery) {
  17746. return Tags.MatchesQuery(obj, tagsQuery);
  17747. };
  17748. };
  17749. Tags.DisableFor = function (obj) {
  17750. delete obj._tags;
  17751. delete obj.hasTags;
  17752. delete obj.addTags;
  17753. delete obj.removeTags;
  17754. delete obj.matchesTagsQuery;
  17755. };
  17756. Tags.HasTags = function (obj) {
  17757. if (!obj._tags) {
  17758. return false;
  17759. }
  17760. return !BABYLON.Tools.IsEmpty(obj._tags);
  17761. };
  17762. Tags.GetTags = function (obj) {
  17763. if (!obj._tags) {
  17764. return null;
  17765. }
  17766. return obj._tags;
  17767. };
  17768. Tags.AddTagsTo = function (obj, tagsString) {
  17769. if (!tagsString) {
  17770. return;
  17771. }
  17772. var tags = tagsString.split(" ");
  17773. for (var t in tags) {
  17774. Tags._AddTagTo(obj, tags[t]);
  17775. }
  17776. };
  17777. Tags._AddTagTo = function (obj, tag) {
  17778. tag = tag.trim();
  17779. if (tag === "" || tag === "true" || tag === "false") {
  17780. return;
  17781. }
  17782. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17783. return;
  17784. }
  17785. Tags.EnableFor(obj);
  17786. obj._tags[tag] = true;
  17787. };
  17788. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17789. if (!Tags.HasTags(obj)) {
  17790. return;
  17791. }
  17792. var tags = tagsString.split(" ");
  17793. for (var t in tags) {
  17794. Tags._RemoveTagFrom(obj, tags[t]);
  17795. }
  17796. };
  17797. Tags._RemoveTagFrom = function (obj, tag) {
  17798. delete obj._tags[tag];
  17799. };
  17800. Tags.MatchesQuery = function (obj, tagsQuery) {
  17801. if (tagsQuery === undefined) {
  17802. return true;
  17803. }
  17804. if (tagsQuery === "") {
  17805. return Tags.HasTags(obj);
  17806. }
  17807. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17808. return Tags.HasTags(obj) && obj._tags[r];
  17809. });
  17810. };
  17811. return Tags;
  17812. })();
  17813. BABYLON.Tags = Tags;
  17814. })(BABYLON || (BABYLON = {}));
  17815. var BABYLON;
  17816. (function (BABYLON) {
  17817. (function (Internals) {
  17818. var AndOrNotEvaluator = (function () {
  17819. function AndOrNotEvaluator() {
  17820. }
  17821. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17822. if (!query.match(/\([^\(\)]*\)/g)) {
  17823. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17824. } else {
  17825. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17826. r = r.slice(1, r.length - 1);
  17827. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17828. });
  17829. }
  17830. if (query === "true") {
  17831. return true;
  17832. }
  17833. if (query === "false") {
  17834. return false;
  17835. }
  17836. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17837. };
  17838. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17839. evaluateCallback = evaluateCallback || (function (r) {
  17840. return r === "true" ? true : false;
  17841. });
  17842. var result;
  17843. var or = parenthesisContent.split("||");
  17844. for (var i in or) {
  17845. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17846. var and = ori.split("&&");
  17847. if (and.length > 1) {
  17848. for (var j = 0; j < and.length; ++j) {
  17849. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17850. if (andj !== "true" && andj !== "false") {
  17851. if (andj[0] === "!") {
  17852. result = !evaluateCallback(andj.substring(1));
  17853. } else {
  17854. result = evaluateCallback(andj);
  17855. }
  17856. } else {
  17857. result = andj === "true" ? true : false;
  17858. }
  17859. if (!result) {
  17860. ori = "false";
  17861. break;
  17862. }
  17863. }
  17864. }
  17865. if (result || ori === "true") {
  17866. result = true;
  17867. break;
  17868. }
  17869. if (ori !== "true" && ori !== "false") {
  17870. if (ori[0] === "!") {
  17871. result = !evaluateCallback(ori.substring(1));
  17872. } else {
  17873. result = evaluateCallback(ori);
  17874. }
  17875. } else {
  17876. result = ori === "true" ? true : false;
  17877. }
  17878. }
  17879. return result ? "true" : "false";
  17880. };
  17881. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17882. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17883. r = r.replace(/[\s]/g, function () {
  17884. return "";
  17885. });
  17886. return r.length % 2 ? "!" : "";
  17887. });
  17888. booleanString = booleanString.trim();
  17889. if (booleanString === "!true") {
  17890. booleanString = "false";
  17891. } else if (booleanString === "!false") {
  17892. booleanString = "true";
  17893. }
  17894. return booleanString;
  17895. };
  17896. return AndOrNotEvaluator;
  17897. })();
  17898. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17899. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17900. var Internals = BABYLON.Internals;
  17901. })(BABYLON || (BABYLON = {}));
  17902. var BABYLON;
  17903. (function (BABYLON) {
  17904. var PostProcessRenderPass = (function () {
  17905. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17906. this._enabled = true;
  17907. this._refCount = 0;
  17908. this._name = name;
  17909. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17910. this.setRenderList(renderList);
  17911. this._renderTexture.onBeforeRender = beforeRender;
  17912. this._renderTexture.onAfterRender = afterRender;
  17913. this._scene = scene;
  17914. }
  17915. PostProcessRenderPass.prototype._incRefCount = function () {
  17916. if (this._refCount === 0) {
  17917. this._scene.customRenderTargets.push(this._renderTexture);
  17918. }
  17919. return ++this._refCount;
  17920. };
  17921. PostProcessRenderPass.prototype._decRefCount = function () {
  17922. this._refCount--;
  17923. if (this._refCount <= 0) {
  17924. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17925. }
  17926. return this._refCount;
  17927. };
  17928. PostProcessRenderPass.prototype._update = function () {
  17929. this.setRenderList(this._renderList);
  17930. };
  17931. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17932. this._renderTexture.renderList = renderList;
  17933. };
  17934. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17935. return this._renderTexture;
  17936. };
  17937. return PostProcessRenderPass;
  17938. })();
  17939. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17940. })(BABYLON || (BABYLON = {}));
  17941. var BABYLON;
  17942. (function (BABYLON) {
  17943. var PostProcessRenderEffect = (function () {
  17944. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17945. this._engine = engine;
  17946. this._name = name;
  17947. this._singleInstance = singleInstance || true;
  17948. this._getPostProcess = getPostProcess;
  17949. this._cameras = [];
  17950. this._postProcesses = [];
  17951. this._indicesForCamera = [];
  17952. this._renderPasses = [];
  17953. this._renderEffectAsPasses = [];
  17954. }
  17955. PostProcessRenderEffect.prototype._update = function () {
  17956. for (var renderPassName in this._renderPasses) {
  17957. this._renderPasses[renderPassName]._update();
  17958. }
  17959. };
  17960. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17961. this._renderPasses[renderPass._name] = renderPass;
  17962. this._linkParameters();
  17963. };
  17964. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17965. delete this._renderPasses[renderPass._name];
  17966. this._linkParameters();
  17967. };
  17968. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17969. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17970. this._linkParameters();
  17971. };
  17972. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17973. for (var renderPassName in this._renderPasses) {
  17974. if (renderPassName === passName) {
  17975. return this._renderPasses[passName];
  17976. }
  17977. }
  17978. };
  17979. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17980. this._renderPasses.length = 0;
  17981. this._linkParameters();
  17982. };
  17983. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17984. var cameraKey;
  17985. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17986. for (var i = 0; i < _cam.length; i++) {
  17987. var camera = _cam[i];
  17988. var cameraName = camera.name;
  17989. if (this._singleInstance) {
  17990. cameraKey = 0;
  17991. } else {
  17992. cameraKey = cameraName;
  17993. }
  17994. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17995. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17996. if (!this._indicesForCamera[cameraName]) {
  17997. this._indicesForCamera[cameraName] = [];
  17998. }
  17999. this._indicesForCamera[cameraName].push(index);
  18000. if (this._cameras.indexOf(camera) === -1) {
  18001. this._cameras[cameraName] = camera;
  18002. }
  18003. for (var passName in this._renderPasses) {
  18004. this._renderPasses[passName]._incRefCount();
  18005. }
  18006. }
  18007. this._linkParameters();
  18008. };
  18009. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18010. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18011. for (var i = 0; i < _cam.length; i++) {
  18012. var camera = _cam[i];
  18013. var cameraName = camera.name;
  18014. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18015. var index = this._cameras.indexOf(cameraName);
  18016. this._indicesForCamera.splice(index, 1);
  18017. this._cameras.splice(index, 1);
  18018. for (var passName in this._renderPasses) {
  18019. this._renderPasses[passName]._decRefCount();
  18020. }
  18021. }
  18022. };
  18023. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18024. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18025. for (var i = 0; i < _cam.length; i++) {
  18026. var camera = _cam[i];
  18027. var cameraName = camera.name;
  18028. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18029. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18030. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18031. }
  18032. }
  18033. for (var passName in this._renderPasses) {
  18034. this._renderPasses[passName]._incRefCount();
  18035. }
  18036. }
  18037. };
  18038. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18039. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18040. for (var i = 0; i < _cam.length; i++) {
  18041. var camera = _cam[i];
  18042. var cameraName = camera.Name;
  18043. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18044. for (var passName in this._renderPasses) {
  18045. this._renderPasses[passName]._decRefCount();
  18046. }
  18047. }
  18048. };
  18049. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18050. if (this._singleInstance) {
  18051. return this._postProcesses[0];
  18052. } else {
  18053. return this._postProcesses[camera.name];
  18054. }
  18055. };
  18056. PostProcessRenderEffect.prototype._linkParameters = function () {
  18057. var _this = this;
  18058. for (var index in this._postProcesses) {
  18059. if (this.applyParameters) {
  18060. this.applyParameters(this._postProcesses[index]);
  18061. }
  18062. this._postProcesses[index].onBeforeRender = function (effect) {
  18063. _this._linkTextures(effect);
  18064. };
  18065. }
  18066. };
  18067. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18068. for (var renderPassName in this._renderPasses) {
  18069. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18070. }
  18071. for (var renderEffectName in this._renderEffectAsPasses) {
  18072. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18073. }
  18074. };
  18075. return PostProcessRenderEffect;
  18076. })();
  18077. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18078. })(BABYLON || (BABYLON = {}));
  18079. var BABYLON;
  18080. (function (BABYLON) {
  18081. var PostProcessRenderPipeline = (function () {
  18082. function PostProcessRenderPipeline(engine, name) {
  18083. this._engine = engine;
  18084. this._name = name;
  18085. this._renderEffects = [];
  18086. this._renderEffectsForIsolatedPass = [];
  18087. this._cameras = [];
  18088. }
  18089. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18090. this._renderEffects[renderEffect._name] = renderEffect;
  18091. };
  18092. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18093. var renderEffects = this._renderEffects[renderEffectName];
  18094. if (!renderEffects) {
  18095. return;
  18096. }
  18097. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18098. };
  18099. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18100. var renderEffects = this._renderEffects[renderEffectName];
  18101. if (!renderEffects) {
  18102. return;
  18103. }
  18104. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18105. };
  18106. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18107. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18108. var indicesToDelete = [];
  18109. for (var i = 0; i < _cam.length; i++) {
  18110. var camera = _cam[i];
  18111. var cameraName = camera.name;
  18112. if (this._cameras.indexOf(camera) === -1) {
  18113. this._cameras[cameraName] = camera;
  18114. } else if (unique) {
  18115. indicesToDelete.push(i);
  18116. }
  18117. }
  18118. for (var i = 0; i < indicesToDelete.length; i++) {
  18119. cameras.splice(indicesToDelete[i], 1);
  18120. }
  18121. for (var renderEffectName in this._renderEffects) {
  18122. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18123. }
  18124. };
  18125. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18127. for (var renderEffectName in this._renderEffects) {
  18128. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18129. }
  18130. for (var i = 0; i < _cam.length; i++) {
  18131. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18132. }
  18133. };
  18134. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18135. var _this = this;
  18136. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18137. var pass = null;
  18138. for (var renderEffectName in this._renderEffects) {
  18139. pass = this._renderEffects[renderEffectName].getPass(passName);
  18140. if (pass != null) {
  18141. break;
  18142. }
  18143. }
  18144. if (pass === null) {
  18145. return;
  18146. }
  18147. for (var renderEffectName in this._renderEffects) {
  18148. this._renderEffects[renderEffectName]._disable(_cam);
  18149. }
  18150. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18151. for (var i = 0; i < _cam.length; i++) {
  18152. var camera = _cam[i];
  18153. var cameraName = camera.name;
  18154. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18155. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18156. });
  18157. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18158. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18159. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18160. }
  18161. };
  18162. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18163. var _this = this;
  18164. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18165. for (var i = 0; i < _cam.length; i++) {
  18166. var camera = _cam[i];
  18167. var cameraName = camera.name;
  18168. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18169. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18170. });
  18171. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18172. }
  18173. for (var renderEffectName in this._renderEffects) {
  18174. this._renderEffects[renderEffectName]._enable(_cam);
  18175. }
  18176. };
  18177. PostProcessRenderPipeline.prototype._update = function () {
  18178. for (var renderEffectName in this._renderEffects) {
  18179. this._renderEffects[renderEffectName]._update();
  18180. }
  18181. for (var i = 0; i < this._cameras.length; i++) {
  18182. var cameraName = this._cameras[i].name;
  18183. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18184. this._renderEffectsForIsolatedPass[cameraName]._update();
  18185. }
  18186. }
  18187. };
  18188. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18189. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18190. return PostProcessRenderPipeline;
  18191. })();
  18192. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18193. })(BABYLON || (BABYLON = {}));
  18194. var BABYLON;
  18195. (function (BABYLON) {
  18196. var PostProcessRenderPipelineManager = (function () {
  18197. function PostProcessRenderPipelineManager() {
  18198. this._renderPipelines = new Array();
  18199. }
  18200. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18201. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18202. };
  18203. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18204. var renderPipeline = this._renderPipelines[renderPipelineName];
  18205. if (!renderPipeline) {
  18206. return;
  18207. }
  18208. renderPipeline._attachCameras(cameras, unique);
  18209. };
  18210. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18211. var renderPipeline = this._renderPipelines[renderPipelineName];
  18212. if (!renderPipeline) {
  18213. return;
  18214. }
  18215. renderPipeline._detachCameras(cameras);
  18216. };
  18217. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18218. var renderPipeline = this._renderPipelines[renderPipelineName];
  18219. if (!renderPipeline) {
  18220. return;
  18221. }
  18222. renderPipeline._enableEffect(renderEffectName, cameras);
  18223. };
  18224. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18225. var renderPipeline = this._renderPipelines[renderPipelineName];
  18226. if (!renderPipeline) {
  18227. return;
  18228. }
  18229. renderPipeline._disableEffect(renderEffectName, cameras);
  18230. };
  18231. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18232. var renderPipeline = this._renderPipelines[renderPipelineName];
  18233. if (!renderPipeline) {
  18234. return;
  18235. }
  18236. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18237. };
  18238. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18239. var renderPipeline = this._renderPipelines[renderPipelineName];
  18240. if (!renderPipeline) {
  18241. return;
  18242. }
  18243. renderPipeline._disableDisplayOnlyPass(cameras);
  18244. };
  18245. PostProcessRenderPipelineManager.prototype.update = function () {
  18246. for (var renderPipelineName in this._renderPipelines) {
  18247. this._renderPipelines[renderPipelineName]._update();
  18248. }
  18249. };
  18250. return PostProcessRenderPipelineManager;
  18251. })();
  18252. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18253. })(BABYLON || (BABYLON = {}));
  18254. var __extends = this.__extends || function (d, b) {
  18255. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18256. function __() { this.constructor = d; }
  18257. __.prototype = b.prototype;
  18258. d.prototype = new __();
  18259. };
  18260. var BABYLON;
  18261. (function (BABYLON) {
  18262. var DisplayPassPostProcess = (function (_super) {
  18263. __extends(DisplayPassPostProcess, _super);
  18264. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18265. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18266. }
  18267. return DisplayPassPostProcess;
  18268. })(BABYLON.PostProcess);
  18269. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18270. })(BABYLON || (BABYLON = {}));
  18271. var BABYLON;
  18272. (function (BABYLON) {
  18273. var BoundingBoxRenderer = (function () {
  18274. function BoundingBoxRenderer(scene) {
  18275. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18276. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18277. this.showBackLines = true;
  18278. this.renderList = new BABYLON.SmartArray(32);
  18279. this._scene = scene;
  18280. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18281. attributes: ["position"],
  18282. uniforms: ["worldViewProjection", "color"]
  18283. });
  18284. var engine = this._scene.getEngine();
  18285. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18286. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18287. 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]);
  18288. }
  18289. BoundingBoxRenderer.prototype.reset = function () {
  18290. this.renderList.reset();
  18291. };
  18292. BoundingBoxRenderer.prototype.render = function () {
  18293. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18294. return;
  18295. }
  18296. var engine = this._scene.getEngine();
  18297. engine.setDepthWrite(false);
  18298. this._colorShader._preBind();
  18299. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18300. var boundingBox = this.renderList.data[boundingBoxIndex];
  18301. var min = boundingBox.minimum;
  18302. var max = boundingBox.maximum;
  18303. var diff = max.subtract(min);
  18304. var median = min.add(diff.scale(0.5));
  18305. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18306. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18307. if (this.showBackLines) {
  18308. engine.setDepthFunctionToGreaterOrEqual();
  18309. this._colorShader.setColor4("color", this.backColor.toColor4());
  18310. this._colorShader.bind(worldMatrix);
  18311. engine.draw(false, 0, 24);
  18312. }
  18313. engine.setDepthFunctionToLess();
  18314. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18315. this._colorShader.bind(worldMatrix);
  18316. engine.draw(false, 0, 24);
  18317. }
  18318. this._colorShader.unbind();
  18319. engine.setDepthFunctionToLessOrEqual();
  18320. engine.setDepthWrite(true);
  18321. };
  18322. BoundingBoxRenderer.prototype.dispose = function () {
  18323. this._colorShader.dispose();
  18324. this._vb.dispose();
  18325. this._scene.getEngine()._releaseBuffer(this._ib);
  18326. };
  18327. return BoundingBoxRenderer;
  18328. })();
  18329. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18330. })(BABYLON || (BABYLON = {}));
  18331. /**
  18332. * Based on jsTGALoader - Javascript loader for TGA file
  18333. * By Vincent Thibault
  18334. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18335. */
  18336. var BABYLON;
  18337. (function (BABYLON) {
  18338. (function (Internals) {
  18339. var TGATools = (function () {
  18340. function TGATools() {
  18341. }
  18342. TGATools.GetTGAHeader = function (data) {
  18343. var offset = 0;
  18344. var header = {
  18345. id_length: data[offset++],
  18346. colormap_type: data[offset++],
  18347. image_type: data[offset++],
  18348. colormap_index: data[offset++] | data[offset++] << 8,
  18349. colormap_length: data[offset++] | data[offset++] << 8,
  18350. colormap_size: data[offset++],
  18351. origin: [
  18352. data[offset++] | data[offset++] << 8,
  18353. data[offset++] | data[offset++] << 8
  18354. ],
  18355. width: data[offset++] | data[offset++] << 8,
  18356. height: data[offset++] | data[offset++] << 8,
  18357. pixel_size: data[offset++],
  18358. flags: data[offset++]
  18359. };
  18360. return header;
  18361. };
  18362. TGATools.UploadContent = function (gl, data) {
  18363. if (data.length < 19) {
  18364. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18365. return;
  18366. }
  18367. var offset = 18;
  18368. var header = TGATools.GetTGAHeader(data);
  18369. if (header.id_length + offset > data.length) {
  18370. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18371. return;
  18372. }
  18373. offset += header.id_length;
  18374. var use_rle = false;
  18375. var use_pal = false;
  18376. var use_rgb = false;
  18377. var use_grey = false;
  18378. switch (header.image_type) {
  18379. case TGATools._TYPE_RLE_INDEXED:
  18380. use_rle = true;
  18381. case TGATools._TYPE_INDEXED:
  18382. use_pal = true;
  18383. break;
  18384. case TGATools._TYPE_RLE_RGB:
  18385. use_rle = true;
  18386. case TGATools._TYPE_RGB:
  18387. use_rgb = true;
  18388. break;
  18389. case TGATools._TYPE_RLE_GREY:
  18390. use_rle = true;
  18391. case TGATools._TYPE_GREY:
  18392. use_grey = true;
  18393. break;
  18394. }
  18395. var pixel_data;
  18396. var numAlphaBits = header.flags & 0xf;
  18397. var pixel_size = header.pixel_size >> 3;
  18398. var pixel_total = header.width * header.height * pixel_size;
  18399. var palettes;
  18400. if (use_pal) {
  18401. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18402. }
  18403. if (use_rle) {
  18404. pixel_data = new Uint8Array(pixel_total);
  18405. var c, count, i;
  18406. var localOffset = 0;
  18407. var pixels = new Uint8Array(pixel_size);
  18408. while (offset < pixel_total && localOffset < pixel_total) {
  18409. c = data[offset++];
  18410. count = (c & 0x7f) + 1;
  18411. if (c & 0x80) {
  18412. for (i = 0; i < pixel_size; ++i) {
  18413. pixels[i] = data[offset++];
  18414. }
  18415. for (i = 0; i < count; ++i) {
  18416. pixel_data.set(pixels, localOffset + i * pixel_size);
  18417. }
  18418. localOffset += pixel_size * count;
  18419. } else {
  18420. count *= pixel_size;
  18421. for (i = 0; i < count; ++i) {
  18422. pixel_data[localOffset + i] = data[offset++];
  18423. }
  18424. localOffset += count;
  18425. }
  18426. }
  18427. } else {
  18428. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18429. }
  18430. var x_start, y_start, x_step, y_step, y_end, x_end;
  18431. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18432. default:
  18433. case TGATools._ORIGIN_UL:
  18434. x_start = 0;
  18435. x_step = 1;
  18436. x_end = header.width;
  18437. y_start = 0;
  18438. y_step = 1;
  18439. y_end = header.height;
  18440. break;
  18441. case TGATools._ORIGIN_BL:
  18442. x_start = 0;
  18443. x_step = 1;
  18444. x_end = header.width;
  18445. y_start = header.height - 1;
  18446. y_step = -1;
  18447. y_end = -1;
  18448. break;
  18449. case TGATools._ORIGIN_UR:
  18450. x_start = header.width - 1;
  18451. x_step = -1;
  18452. x_end = -1;
  18453. y_start = 0;
  18454. y_step = 1;
  18455. y_end = header.height;
  18456. break;
  18457. case TGATools._ORIGIN_BR:
  18458. x_start = header.width - 1;
  18459. x_step = -1;
  18460. x_end = -1;
  18461. y_start = header.height - 1;
  18462. y_step = -1;
  18463. y_end = -1;
  18464. break;
  18465. }
  18466. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18467. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18468. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18469. };
  18470. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18471. var image = pixel_data, colormap = palettes;
  18472. var width = header.width, height = header.height;
  18473. var color, i = 0, x, y;
  18474. var imageData = new Uint8Array(width * height * 4);
  18475. for (y = y_start; y !== y_end; y += y_step) {
  18476. for (x = x_start; x !== x_end; x += x_step, i++) {
  18477. color = image[i];
  18478. imageData[(x + width * y) * 4 + 3] = 255;
  18479. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18480. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18481. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18482. }
  18483. }
  18484. return imageData;
  18485. };
  18486. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18487. var image = pixel_data;
  18488. var width = header.width, height = header.height;
  18489. var color, i = 0, x, y;
  18490. var imageData = new Uint8Array(width * height * 4);
  18491. for (y = y_start; y !== y_end; y += y_step) {
  18492. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18493. color = image[i + 0] + (image[i + 1] << 8);
  18494. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18495. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18496. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18497. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18498. }
  18499. }
  18500. return imageData;
  18501. };
  18502. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18503. var image = pixel_data;
  18504. var width = header.width, height = header.height;
  18505. var i = 0, x, y;
  18506. var imageData = new Uint8Array(width * height * 4);
  18507. for (y = y_start; y !== y_end; y += y_step) {
  18508. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18509. imageData[(x + width * y) * 4 + 3] = 255;
  18510. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18511. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18512. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18513. }
  18514. }
  18515. return imageData;
  18516. };
  18517. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18518. var image = pixel_data;
  18519. var width = header.width, height = header.height;
  18520. var i = 0, x, y;
  18521. var imageData = new Uint8Array(width * height * 4);
  18522. for (y = y_start; y !== y_end; y += y_step) {
  18523. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18524. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18525. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18526. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18527. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18528. }
  18529. }
  18530. return imageData;
  18531. };
  18532. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18533. var image = pixel_data;
  18534. var width = header.width, height = header.height;
  18535. var color, i = 0, x, y;
  18536. var imageData = new Uint8Array(width * height * 4);
  18537. for (y = y_start; y !== y_end; y += y_step) {
  18538. for (x = x_start; x !== x_end; x += x_step, i++) {
  18539. color = image[i];
  18540. imageData[(x + width * y) * 4 + 0] = color;
  18541. imageData[(x + width * y) * 4 + 1] = color;
  18542. imageData[(x + width * y) * 4 + 2] = color;
  18543. imageData[(x + width * y) * 4 + 3] = 255;
  18544. }
  18545. }
  18546. return imageData;
  18547. };
  18548. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18549. var image = pixel_data;
  18550. var width = header.width, height = header.height;
  18551. var i = 0, x, y;
  18552. var imageData = new Uint8Array(width * height * 4);
  18553. for (y = y_start; y !== y_end; y += y_step) {
  18554. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18555. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18556. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18557. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18558. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18559. }
  18560. }
  18561. return imageData;
  18562. };
  18563. TGATools._TYPE_NO_DATA = 0;
  18564. TGATools._TYPE_INDEXED = 1;
  18565. TGATools._TYPE_RGB = 2;
  18566. TGATools._TYPE_GREY = 3;
  18567. TGATools._TYPE_RLE_INDEXED = 9;
  18568. TGATools._TYPE_RLE_RGB = 10;
  18569. TGATools._TYPE_RLE_GREY = 11;
  18570. TGATools._ORIGIN_MASK = 0x30;
  18571. TGATools._ORIGIN_SHIFT = 0x04;
  18572. TGATools._ORIGIN_BL = 0x00;
  18573. TGATools._ORIGIN_BR = 0x01;
  18574. TGATools._ORIGIN_UL = 0x02;
  18575. TGATools._ORIGIN_UR = 0x03;
  18576. return TGATools;
  18577. })();
  18578. Internals.TGATools = TGATools;
  18579. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18580. var Internals = BABYLON.Internals;
  18581. })(BABYLON || (BABYLON = {}));
  18582. var BABYLON;
  18583. (function (BABYLON) {
  18584. (function (Internals) {
  18585. var DDS_MAGIC = 0x20534444;
  18586. 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;
  18587. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18588. 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;
  18589. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18590. function FourCCToInt32(value) {
  18591. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18592. }
  18593. function Int32ToFourCC(value) {
  18594. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18595. }
  18596. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18597. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18598. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18599. var headerLengthInt = 31;
  18600. var off_magic = 0;
  18601. var off_size = 1;
  18602. var off_flags = 2;
  18603. var off_height = 3;
  18604. var off_width = 4;
  18605. var off_mipmapCount = 7;
  18606. var off_pfFlags = 20;
  18607. var off_pfFourCC = 21;
  18608. var off_RGBbpp = 22;
  18609. var off_RMask = 23;
  18610. var off_GMask = 24;
  18611. var off_BMask = 25;
  18612. var off_AMask = 26;
  18613. var off_caps1 = 27;
  18614. var off_caps2 = 28;
  18615. ;
  18616. var DDSTools = (function () {
  18617. function DDSTools() {
  18618. }
  18619. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18620. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18621. var mipmapCount = 1;
  18622. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18623. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18624. }
  18625. return {
  18626. width: header[off_width],
  18627. height: header[off_height],
  18628. mipmapCount: mipmapCount,
  18629. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18630. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18631. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18632. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18633. };
  18634. };
  18635. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18636. var byteArray = new Uint8Array(dataLength);
  18637. var srcData = new Uint8Array(arrayBuffer);
  18638. var index = 0;
  18639. for (var y = height - 1; y >= 0; y--) {
  18640. for (var x = 0; x < width; x++) {
  18641. var srcPos = dataOffset + (x + y * width) * 4;
  18642. byteArray[index + 2] = srcData[srcPos];
  18643. byteArray[index + 1] = srcData[srcPos + 1];
  18644. byteArray[index] = srcData[srcPos + 2];
  18645. byteArray[index + 3] = srcData[srcPos + 3];
  18646. index += 4;
  18647. }
  18648. }
  18649. return byteArray;
  18650. };
  18651. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18652. var byteArray = new Uint8Array(dataLength);
  18653. var srcData = new Uint8Array(arrayBuffer);
  18654. var index = 0;
  18655. for (var y = height - 1; y >= 0; y--) {
  18656. for (var x = 0; x < width; x++) {
  18657. var srcPos = dataOffset + (x + y * width) * 3;
  18658. byteArray[index + 2] = srcData[srcPos];
  18659. byteArray[index + 1] = srcData[srcPos + 1];
  18660. byteArray[index] = srcData[srcPos + 2];
  18661. index += 3;
  18662. }
  18663. }
  18664. return byteArray;
  18665. };
  18666. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18667. var byteArray = new Uint8Array(dataLength);
  18668. var srcData = new Uint8Array(arrayBuffer);
  18669. var index = 0;
  18670. for (var y = height - 1; y >= 0; y--) {
  18671. for (var x = 0; x < width; x++) {
  18672. var srcPos = dataOffset + (x + y * width);
  18673. byteArray[index] = srcData[srcPos];
  18674. index++;
  18675. }
  18676. }
  18677. return byteArray;
  18678. };
  18679. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18680. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18681. if (header[off_magic] != DDS_MAGIC) {
  18682. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18683. return;
  18684. }
  18685. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18686. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18687. return;
  18688. }
  18689. if (info.isFourCC) {
  18690. fourCC = header[off_pfFourCC];
  18691. switch (fourCC) {
  18692. case FOURCC_DXT1:
  18693. blockBytes = 8;
  18694. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18695. break;
  18696. case FOURCC_DXT3:
  18697. blockBytes = 16;
  18698. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18699. break;
  18700. case FOURCC_DXT5:
  18701. blockBytes = 16;
  18702. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18703. break;
  18704. default:
  18705. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18706. return;
  18707. }
  18708. }
  18709. mipmapCount = 1;
  18710. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18711. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18712. }
  18713. var bpp = header[off_RGBbpp];
  18714. for (var face = 0; face < faces; face++) {
  18715. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18716. width = header[off_width];
  18717. height = header[off_height];
  18718. dataOffset = header[off_size] + 4;
  18719. for (i = 0; i < mipmapCount; ++i) {
  18720. if (info.isRGB) {
  18721. if (bpp == 24) {
  18722. dataLength = width * height * 3;
  18723. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18724. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18725. } else {
  18726. dataLength = width * height * 4;
  18727. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18728. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18729. }
  18730. } else if (info.isLuminance) {
  18731. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18732. var unpaddedRowSize = width;
  18733. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18734. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18735. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18736. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18737. } else {
  18738. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18739. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18740. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18741. }
  18742. dataOffset += dataLength;
  18743. width *= 0.5;
  18744. height *= 0.5;
  18745. width = Math.max(1.0, width);
  18746. height = Math.max(1.0, height);
  18747. }
  18748. }
  18749. };
  18750. return DDSTools;
  18751. })();
  18752. Internals.DDSTools = DDSTools;
  18753. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18754. var Internals = BABYLON.Internals;
  18755. })(BABYLON || (BABYLON = {}));
  18756. var BABYLON;
  18757. (function (BABYLON) {
  18758. var SmartArray = (function () {
  18759. function SmartArray(capacity) {
  18760. this.length = 0;
  18761. this._duplicateId = 0;
  18762. this.data = new Array(capacity);
  18763. this._id = SmartArray._GlobalId++;
  18764. }
  18765. SmartArray.prototype.push = function (value) {
  18766. this.data[this.length++] = value;
  18767. if (this.length > this.data.length) {
  18768. this.data.length *= 2;
  18769. }
  18770. if (!value.__smartArrayFlags) {
  18771. value.__smartArrayFlags = {};
  18772. }
  18773. value.__smartArrayFlags[this._id] = this._duplicateId;
  18774. };
  18775. SmartArray.prototype.pushNoDuplicate = function (value) {
  18776. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18777. return;
  18778. }
  18779. this.push(value);
  18780. };
  18781. SmartArray.prototype.sort = function (compareFn) {
  18782. this.data.sort(compareFn);
  18783. };
  18784. SmartArray.prototype.reset = function () {
  18785. this.length = 0;
  18786. this._duplicateId++;
  18787. };
  18788. SmartArray.prototype.concat = function (array) {
  18789. if (array.length === 0) {
  18790. return;
  18791. }
  18792. if (this.length + array.length > this.data.length) {
  18793. this.data.length = (this.length + array.length) * 2;
  18794. }
  18795. for (var index = 0; index < array.length; index++) {
  18796. this.data[this.length++] = (array.data || array)[index];
  18797. }
  18798. };
  18799. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18800. if (array.length === 0) {
  18801. return;
  18802. }
  18803. if (this.length + array.length > this.data.length) {
  18804. this.data.length = (this.length + array.length) * 2;
  18805. }
  18806. for (var index = 0; index < array.length; index++) {
  18807. var item = (array.data || array)[index];
  18808. this.pushNoDuplicate(item);
  18809. }
  18810. };
  18811. SmartArray.prototype.indexOf = function (value) {
  18812. var position = this.data.indexOf(value);
  18813. if (position >= this.length) {
  18814. return -1;
  18815. }
  18816. return position;
  18817. };
  18818. SmartArray._GlobalId = 0;
  18819. return SmartArray;
  18820. })();
  18821. BABYLON.SmartArray = SmartArray;
  18822. })(BABYLON || (BABYLON = {}));
  18823. var BABYLON;
  18824. (function (BABYLON) {
  18825. var CannonJSPlugin = (function () {
  18826. function CannonJSPlugin() {
  18827. this._registeredMeshes = [];
  18828. this._physicsMaterials = [];
  18829. this.updateBodyPosition = function (mesh) {
  18830. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18831. var registeredMesh = this._registeredMeshes[index];
  18832. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18833. var body = registeredMesh.body;
  18834. var center = mesh.getBoundingInfo().boundingBox.center;
  18835. body.position.set(center.x, center.z, center.y);
  18836. body.quaternion.x = mesh.rotationQuaternion.x;
  18837. body.quaternion.z = mesh.rotationQuaternion.y;
  18838. body.quaternion.y = mesh.rotationQuaternion.z;
  18839. body.quaternion.w = -mesh.rotationQuaternion.w;
  18840. return;
  18841. }
  18842. }
  18843. };
  18844. }
  18845. CannonJSPlugin.prototype.initialize = function (iterations) {
  18846. if (typeof iterations === "undefined") { iterations = 10; }
  18847. this._world = new CANNON.World();
  18848. this._world.broadphase = new CANNON.NaiveBroadphase();
  18849. this._world.solver.iterations = iterations;
  18850. };
  18851. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18852. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18853. };
  18854. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18855. this._world.step(delta);
  18856. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18857. var registeredMesh = this._registeredMeshes[index];
  18858. if (registeredMesh.isChild) {
  18859. continue;
  18860. }
  18861. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18862. var deltaPos = registeredMesh.delta;
  18863. if (deltaPos) {
  18864. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18865. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18866. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18867. } else {
  18868. registeredMesh.mesh.position.x = bodyX;
  18869. registeredMesh.mesh.position.y = bodyZ;
  18870. registeredMesh.mesh.position.z = bodyY;
  18871. }
  18872. if (!registeredMesh.mesh.rotationQuaternion) {
  18873. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18874. }
  18875. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18876. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18877. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18878. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18879. }
  18880. };
  18881. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18882. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18883. };
  18884. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18885. this.unregisterMesh(mesh);
  18886. mesh.computeWorldMatrix(true);
  18887. switch (impostor) {
  18888. case BABYLON.PhysicsEngine.SphereImpostor:
  18889. var bbox = mesh.getBoundingInfo().boundingBox;
  18890. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18891. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18892. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18893. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18894. case BABYLON.PhysicsEngine.BoxImpostor:
  18895. bbox = mesh.getBoundingInfo().boundingBox;
  18896. var min = bbox.minimumWorld;
  18897. var max = bbox.maximumWorld;
  18898. var box = max.subtract(min).scale(0.5);
  18899. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18900. case BABYLON.PhysicsEngine.PlaneImpostor:
  18901. return this._createPlane(mesh, options);
  18902. case BABYLON.PhysicsEngine.MeshImpostor:
  18903. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18904. var rawFaces = mesh.getIndices();
  18905. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18906. }
  18907. return null;
  18908. };
  18909. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18910. var shape = new CANNON.Sphere(radius);
  18911. if (!options) {
  18912. return shape;
  18913. }
  18914. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18915. };
  18916. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18917. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18918. if (!options) {
  18919. return shape;
  18920. }
  18921. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18922. };
  18923. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18924. var shape = new CANNON.Plane();
  18925. if (!options) {
  18926. return shape;
  18927. }
  18928. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18929. };
  18930. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18931. var verts = [], faces = [];
  18932. mesh.computeWorldMatrix(true);
  18933. for (var i = 0; i < rawVerts.length; i += 3) {
  18934. var transformed = BABYLON.Vector3.Zero();
  18935. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18936. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18937. }
  18938. for (var j = 0; j < rawFaces.length; j += 3) {
  18939. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18940. }
  18941. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18942. if (!options) {
  18943. return shape;
  18944. }
  18945. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18946. };
  18947. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18948. var index;
  18949. var mat;
  18950. for (index = 0; index < this._physicsMaterials.length; index++) {
  18951. mat = this._physicsMaterials[index];
  18952. if (mat.friction === friction && mat.restitution === restitution) {
  18953. return mat;
  18954. }
  18955. }
  18956. var currentMat = new CANNON.Material();
  18957. currentMat.friction = friction;
  18958. currentMat.restitution = restitution;
  18959. this._physicsMaterials.push(currentMat);
  18960. for (index = 0; index < this._physicsMaterials.length; index++) {
  18961. mat = this._physicsMaterials[index];
  18962. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18963. contactMaterial.contactEquationStiffness = 1e10;
  18964. contactMaterial.contactEquationRegularizationTime = 10;
  18965. this._world.addContactMaterial(contactMaterial);
  18966. }
  18967. return currentMat;
  18968. };
  18969. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18970. var initialRotation = null;
  18971. if (mesh.rotationQuaternion) {
  18972. initialRotation = mesh.rotationQuaternion.clone();
  18973. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18974. }
  18975. var bbox = mesh.getBoundingInfo().boundingBox;
  18976. var deltaPosition = mesh.position.subtract(bbox.center);
  18977. var material = this._addMaterial(friction, restitution);
  18978. var body = new CANNON.RigidBody(mass, shape, material);
  18979. if (initialRotation) {
  18980. body.quaternion.x = initialRotation.x;
  18981. body.quaternion.z = initialRotation.y;
  18982. body.quaternion.y = initialRotation.z;
  18983. body.quaternion.w = -initialRotation.w;
  18984. }
  18985. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18986. this._world.add(body);
  18987. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18988. return body;
  18989. };
  18990. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18991. var compoundShape = new CANNON.Compound();
  18992. for (var index = 0; index < parts.length; index++) {
  18993. var mesh = parts[index].mesh;
  18994. var shape = this.registerMesh(mesh, parts[index].impostor);
  18995. if (index == 0) {
  18996. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18997. } else {
  18998. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18999. }
  19000. }
  19001. var initialMesh = parts[0].mesh;
  19002. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19003. body.parts = parts;
  19004. return body;
  19005. };
  19006. CannonJSPlugin.prototype._unbindBody = function (body) {
  19007. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19008. var registeredMesh = this._registeredMeshes[index];
  19009. if (registeredMesh.body === body) {
  19010. registeredMesh.body = null;
  19011. registeredMesh.delta = 0;
  19012. }
  19013. }
  19014. };
  19015. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19016. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19017. var registeredMesh = this._registeredMeshes[index];
  19018. if (registeredMesh.mesh === mesh) {
  19019. if (registeredMesh.body) {
  19020. this._world.remove(registeredMesh.body);
  19021. this._unbindBody(registeredMesh.body);
  19022. }
  19023. this._registeredMeshes.splice(index, 1);
  19024. return;
  19025. }
  19026. }
  19027. };
  19028. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19029. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19030. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19031. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19032. var registeredMesh = this._registeredMeshes[index];
  19033. if (registeredMesh.mesh === mesh) {
  19034. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19035. return;
  19036. }
  19037. }
  19038. };
  19039. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19040. var body1 = null, body2 = null;
  19041. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19042. var registeredMesh = this._registeredMeshes[index];
  19043. if (registeredMesh.mesh === mesh1) {
  19044. body1 = registeredMesh.body;
  19045. } else if (registeredMesh.mesh === mesh2) {
  19046. body2 = registeredMesh.body;
  19047. }
  19048. }
  19049. if (!body1 || !body2) {
  19050. return false;
  19051. }
  19052. 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));
  19053. this._world.addConstraint(constraint);
  19054. return true;
  19055. };
  19056. CannonJSPlugin.prototype.dispose = function () {
  19057. while (this._registeredMeshes.length) {
  19058. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19059. }
  19060. };
  19061. CannonJSPlugin.prototype.isSupported = function () {
  19062. return window.CANNON !== undefined;
  19063. };
  19064. return CannonJSPlugin;
  19065. })();
  19066. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19067. })(BABYLON || (BABYLON = {}));
  19068. var __extends = this.__extends || function (d, b) {
  19069. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19070. function __() { this.constructor = d; }
  19071. __.prototype = b.prototype;
  19072. d.prototype = new __();
  19073. };
  19074. var BABYLON;
  19075. (function (BABYLON) {
  19076. var Condition = (function () {
  19077. function Condition(actionManager) {
  19078. this._actionManager = actionManager;
  19079. }
  19080. Condition.prototype.isValid = function () {
  19081. return true;
  19082. };
  19083. Condition.prototype._getProperty = function (propertyPath) {
  19084. return this._actionManager._getProperty(propertyPath);
  19085. };
  19086. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19087. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19088. };
  19089. return Condition;
  19090. })();
  19091. BABYLON.Condition = Condition;
  19092. var ValueCondition = (function (_super) {
  19093. __extends(ValueCondition, _super);
  19094. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19095. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19096. _super.call(this, actionManager);
  19097. this.propertyPath = propertyPath;
  19098. this.value = value;
  19099. this.operator = operator;
  19100. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19101. this._property = this._getProperty(this.propertyPath);
  19102. }
  19103. Object.defineProperty(ValueCondition, "IsEqual", {
  19104. get: function () {
  19105. return ValueCondition._IsEqual;
  19106. },
  19107. enumerable: true,
  19108. configurable: true
  19109. });
  19110. Object.defineProperty(ValueCondition, "IsDifferent", {
  19111. get: function () {
  19112. return ValueCondition._IsDifferent;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. Object.defineProperty(ValueCondition, "IsGreater", {
  19118. get: function () {
  19119. return ValueCondition._IsGreater;
  19120. },
  19121. enumerable: true,
  19122. configurable: true
  19123. });
  19124. Object.defineProperty(ValueCondition, "IsLesser", {
  19125. get: function () {
  19126. return ValueCondition._IsLesser;
  19127. },
  19128. enumerable: true,
  19129. configurable: true
  19130. });
  19131. ValueCondition.prototype.isValid = function () {
  19132. switch (this.operator) {
  19133. case ValueCondition.IsGreater:
  19134. return this._target[this._property] > this.value;
  19135. case ValueCondition.IsLesser:
  19136. return this._target[this._property] < this.value;
  19137. case ValueCondition.IsEqual:
  19138. case ValueCondition.IsDifferent:
  19139. var check;
  19140. if (this.value.equals) {
  19141. check = this.value.equals(this._target[this._property]);
  19142. } else {
  19143. check = this.value === this._target[this._property];
  19144. }
  19145. return this.operator === ValueCondition.IsEqual ? check : !check;
  19146. }
  19147. return false;
  19148. };
  19149. ValueCondition._IsEqual = 0;
  19150. ValueCondition._IsDifferent = 1;
  19151. ValueCondition._IsGreater = 2;
  19152. ValueCondition._IsLesser = 3;
  19153. return ValueCondition;
  19154. })(Condition);
  19155. BABYLON.ValueCondition = ValueCondition;
  19156. var PredicateCondition = (function (_super) {
  19157. __extends(PredicateCondition, _super);
  19158. function PredicateCondition(actionManager, predicate) {
  19159. _super.call(this, actionManager);
  19160. this.predicate = predicate;
  19161. }
  19162. PredicateCondition.prototype.isValid = function () {
  19163. return this.predicate();
  19164. };
  19165. return PredicateCondition;
  19166. })(Condition);
  19167. BABYLON.PredicateCondition = PredicateCondition;
  19168. var StateCondition = (function (_super) {
  19169. __extends(StateCondition, _super);
  19170. function StateCondition(actionManager, target, value) {
  19171. _super.call(this, actionManager);
  19172. this.value = value;
  19173. this._target = target;
  19174. }
  19175. StateCondition.prototype.isValid = function () {
  19176. return this._target.state === this.value;
  19177. };
  19178. return StateCondition;
  19179. })(Condition);
  19180. BABYLON.StateCondition = StateCondition;
  19181. })(BABYLON || (BABYLON = {}));
  19182. var BABYLON;
  19183. (function (BABYLON) {
  19184. var Action = (function () {
  19185. function Action(triggerOptions, condition) {
  19186. this.triggerOptions = triggerOptions;
  19187. if (triggerOptions.parameter) {
  19188. this.trigger = triggerOptions.trigger;
  19189. this._triggerParameter = triggerOptions.parameter;
  19190. } else {
  19191. this.trigger = triggerOptions;
  19192. }
  19193. this._nextActiveAction = this;
  19194. this._condition = condition;
  19195. }
  19196. Action.prototype._prepare = function () {
  19197. };
  19198. Action.prototype.getTriggerParameter = function () {
  19199. return this._triggerParameter;
  19200. };
  19201. Action.prototype._executeCurrent = function (evt) {
  19202. if (this._condition) {
  19203. var currentRenderId = this._actionManager.getScene().getRenderId();
  19204. if (this._condition._evaluationId === currentRenderId) {
  19205. if (!this._condition._currentResult) {
  19206. return;
  19207. }
  19208. } else {
  19209. this._condition._evaluationId = currentRenderId;
  19210. if (!this._condition.isValid()) {
  19211. this._condition._currentResult = false;
  19212. return;
  19213. }
  19214. this._condition._currentResult = true;
  19215. }
  19216. }
  19217. this._nextActiveAction.execute(evt);
  19218. if (this._nextActiveAction._child) {
  19219. if (!this._nextActiveAction._child._actionManager) {
  19220. this._nextActiveAction._child._actionManager = this._actionManager;
  19221. }
  19222. this._nextActiveAction = this._nextActiveAction._child;
  19223. } else {
  19224. this._nextActiveAction = this;
  19225. }
  19226. };
  19227. Action.prototype.execute = function (evt) {
  19228. };
  19229. Action.prototype.then = function (action) {
  19230. this._child = action;
  19231. action._actionManager = this._actionManager;
  19232. action._prepare();
  19233. return action;
  19234. };
  19235. Action.prototype._getProperty = function (propertyPath) {
  19236. return this._actionManager._getProperty(propertyPath);
  19237. };
  19238. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19239. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19240. };
  19241. return Action;
  19242. })();
  19243. BABYLON.Action = Action;
  19244. })(BABYLON || (BABYLON = {}));
  19245. var BABYLON;
  19246. (function (BABYLON) {
  19247. var ActionEvent = (function () {
  19248. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19249. this.source = source;
  19250. this.pointerX = pointerX;
  19251. this.pointerY = pointerY;
  19252. this.meshUnderPointer = meshUnderPointer;
  19253. this.sourceEvent = sourceEvent;
  19254. }
  19255. ActionEvent.CreateNew = function (source) {
  19256. var scene = source.getScene();
  19257. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19258. };
  19259. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19260. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19261. };
  19262. return ActionEvent;
  19263. })();
  19264. BABYLON.ActionEvent = ActionEvent;
  19265. var ActionManager = (function () {
  19266. function ActionManager(scene) {
  19267. this.actions = new Array();
  19268. this._scene = scene;
  19269. scene._actionManagers.push(this);
  19270. }
  19271. Object.defineProperty(ActionManager, "NothingTrigger", {
  19272. get: function () {
  19273. return ActionManager._NothingTrigger;
  19274. },
  19275. enumerable: true,
  19276. configurable: true
  19277. });
  19278. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19279. get: function () {
  19280. return ActionManager._OnPickTrigger;
  19281. },
  19282. enumerable: true,
  19283. configurable: true
  19284. });
  19285. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19286. get: function () {
  19287. return ActionManager._OnLeftPickTrigger;
  19288. },
  19289. enumerable: true,
  19290. configurable: true
  19291. });
  19292. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19293. get: function () {
  19294. return ActionManager._OnRightPickTrigger;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19300. get: function () {
  19301. return ActionManager._OnCenterPickTrigger;
  19302. },
  19303. enumerable: true,
  19304. configurable: true
  19305. });
  19306. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19307. get: function () {
  19308. return ActionManager._OnPointerOverTrigger;
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19314. get: function () {
  19315. return ActionManager._OnPointerOutTrigger;
  19316. },
  19317. enumerable: true,
  19318. configurable: true
  19319. });
  19320. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19321. get: function () {
  19322. return ActionManager._OnEveryFrameTrigger;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19328. get: function () {
  19329. return ActionManager._OnIntersectionEnterTrigger;
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19335. get: function () {
  19336. return ActionManager._OnIntersectionExitTrigger;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19342. get: function () {
  19343. return ActionManager._OnKeyDownTrigger;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19349. get: function () {
  19350. return ActionManager._OnKeyUpTrigger;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. ActionManager.prototype.dispose = function () {
  19356. var index = this._scene._actionManagers.indexOf(this);
  19357. if (index > -1) {
  19358. this._scene._actionManagers.splice(index, 1);
  19359. }
  19360. };
  19361. ActionManager.prototype.getScene = function () {
  19362. return this._scene;
  19363. };
  19364. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19365. for (var index = 0; index < this.actions.length; index++) {
  19366. var action = this.actions[index];
  19367. if (triggers.indexOf(action.trigger) > -1) {
  19368. return true;
  19369. }
  19370. }
  19371. return false;
  19372. };
  19373. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19374. get: function () {
  19375. for (var index = 0; index < this.actions.length; index++) {
  19376. var action = this.actions[index];
  19377. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19378. return true;
  19379. }
  19380. }
  19381. return false;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19387. get: function () {
  19388. for (var index = 0; index < this.actions.length; index++) {
  19389. var action = this.actions[index];
  19390. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19391. return true;
  19392. }
  19393. }
  19394. return false;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. ActionManager.prototype.registerAction = function (action) {
  19400. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19401. if (this.getScene().actionManager !== this) {
  19402. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19403. return null;
  19404. }
  19405. }
  19406. this.actions.push(action);
  19407. action._actionManager = this;
  19408. action._prepare();
  19409. return action;
  19410. };
  19411. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19412. for (var index = 0; index < this.actions.length; index++) {
  19413. var action = this.actions[index];
  19414. if (action.trigger === trigger) {
  19415. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19416. var parameter = action.getTriggerParameter();
  19417. if (parameter) {
  19418. if (evt.sourceEvent.key !== parameter) {
  19419. continue;
  19420. }
  19421. }
  19422. }
  19423. action._executeCurrent(evt);
  19424. }
  19425. }
  19426. };
  19427. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19428. var properties = propertyPath.split(".");
  19429. for (var index = 0; index < properties.length - 1; index++) {
  19430. target = target[properties[index]];
  19431. }
  19432. return target;
  19433. };
  19434. ActionManager.prototype._getProperty = function (propertyPath) {
  19435. var properties = propertyPath.split(".");
  19436. return properties[properties.length - 1];
  19437. };
  19438. ActionManager._NothingTrigger = 0;
  19439. ActionManager._OnPickTrigger = 1;
  19440. ActionManager._OnLeftPickTrigger = 2;
  19441. ActionManager._OnRightPickTrigger = 3;
  19442. ActionManager._OnCenterPickTrigger = 4;
  19443. ActionManager._OnPointerOverTrigger = 5;
  19444. ActionManager._OnPointerOutTrigger = 6;
  19445. ActionManager._OnEveryFrameTrigger = 7;
  19446. ActionManager._OnIntersectionEnterTrigger = 8;
  19447. ActionManager._OnIntersectionExitTrigger = 9;
  19448. ActionManager._OnKeyDownTrigger = 10;
  19449. ActionManager._OnKeyUpTrigger = 11;
  19450. return ActionManager;
  19451. })();
  19452. BABYLON.ActionManager = ActionManager;
  19453. })(BABYLON || (BABYLON = {}));
  19454. var __extends = this.__extends || function (d, b) {
  19455. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19456. function __() { this.constructor = d; }
  19457. __.prototype = b.prototype;
  19458. d.prototype = new __();
  19459. };
  19460. var BABYLON;
  19461. (function (BABYLON) {
  19462. var InterpolateValueAction = (function (_super) {
  19463. __extends(InterpolateValueAction, _super);
  19464. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19465. if (typeof duration === "undefined") { duration = 1000; }
  19466. _super.call(this, triggerOptions, condition);
  19467. this.propertyPath = propertyPath;
  19468. this.value = value;
  19469. this.duration = duration;
  19470. this.stopOtherAnimations = stopOtherAnimations;
  19471. this._target = target;
  19472. }
  19473. InterpolateValueAction.prototype._prepare = function () {
  19474. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19475. this._property = this._getProperty(this.propertyPath);
  19476. };
  19477. InterpolateValueAction.prototype.execute = function () {
  19478. var scene = this._actionManager.getScene();
  19479. var keys = [
  19480. {
  19481. frame: 0,
  19482. value: this._target[this._property]
  19483. }, {
  19484. frame: 100,
  19485. value: this.value
  19486. }
  19487. ];
  19488. var dataType;
  19489. if (typeof this.value === "number") {
  19490. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19491. } else if (this.value instanceof BABYLON.Color3) {
  19492. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19493. } else if (this.value instanceof BABYLON.Vector3) {
  19494. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19495. } else if (this.value instanceof BABYLON.Matrix) {
  19496. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19497. } else if (this.value instanceof BABYLON.Quaternion) {
  19498. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19499. } else {
  19500. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19501. return;
  19502. }
  19503. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19504. animation.setKeys(keys);
  19505. if (this.stopOtherAnimations) {
  19506. scene.stopAnimation(this._target);
  19507. }
  19508. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19509. };
  19510. return InterpolateValueAction;
  19511. })(BABYLON.Action);
  19512. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19513. })(BABYLON || (BABYLON = {}));
  19514. var __extends = this.__extends || function (d, b) {
  19515. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19516. function __() { this.constructor = d; }
  19517. __.prototype = b.prototype;
  19518. d.prototype = new __();
  19519. };
  19520. var BABYLON;
  19521. (function (BABYLON) {
  19522. var SwitchBooleanAction = (function (_super) {
  19523. __extends(SwitchBooleanAction, _super);
  19524. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19525. _super.call(this, triggerOptions, condition);
  19526. this.propertyPath = propertyPath;
  19527. this._target = target;
  19528. }
  19529. SwitchBooleanAction.prototype._prepare = function () {
  19530. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19531. this._property = this._getProperty(this.propertyPath);
  19532. };
  19533. SwitchBooleanAction.prototype.execute = function () {
  19534. this._target[this._property] = !this._target[this._property];
  19535. };
  19536. return SwitchBooleanAction;
  19537. })(BABYLON.Action);
  19538. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19539. var SetStateAction = (function (_super) {
  19540. __extends(SetStateAction, _super);
  19541. function SetStateAction(triggerOptions, target, value, condition) {
  19542. _super.call(this, triggerOptions, condition);
  19543. this.value = value;
  19544. this._target = target;
  19545. }
  19546. SetStateAction.prototype.execute = function () {
  19547. this._target.state = this.value;
  19548. };
  19549. return SetStateAction;
  19550. })(BABYLON.Action);
  19551. BABYLON.SetStateAction = SetStateAction;
  19552. var SetValueAction = (function (_super) {
  19553. __extends(SetValueAction, _super);
  19554. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19555. _super.call(this, triggerOptions, condition);
  19556. this.propertyPath = propertyPath;
  19557. this.value = value;
  19558. this._target = target;
  19559. }
  19560. SetValueAction.prototype._prepare = function () {
  19561. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19562. this._property = this._getProperty(this.propertyPath);
  19563. };
  19564. SetValueAction.prototype.execute = function () {
  19565. this._target[this._property] = this.value;
  19566. };
  19567. return SetValueAction;
  19568. })(BABYLON.Action);
  19569. BABYLON.SetValueAction = SetValueAction;
  19570. var IncrementValueAction = (function (_super) {
  19571. __extends(IncrementValueAction, _super);
  19572. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19573. _super.call(this, triggerOptions, condition);
  19574. this.propertyPath = propertyPath;
  19575. this.value = value;
  19576. this._target = target;
  19577. }
  19578. IncrementValueAction.prototype._prepare = function () {
  19579. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19580. this._property = this._getProperty(this.propertyPath);
  19581. if (typeof this._target[this._property] !== "number") {
  19582. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19583. }
  19584. };
  19585. IncrementValueAction.prototype.execute = function () {
  19586. this._target[this._property] += this.value;
  19587. };
  19588. return IncrementValueAction;
  19589. })(BABYLON.Action);
  19590. BABYLON.IncrementValueAction = IncrementValueAction;
  19591. var PlayAnimationAction = (function (_super) {
  19592. __extends(PlayAnimationAction, _super);
  19593. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19594. _super.call(this, triggerOptions, condition);
  19595. this.from = from;
  19596. this.to = to;
  19597. this.loop = loop;
  19598. this._target = target;
  19599. }
  19600. PlayAnimationAction.prototype._prepare = function () {
  19601. };
  19602. PlayAnimationAction.prototype.execute = function () {
  19603. var scene = this._actionManager.getScene();
  19604. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19605. };
  19606. return PlayAnimationAction;
  19607. })(BABYLON.Action);
  19608. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19609. var StopAnimationAction = (function (_super) {
  19610. __extends(StopAnimationAction, _super);
  19611. function StopAnimationAction(triggerOptions, target, condition) {
  19612. _super.call(this, triggerOptions, condition);
  19613. this._target = target;
  19614. }
  19615. StopAnimationAction.prototype._prepare = function () {
  19616. };
  19617. StopAnimationAction.prototype.execute = function () {
  19618. var scene = this._actionManager.getScene();
  19619. scene.stopAnimation(this._target);
  19620. };
  19621. return StopAnimationAction;
  19622. })(BABYLON.Action);
  19623. BABYLON.StopAnimationAction = StopAnimationAction;
  19624. var DoNothingAction = (function (_super) {
  19625. __extends(DoNothingAction, _super);
  19626. function DoNothingAction(triggerOptions, condition) {
  19627. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19628. _super.call(this, triggerOptions, condition);
  19629. }
  19630. DoNothingAction.prototype.execute = function () {
  19631. };
  19632. return DoNothingAction;
  19633. })(BABYLON.Action);
  19634. BABYLON.DoNothingAction = DoNothingAction;
  19635. var CombineAction = (function (_super) {
  19636. __extends(CombineAction, _super);
  19637. function CombineAction(triggerOptions, children, condition) {
  19638. _super.call(this, triggerOptions, condition);
  19639. this.children = children;
  19640. }
  19641. CombineAction.prototype._prepare = function () {
  19642. for (var index = 0; index < this.children.length; index++) {
  19643. this.children[index]._actionManager = this._actionManager;
  19644. this.children[index]._prepare();
  19645. }
  19646. };
  19647. CombineAction.prototype.execute = function (evt) {
  19648. for (var index = 0; index < this.children.length; index++) {
  19649. this.children[index].execute(evt);
  19650. }
  19651. };
  19652. return CombineAction;
  19653. })(BABYLON.Action);
  19654. BABYLON.CombineAction = CombineAction;
  19655. var ExecuteCodeAction = (function (_super) {
  19656. __extends(ExecuteCodeAction, _super);
  19657. function ExecuteCodeAction(triggerOptions, func, condition) {
  19658. _super.call(this, triggerOptions, condition);
  19659. this.func = func;
  19660. }
  19661. ExecuteCodeAction.prototype.execute = function (evt) {
  19662. this.func(evt);
  19663. };
  19664. return ExecuteCodeAction;
  19665. })(BABYLON.Action);
  19666. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19667. var SetParentAction = (function (_super) {
  19668. __extends(SetParentAction, _super);
  19669. function SetParentAction(triggerOptions, target, parent, condition) {
  19670. _super.call(this, triggerOptions, condition);
  19671. this._target = target;
  19672. this._parent = parent;
  19673. }
  19674. SetParentAction.prototype._prepare = function () {
  19675. };
  19676. SetParentAction.prototype.execute = function () {
  19677. if (this._target.parent === this._parent) {
  19678. return;
  19679. }
  19680. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19681. invertParentWorldMatrix.invert();
  19682. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19683. this._target.parent = this._parent;
  19684. };
  19685. return SetParentAction;
  19686. })(BABYLON.Action);
  19687. BABYLON.SetParentAction = SetParentAction;
  19688. })(BABYLON || (BABYLON = {}));
  19689. var __extends = this.__extends || function (d, b) {
  19690. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19691. function __() { this.constructor = d; }
  19692. __.prototype = b.prototype;
  19693. d.prototype = new __();
  19694. };
  19695. var BABYLON;
  19696. (function (BABYLON) {
  19697. var Geometry = (function () {
  19698. function Geometry(id, scene, vertexData, updatable, mesh) {
  19699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19700. this._totalVertices = 0;
  19701. this._indices = [];
  19702. this.id = id;
  19703. this._engine = scene.getEngine();
  19704. this._meshes = [];
  19705. this._scene = scene;
  19706. if (vertexData) {
  19707. this.setAllVerticesData(vertexData, updatable);
  19708. } else {
  19709. this._totalVertices = 0;
  19710. this._indices = [];
  19711. }
  19712. if (mesh) {
  19713. this.applyToMesh(mesh);
  19714. }
  19715. }
  19716. Geometry.prototype.getScene = function () {
  19717. return this._scene;
  19718. };
  19719. Geometry.prototype.getEngine = function () {
  19720. return this._engine;
  19721. };
  19722. Geometry.prototype.isReady = function () {
  19723. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19724. };
  19725. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19726. vertexData.applyToGeometry(this, updatable);
  19727. };
  19728. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19729. this._vertexBuffers = this._vertexBuffers || {};
  19730. if (this._vertexBuffers[kind]) {
  19731. this._vertexBuffers[kind].dispose();
  19732. }
  19733. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19734. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19735. var stride = this._vertexBuffers[kind].getStrideSize();
  19736. this._totalVertices = data.length / stride;
  19737. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19738. var meshes = this._meshes;
  19739. var numOfMeshes = meshes.length;
  19740. for (var index = 0; index < numOfMeshes; index++) {
  19741. var mesh = meshes[index];
  19742. mesh._resetPointsArrayCache();
  19743. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19744. mesh._createGlobalSubMesh();
  19745. mesh.computeWorldMatrix(true);
  19746. }
  19747. }
  19748. };
  19749. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19750. var vertexBuffer = this.getVertexBuffer(kind);
  19751. if (!vertexBuffer) {
  19752. return;
  19753. }
  19754. vertexBuffer.updateDirectly(data);
  19755. };
  19756. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19757. var vertexBuffer = this.getVertexBuffer(kind);
  19758. if (!vertexBuffer) {
  19759. return;
  19760. }
  19761. vertexBuffer.update(data);
  19762. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19763. var extend;
  19764. if (updateExtends) {
  19765. var stride = vertexBuffer.getStrideSize();
  19766. this._totalVertices = data.length / stride;
  19767. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19768. }
  19769. var meshes = this._meshes;
  19770. var numOfMeshes = meshes.length;
  19771. for (var index = 0; index < numOfMeshes; index++) {
  19772. var mesh = meshes[index];
  19773. mesh._resetPointsArrayCache();
  19774. if (updateExtends) {
  19775. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19776. }
  19777. }
  19778. }
  19779. };
  19780. Geometry.prototype.getTotalVertices = function () {
  19781. if (!this.isReady()) {
  19782. return 0;
  19783. }
  19784. return this._totalVertices;
  19785. };
  19786. Geometry.prototype.getVerticesData = function (kind) {
  19787. var vertexBuffer = this.getVertexBuffer(kind);
  19788. if (!vertexBuffer) {
  19789. return null;
  19790. }
  19791. return vertexBuffer.getData();
  19792. };
  19793. Geometry.prototype.getVertexBuffer = function (kind) {
  19794. if (!this.isReady()) {
  19795. return null;
  19796. }
  19797. return this._vertexBuffers[kind];
  19798. };
  19799. Geometry.prototype.getVertexBuffers = function () {
  19800. if (!this.isReady()) {
  19801. return null;
  19802. }
  19803. return this._vertexBuffers;
  19804. };
  19805. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19806. if (!this._vertexBuffers) {
  19807. if (this._delayInfo) {
  19808. return this._delayInfo.indexOf(kind) !== -1;
  19809. }
  19810. return false;
  19811. }
  19812. return this._vertexBuffers[kind] !== undefined;
  19813. };
  19814. Geometry.prototype.getVerticesDataKinds = function () {
  19815. var result = [];
  19816. if (!this._vertexBuffers && this._delayInfo) {
  19817. for (var kind in this._delayInfo) {
  19818. result.push(kind);
  19819. }
  19820. } else {
  19821. for (kind in this._vertexBuffers) {
  19822. result.push(kind);
  19823. }
  19824. }
  19825. return result;
  19826. };
  19827. Geometry.prototype.setIndices = function (indices) {
  19828. if (this._indexBuffer) {
  19829. this._engine._releaseBuffer(this._indexBuffer);
  19830. }
  19831. this._indices = indices;
  19832. if (this._meshes.length !== 0 && this._indices) {
  19833. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19834. }
  19835. var meshes = this._meshes;
  19836. var numOfMeshes = meshes.length;
  19837. for (var index = 0; index < numOfMeshes; index++) {
  19838. meshes[index]._createGlobalSubMesh();
  19839. }
  19840. };
  19841. Geometry.prototype.getTotalIndices = function () {
  19842. if (!this.isReady()) {
  19843. return 0;
  19844. }
  19845. return this._indices.length;
  19846. };
  19847. Geometry.prototype.getIndices = function () {
  19848. if (!this.isReady()) {
  19849. return null;
  19850. }
  19851. return this._indices;
  19852. };
  19853. Geometry.prototype.getIndexBuffer = function () {
  19854. if (!this.isReady()) {
  19855. return null;
  19856. }
  19857. return this._indexBuffer;
  19858. };
  19859. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19860. var meshes = this._meshes;
  19861. var index = meshes.indexOf(mesh);
  19862. if (index === -1) {
  19863. return;
  19864. }
  19865. for (var kind in this._vertexBuffers) {
  19866. this._vertexBuffers[kind].dispose();
  19867. }
  19868. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19869. this._indexBuffer = null;
  19870. }
  19871. meshes.splice(index, 1);
  19872. mesh._geometry = null;
  19873. if (meshes.length == 0 && shouldDispose) {
  19874. this.dispose();
  19875. }
  19876. };
  19877. Geometry.prototype.applyToMesh = function (mesh) {
  19878. if (mesh._geometry === this) {
  19879. return;
  19880. }
  19881. var previousGeometry = mesh._geometry;
  19882. if (previousGeometry) {
  19883. previousGeometry.releaseForMesh(mesh);
  19884. }
  19885. var meshes = this._meshes;
  19886. mesh._geometry = this;
  19887. this._scene.pushGeometry(this);
  19888. meshes.push(mesh);
  19889. if (this.isReady()) {
  19890. this._applyToMesh(mesh);
  19891. } else {
  19892. mesh._boundingInfo = this._boundingInfo;
  19893. }
  19894. };
  19895. Geometry.prototype._applyToMesh = function (mesh) {
  19896. var numOfMeshes = this._meshes.length;
  19897. for (var kind in this._vertexBuffers) {
  19898. if (numOfMeshes === 1) {
  19899. this._vertexBuffers[kind].create();
  19900. }
  19901. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19902. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19903. mesh._resetPointsArrayCache();
  19904. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19905. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19906. mesh._createGlobalSubMesh();
  19907. }
  19908. }
  19909. if (numOfMeshes === 1 && this._indices) {
  19910. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19911. }
  19912. if (this._indexBuffer) {
  19913. this._indexBuffer.references = numOfMeshes;
  19914. }
  19915. };
  19916. Geometry.prototype.load = function (scene, onLoaded) {
  19917. var _this = this;
  19918. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19919. return;
  19920. }
  19921. if (this.isReady()) {
  19922. if (onLoaded) {
  19923. onLoaded();
  19924. }
  19925. return;
  19926. }
  19927. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19928. scene._addPendingData(this);
  19929. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19930. _this._delayLoadingFunction(JSON.parse(data), _this);
  19931. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19932. _this._delayInfo = [];
  19933. scene._removePendingData(_this);
  19934. var meshes = _this._meshes;
  19935. var numOfMeshes = meshes.length;
  19936. for (var index = 0; index < numOfMeshes; index++) {
  19937. _this._applyToMesh(meshes[index]);
  19938. }
  19939. if (onLoaded) {
  19940. onLoaded();
  19941. }
  19942. }, function () {
  19943. }, scene.database);
  19944. };
  19945. Geometry.prototype.dispose = function () {
  19946. var meshes = this._meshes;
  19947. var numOfMeshes = meshes.length;
  19948. for (var index = 0; index < numOfMeshes; index++) {
  19949. this.releaseForMesh(meshes[index]);
  19950. }
  19951. this._meshes = [];
  19952. for (var kind in this._vertexBuffers) {
  19953. this._vertexBuffers[kind].dispose();
  19954. }
  19955. this._vertexBuffers = [];
  19956. this._totalVertices = 0;
  19957. if (this._indexBuffer) {
  19958. this._engine._releaseBuffer(this._indexBuffer);
  19959. }
  19960. this._indexBuffer = null;
  19961. this._indices = [];
  19962. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19963. this.delayLoadingFile = null;
  19964. this._delayLoadingFunction = null;
  19965. this._delayInfo = [];
  19966. this._boundingInfo = null;
  19967. var geometries = this._scene.getGeometries();
  19968. index = geometries.indexOf(this);
  19969. if (index > -1) {
  19970. geometries.splice(index, 1);
  19971. }
  19972. };
  19973. Geometry.prototype.copy = function (id) {
  19974. var vertexData = new BABYLON.VertexData();
  19975. vertexData.indices = [];
  19976. var indices = this.getIndices();
  19977. for (var index = 0; index < indices.length; index++) {
  19978. vertexData.indices.push(indices[index]);
  19979. }
  19980. var updatable = false;
  19981. var stopChecking = false;
  19982. for (var kind in this._vertexBuffers) {
  19983. vertexData.set(this.getVerticesData(kind), kind);
  19984. if (!stopChecking) {
  19985. updatable = this.getVertexBuffer(kind).isUpdatable();
  19986. stopChecking = !updatable;
  19987. }
  19988. }
  19989. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19990. geometry.delayLoadState = this.delayLoadState;
  19991. geometry.delayLoadingFile = this.delayLoadingFile;
  19992. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19993. for (kind in this._delayInfo) {
  19994. geometry._delayInfo = geometry._delayInfo || [];
  19995. geometry._delayInfo.push(kind);
  19996. }
  19997. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19998. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19999. return geometry;
  20000. };
  20001. Geometry.ExtractFromMesh = function (mesh, id) {
  20002. var geometry = mesh._geometry;
  20003. if (!geometry) {
  20004. return null;
  20005. }
  20006. return geometry.copy(id);
  20007. };
  20008. Geometry.RandomId = function () {
  20009. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20010. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20011. return v.toString(16);
  20012. });
  20013. };
  20014. return Geometry;
  20015. })();
  20016. BABYLON.Geometry = Geometry;
  20017. (function (Geometry) {
  20018. (function (Primitives) {
  20019. var _Primitive = (function (_super) {
  20020. __extends(_Primitive, _super);
  20021. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20022. this._beingRegenerated = true;
  20023. this._canBeRegenerated = canBeRegenerated;
  20024. _super.call(this, id, scene, vertexData, false, mesh);
  20025. this._beingRegenerated = false;
  20026. }
  20027. _Primitive.prototype.canBeRegenerated = function () {
  20028. return this._canBeRegenerated;
  20029. };
  20030. _Primitive.prototype.regenerate = function () {
  20031. if (!this._canBeRegenerated) {
  20032. return;
  20033. }
  20034. this._beingRegenerated = true;
  20035. this.setAllVerticesData(this._regenerateVertexData(), false);
  20036. this._beingRegenerated = false;
  20037. };
  20038. _Primitive.prototype.asNewGeometry = function (id) {
  20039. return _super.prototype.copy.call(this, id);
  20040. };
  20041. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20042. if (!this._beingRegenerated) {
  20043. return;
  20044. }
  20045. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20046. };
  20047. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20048. if (!this._beingRegenerated) {
  20049. return;
  20050. }
  20051. _super.prototype.setVerticesData.call(this, kind, data, false);
  20052. };
  20053. _Primitive.prototype._regenerateVertexData = function () {
  20054. throw new Error("Abstract method");
  20055. };
  20056. _Primitive.prototype.copy = function (id) {
  20057. throw new Error("Must be overriden in sub-classes.");
  20058. };
  20059. return _Primitive;
  20060. })(Geometry);
  20061. Primitives._Primitive = _Primitive;
  20062. var Box = (function (_super) {
  20063. __extends(Box, _super);
  20064. function Box(id, scene, size, canBeRegenerated, mesh) {
  20065. this.size = size;
  20066. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20067. }
  20068. Box.prototype._regenerateVertexData = function () {
  20069. return BABYLON.VertexData.CreateBox(this.size);
  20070. };
  20071. Box.prototype.copy = function (id) {
  20072. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20073. };
  20074. return Box;
  20075. })(_Primitive);
  20076. Primitives.Box = Box;
  20077. var Sphere = (function (_super) {
  20078. __extends(Sphere, _super);
  20079. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20080. this.segments = segments;
  20081. this.diameter = diameter;
  20082. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20083. }
  20084. Sphere.prototype._regenerateVertexData = function () {
  20085. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20086. };
  20087. Sphere.prototype.copy = function (id) {
  20088. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20089. };
  20090. return Sphere;
  20091. })(_Primitive);
  20092. Primitives.Sphere = Sphere;
  20093. var Cylinder = (function (_super) {
  20094. __extends(Cylinder, _super);
  20095. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20096. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20097. this.height = height;
  20098. this.diameterTop = diameterTop;
  20099. this.diameterBottom = diameterBottom;
  20100. this.tessellation = tessellation;
  20101. this.subdivisions = subdivisions;
  20102. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20103. }
  20104. Cylinder.prototype._regenerateVertexData = function () {
  20105. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20106. };
  20107. Cylinder.prototype.copy = function (id) {
  20108. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20109. };
  20110. return Cylinder;
  20111. })(_Primitive);
  20112. Primitives.Cylinder = Cylinder;
  20113. var Torus = (function (_super) {
  20114. __extends(Torus, _super);
  20115. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20116. this.diameter = diameter;
  20117. this.thickness = thickness;
  20118. this.tessellation = tessellation;
  20119. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20120. }
  20121. Torus.prototype._regenerateVertexData = function () {
  20122. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20123. };
  20124. Torus.prototype.copy = function (id) {
  20125. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20126. };
  20127. return Torus;
  20128. })(_Primitive);
  20129. Primitives.Torus = Torus;
  20130. var Ground = (function (_super) {
  20131. __extends(Ground, _super);
  20132. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20133. this.width = width;
  20134. this.height = height;
  20135. this.subdivisions = subdivisions;
  20136. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20137. }
  20138. Ground.prototype._regenerateVertexData = function () {
  20139. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20140. };
  20141. Ground.prototype.copy = function (id) {
  20142. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20143. };
  20144. return Ground;
  20145. })(_Primitive);
  20146. Primitives.Ground = Ground;
  20147. var TiledGround = (function (_super) {
  20148. __extends(TiledGround, _super);
  20149. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20150. this.xmin = xmin;
  20151. this.zmin = zmin;
  20152. this.xmax = xmax;
  20153. this.zmax = zmax;
  20154. this.subdivisions = subdivisions;
  20155. this.precision = precision;
  20156. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20157. }
  20158. TiledGround.prototype._regenerateVertexData = function () {
  20159. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20160. };
  20161. TiledGround.prototype.copy = function (id) {
  20162. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20163. };
  20164. return TiledGround;
  20165. })(_Primitive);
  20166. Primitives.TiledGround = TiledGround;
  20167. var Plane = (function (_super) {
  20168. __extends(Plane, _super);
  20169. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20170. this.size = size;
  20171. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20172. }
  20173. Plane.prototype._regenerateVertexData = function () {
  20174. return BABYLON.VertexData.CreatePlane(this.size);
  20175. };
  20176. Plane.prototype.copy = function (id) {
  20177. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20178. };
  20179. return Plane;
  20180. })(_Primitive);
  20181. Primitives.Plane = Plane;
  20182. var TorusKnot = (function (_super) {
  20183. __extends(TorusKnot, _super);
  20184. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20185. this.radius = radius;
  20186. this.tube = tube;
  20187. this.radialSegments = radialSegments;
  20188. this.tubularSegments = tubularSegments;
  20189. this.p = p;
  20190. this.q = q;
  20191. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20192. }
  20193. TorusKnot.prototype._regenerateVertexData = function () {
  20194. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20195. };
  20196. TorusKnot.prototype.copy = function (id) {
  20197. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20198. };
  20199. return TorusKnot;
  20200. })(_Primitive);
  20201. Primitives.TorusKnot = TorusKnot;
  20202. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20203. var Primitives = Geometry.Primitives;
  20204. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20205. var Geometry = BABYLON.Geometry;
  20206. })(BABYLON || (BABYLON = {}));
  20207. var __extends = this.__extends || function (d, b) {
  20208. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20209. function __() { this.constructor = d; }
  20210. __.prototype = b.prototype;
  20211. d.prototype = new __();
  20212. };
  20213. var BABYLON;
  20214. (function (BABYLON) {
  20215. var Gamepads = (function () {
  20216. function Gamepads(ongamedpadconnected) {
  20217. var _this = this;
  20218. this.babylonGamepads = [];
  20219. this.oneGamepadConnected = false;
  20220. this.isMonitoring = false;
  20221. this.gamepadEventSupported = 'GamepadEvent' in window;
  20222. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20223. 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=";
  20224. this._callbackGamepadConnected = ongamedpadconnected;
  20225. if (this.gamepadSupportAvailable) {
  20226. if (this.gamepadEventSupported) {
  20227. window.addEventListener('gamepadconnected', function (evt) {
  20228. _this._onGamepadConnected(evt);
  20229. }, false);
  20230. window.addEventListener('gamepaddisconnected', function (evt) {
  20231. _this._onGamepadDisconnected(evt);
  20232. }, false);
  20233. } else {
  20234. this._startMonitoringGamepads();
  20235. }
  20236. if (!this.oneGamepadConnected) {
  20237. this._insertGamepadDOMInstructions();
  20238. }
  20239. } else {
  20240. this._insertGamepadDOMNotSupported();
  20241. }
  20242. }
  20243. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20244. Gamepads.gamepadDOMInfo = document.createElement("div");
  20245. var buttonAImage = document.createElement("img");
  20246. buttonAImage.src = this.buttonADataURL;
  20247. var spanMessage = document.createElement("span");
  20248. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20249. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20250. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20251. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20252. Gamepads.gamepadDOMInfo.style.width = "100%";
  20253. Gamepads.gamepadDOMInfo.style.height = "48px";
  20254. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20255. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20256. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20257. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20258. buttonAImage.style.position = "relative";
  20259. buttonAImage.style.bottom = "8px";
  20260. spanMessage.style.position = "relative";
  20261. spanMessage.style.fontSize = "32px";
  20262. spanMessage.style.bottom = "32px";
  20263. spanMessage.style.color = "green";
  20264. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20265. };
  20266. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20267. Gamepads.gamepadDOMInfo = document.createElement("div");
  20268. var spanMessage = document.createElement("span");
  20269. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20270. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20271. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20272. Gamepads.gamepadDOMInfo.style.width = "100%";
  20273. Gamepads.gamepadDOMInfo.style.height = "40px";
  20274. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20275. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20276. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20277. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20278. spanMessage.style.position = "relative";
  20279. spanMessage.style.fontSize = "32px";
  20280. spanMessage.style.color = "red";
  20281. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20282. };
  20283. Gamepads.prototype.dispose = function () {
  20284. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20285. };
  20286. Gamepads.prototype._onGamepadConnected = function (evt) {
  20287. var newGamepad = this._addNewGamepad(evt.gamepad);
  20288. if (this._callbackGamepadConnected)
  20289. this._callbackGamepadConnected(newGamepad);
  20290. this._startMonitoringGamepads();
  20291. };
  20292. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20293. if (!this.oneGamepadConnected) {
  20294. this.oneGamepadConnected = true;
  20295. if (Gamepads.gamepadDOMInfo) {
  20296. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20297. Gamepads.gamepadDOMInfo = null;
  20298. }
  20299. }
  20300. var newGamepad;
  20301. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20302. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20303. } else {
  20304. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20305. }
  20306. this.babylonGamepads.push(newGamepad);
  20307. return newGamepad;
  20308. };
  20309. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20310. for (var i in this.babylonGamepads) {
  20311. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20312. this.babylonGamepads.splice(i, 1);
  20313. break;
  20314. }
  20315. }
  20316. if (this.babylonGamepads.length == 0) {
  20317. this._stopMonitoringGamepads();
  20318. }
  20319. };
  20320. Gamepads.prototype._startMonitoringGamepads = function () {
  20321. if (!this.isMonitoring) {
  20322. this.isMonitoring = true;
  20323. this._checkGamepadsStatus();
  20324. }
  20325. };
  20326. Gamepads.prototype._stopMonitoringGamepads = function () {
  20327. this.isMonitoring = false;
  20328. };
  20329. Gamepads.prototype._checkGamepadsStatus = function () {
  20330. var _this = this;
  20331. this._updateGamepadObjects();
  20332. for (var i in this.babylonGamepads) {
  20333. this.babylonGamepads[i].update();
  20334. }
  20335. if (this.isMonitoring) {
  20336. if (window.requestAnimationFrame) {
  20337. window.requestAnimationFrame(function () {
  20338. _this._checkGamepadsStatus();
  20339. });
  20340. } else if (window.mozRequestAnimationFrame) {
  20341. window.mozRequestAnimationFrame(function () {
  20342. _this._checkGamepadsStatus();
  20343. });
  20344. } else if (window.webkitRequestAnimationFrame) {
  20345. window.webkitRequestAnimationFrame(function () {
  20346. _this._checkGamepadsStatus();
  20347. });
  20348. }
  20349. }
  20350. };
  20351. Gamepads.prototype._updateGamepadObjects = function () {
  20352. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20353. for (var i = 0; i < gamepads.length; i++) {
  20354. if (gamepads[i]) {
  20355. if (!(gamepads[i].index in this.babylonGamepads)) {
  20356. var newGamepad = this._addNewGamepad(gamepads[i]);
  20357. if (this._callbackGamepadConnected) {
  20358. this._callbackGamepadConnected(newGamepad);
  20359. }
  20360. } else {
  20361. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20362. }
  20363. }
  20364. }
  20365. };
  20366. return Gamepads;
  20367. })();
  20368. BABYLON.Gamepads = Gamepads;
  20369. var StickValues = (function () {
  20370. function StickValues(x, y) {
  20371. this.x = x;
  20372. this.y = y;
  20373. }
  20374. return StickValues;
  20375. })();
  20376. BABYLON.StickValues = StickValues;
  20377. var Gamepad = (function () {
  20378. function Gamepad(id, index, browserGamepad) {
  20379. this.id = id;
  20380. this.index = index;
  20381. this.browserGamepad = browserGamepad;
  20382. if (this.browserGamepad.axes.length >= 2) {
  20383. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20384. }
  20385. if (this.browserGamepad.axes.length >= 4) {
  20386. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20387. }
  20388. }
  20389. Gamepad.prototype.onleftstickchanged = function (callback) {
  20390. this._onleftstickchanged = callback;
  20391. };
  20392. Gamepad.prototype.onrightstickchanged = function (callback) {
  20393. this._onrightstickchanged = callback;
  20394. };
  20395. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20396. get: function () {
  20397. return this._leftStick;
  20398. },
  20399. set: function (newValues) {
  20400. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20401. this._onleftstickchanged(newValues);
  20402. }
  20403. this._leftStick = newValues;
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20409. get: function () {
  20410. return this._rightStick;
  20411. },
  20412. set: function (newValues) {
  20413. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20414. this._onrightstickchanged(newValues);
  20415. }
  20416. this._rightStick = newValues;
  20417. },
  20418. enumerable: true,
  20419. configurable: true
  20420. });
  20421. Gamepad.prototype.update = function () {
  20422. if (this._leftStick) {
  20423. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20424. }
  20425. if (this._rightStick) {
  20426. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20427. }
  20428. };
  20429. return Gamepad;
  20430. })();
  20431. BABYLON.Gamepad = Gamepad;
  20432. var GenericPad = (function (_super) {
  20433. __extends(GenericPad, _super);
  20434. function GenericPad(id, index, gamepad) {
  20435. _super.call(this, id, index, gamepad);
  20436. this.id = id;
  20437. this.index = index;
  20438. this.gamepad = gamepad;
  20439. this._buttons = new Array(gamepad.buttons.length);
  20440. }
  20441. GenericPad.prototype.onbuttondown = function (callback) {
  20442. this._onbuttondown = callback;
  20443. };
  20444. GenericPad.prototype.onbuttonup = function (callback) {
  20445. this._onbuttonup = callback;
  20446. };
  20447. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20448. if (newValue !== currentValue) {
  20449. if (this._onbuttondown && newValue === 1) {
  20450. this._onbuttondown(buttonIndex);
  20451. }
  20452. if (this._onbuttonup && newValue === 0) {
  20453. this._onbuttonup(buttonIndex);
  20454. }
  20455. }
  20456. return newValue;
  20457. };
  20458. GenericPad.prototype.update = function () {
  20459. _super.prototype.update.call(this);
  20460. for (var index = 0; index < this._buttons.length; index++) {
  20461. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20462. }
  20463. };
  20464. return GenericPad;
  20465. })(Gamepad);
  20466. BABYLON.GenericPad = GenericPad;
  20467. (function (Xbox360Button) {
  20468. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20469. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20470. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20471. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20472. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20473. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20474. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20475. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20476. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20477. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20478. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20479. var Xbox360Button = BABYLON.Xbox360Button;
  20480. (function (Xbox360Dpad) {
  20481. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20482. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20483. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20484. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20485. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20486. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20487. var Xbox360Pad = (function (_super) {
  20488. __extends(Xbox360Pad, _super);
  20489. function Xbox360Pad() {
  20490. _super.apply(this, arguments);
  20491. this._leftTrigger = 0;
  20492. this._rightTrigger = 0;
  20493. this._buttonA = 0;
  20494. this._buttonB = 0;
  20495. this._buttonX = 0;
  20496. this._buttonY = 0;
  20497. this._buttonBack = 0;
  20498. this._buttonStart = 0;
  20499. this._buttonLB = 0;
  20500. this._buttonRB = 0;
  20501. this._buttonLeftStick = 0;
  20502. this._buttonRightStick = 0;
  20503. this._dPadUp = 0;
  20504. this._dPadDown = 0;
  20505. this._dPadLeft = 0;
  20506. this._dPadRight = 0;
  20507. }
  20508. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20509. this._onlefttriggerchanged = callback;
  20510. };
  20511. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20512. this._onrighttriggerchanged = callback;
  20513. };
  20514. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20515. get: function () {
  20516. return this._leftTrigger;
  20517. },
  20518. set: function (newValue) {
  20519. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20520. this._onlefttriggerchanged(newValue);
  20521. }
  20522. this._leftTrigger = newValue;
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20528. get: function () {
  20529. return this._rightTrigger;
  20530. },
  20531. set: function (newValue) {
  20532. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20533. this._onrighttriggerchanged(newValue);
  20534. }
  20535. this._rightTrigger = newValue;
  20536. },
  20537. enumerable: true,
  20538. configurable: true
  20539. });
  20540. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20541. this._onbuttondown = callback;
  20542. };
  20543. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20544. this._onbuttonup = callback;
  20545. };
  20546. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20547. this._ondpaddown = callback;
  20548. };
  20549. Xbox360Pad.prototype.ondpadup = function (callback) {
  20550. this._ondpadup = callback;
  20551. };
  20552. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20553. if (newValue !== currentValue) {
  20554. if (this._onbuttondown && newValue === 1) {
  20555. this._onbuttondown(buttonType);
  20556. }
  20557. if (this._onbuttonup && newValue === 0) {
  20558. this._onbuttonup(buttonType);
  20559. }
  20560. }
  20561. return newValue;
  20562. };
  20563. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20564. if (newValue !== currentValue) {
  20565. if (this._ondpaddown && newValue === 1) {
  20566. this._ondpaddown(buttonType);
  20567. }
  20568. if (this._ondpadup && newValue === 0) {
  20569. this._ondpadup(buttonType);
  20570. }
  20571. }
  20572. return newValue;
  20573. };
  20574. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20575. get: function () {
  20576. return this._buttonA;
  20577. },
  20578. set: function (value) {
  20579. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20580. },
  20581. enumerable: true,
  20582. configurable: true
  20583. });
  20584. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20585. get: function () {
  20586. return this._buttonB;
  20587. },
  20588. set: function (value) {
  20589. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20595. get: function () {
  20596. return this._buttonX;
  20597. },
  20598. set: function (value) {
  20599. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20600. },
  20601. enumerable: true,
  20602. configurable: true
  20603. });
  20604. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20605. get: function () {
  20606. return this._buttonY;
  20607. },
  20608. set: function (value) {
  20609. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20610. },
  20611. enumerable: true,
  20612. configurable: true
  20613. });
  20614. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20615. get: function () {
  20616. return this._buttonStart;
  20617. },
  20618. set: function (value) {
  20619. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20620. },
  20621. enumerable: true,
  20622. configurable: true
  20623. });
  20624. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20625. get: function () {
  20626. return this._buttonBack;
  20627. },
  20628. set: function (value) {
  20629. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20635. get: function () {
  20636. return this._buttonLB;
  20637. },
  20638. set: function (value) {
  20639. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20645. get: function () {
  20646. return this._buttonRB;
  20647. },
  20648. set: function (value) {
  20649. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20650. },
  20651. enumerable: true,
  20652. configurable: true
  20653. });
  20654. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20655. get: function () {
  20656. return this._buttonLeftStick;
  20657. },
  20658. set: function (value) {
  20659. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20665. get: function () {
  20666. return this._buttonRightStick;
  20667. },
  20668. set: function (value) {
  20669. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20675. get: function () {
  20676. return this._dPadUp;
  20677. },
  20678. set: function (value) {
  20679. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20685. get: function () {
  20686. return this._dPadDown;
  20687. },
  20688. set: function (value) {
  20689. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20695. get: function () {
  20696. return this._dPadLeft;
  20697. },
  20698. set: function (value) {
  20699. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20705. get: function () {
  20706. return this._dPadRight;
  20707. },
  20708. set: function (value) {
  20709. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20710. },
  20711. enumerable: true,
  20712. configurable: true
  20713. });
  20714. Xbox360Pad.prototype.update = function () {
  20715. _super.prototype.update.call(this);
  20716. this.buttonA = this.browserGamepad.buttons[0].value;
  20717. this.buttonB = this.browserGamepad.buttons[1].value;
  20718. this.buttonX = this.browserGamepad.buttons[2].value;
  20719. this.buttonY = this.browserGamepad.buttons[3].value;
  20720. this.buttonLB = this.browserGamepad.buttons[4].value;
  20721. this.buttonRB = this.browserGamepad.buttons[5].value;
  20722. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20723. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20724. this.buttonBack = this.browserGamepad.buttons[8].value;
  20725. this.buttonStart = this.browserGamepad.buttons[9].value;
  20726. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20727. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20728. this.dPadUp = this.browserGamepad.buttons[12].value;
  20729. this.dPadDown = this.browserGamepad.buttons[13].value;
  20730. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20731. this.dPadRight = this.browserGamepad.buttons[15].value;
  20732. };
  20733. return Xbox360Pad;
  20734. })(Gamepad);
  20735. BABYLON.Xbox360Pad = Xbox360Pad;
  20736. })(BABYLON || (BABYLON = {}));
  20737. var __extends = this.__extends || function (d, b) {
  20738. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20739. function __() { this.constructor = d; }
  20740. __.prototype = b.prototype;
  20741. d.prototype = new __();
  20742. };
  20743. var BABYLON;
  20744. (function (BABYLON) {
  20745. var GamepadCamera = (function (_super) {
  20746. __extends(GamepadCamera, _super);
  20747. function GamepadCamera(name, position, scene) {
  20748. var _this = this;
  20749. _super.call(this, name, position, scene);
  20750. this.angularSensibility = 200;
  20751. this.moveSensibility = 75;
  20752. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20753. _this._onNewGameConnected(gamepad);
  20754. });
  20755. }
  20756. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20757. if (gamepad.index === 0) {
  20758. this._gamepad = gamepad;
  20759. }
  20760. };
  20761. GamepadCamera.prototype._checkInputs = function () {
  20762. if (!this._gamepad) {
  20763. return;
  20764. }
  20765. var LSValues = this._gamepad.leftStick;
  20766. var normalizedLX = LSValues.x / this.moveSensibility;
  20767. var normalizedLY = LSValues.y / this.moveSensibility;
  20768. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20769. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20770. var RSValues = this._gamepad.rightStick;
  20771. var normalizedRX = RSValues.x / this.angularSensibility;
  20772. var normalizedRY = RSValues.y / this.angularSensibility;
  20773. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20774. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20775. ;
  20776. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20777. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20778. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20779. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20780. };
  20781. GamepadCamera.prototype.dispose = function () {
  20782. this._gamepads.dispose();
  20783. _super.prototype.dispose.call(this);
  20784. };
  20785. return GamepadCamera;
  20786. })(BABYLON.FreeCamera);
  20787. BABYLON.GamepadCamera = GamepadCamera;
  20788. })(BABYLON || (BABYLON = {}));
  20789. var __extends = this.__extends || function (d, b) {
  20790. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20791. function __() { this.constructor = d; }
  20792. __.prototype = b.prototype;
  20793. d.prototype = new __();
  20794. };
  20795. var BABYLON;
  20796. (function (BABYLON) {
  20797. var LinesMesh = (function (_super) {
  20798. __extends(LinesMesh, _super);
  20799. function LinesMesh(name, scene, updatable) {
  20800. if (typeof updatable === "undefined") { updatable = false; }
  20801. _super.call(this, name, scene);
  20802. this.color = new BABYLON.Color3(1, 1, 1);
  20803. this.alpha = 1;
  20804. this._indices = new Array();
  20805. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20806. attributes: ["position"],
  20807. uniforms: ["worldViewProjection", "color"],
  20808. needAlphaBlending: true
  20809. });
  20810. }
  20811. Object.defineProperty(LinesMesh.prototype, "material", {
  20812. get: function () {
  20813. return this._colorShader;
  20814. },
  20815. enumerable: true,
  20816. configurable: true
  20817. });
  20818. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20819. get: function () {
  20820. return false;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20826. get: function () {
  20827. return false;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20833. var engine = this.getScene().getEngine();
  20834. var indexToBind = this._geometry.getIndexBuffer();
  20835. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20836. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20837. };
  20838. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20839. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20840. return;
  20841. }
  20842. var engine = this.getScene().getEngine();
  20843. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20844. };
  20845. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20846. return null;
  20847. };
  20848. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20849. this._colorShader.dispose();
  20850. _super.prototype.dispose.call(this, doNotRecurse);
  20851. };
  20852. return LinesMesh;
  20853. })(BABYLON.Mesh);
  20854. BABYLON.LinesMesh = LinesMesh;
  20855. })(BABYLON || (BABYLON = {}));
  20856. var BABYLON;
  20857. (function (BABYLON) {
  20858. var OutlineRenderer = (function () {
  20859. function OutlineRenderer(scene) {
  20860. this._scene = scene;
  20861. }
  20862. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20863. var scene = this._scene;
  20864. var engine = this._scene.getEngine();
  20865. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20866. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20867. return;
  20868. }
  20869. var mesh = subMesh.getRenderingMesh();
  20870. var material = subMesh.getMaterial();
  20871. engine.enableEffect(this._effect);
  20872. this._effect.setFloat("offset", mesh.outlineWidth);
  20873. this._effect.setColor3("color", mesh.outlineColor);
  20874. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20875. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20876. if (useBones) {
  20877. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20878. }
  20879. mesh._bind(subMesh, this._effect, false);
  20880. if (material && material.needAlphaTesting()) {
  20881. var alphaTexture = material.getAlphaTestTexture();
  20882. this._effect.setTexture("diffuseSampler", alphaTexture);
  20883. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20884. }
  20885. if (hardwareInstancedRendering) {
  20886. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20887. } else {
  20888. if (batch.renderSelf[subMesh._id]) {
  20889. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20890. mesh._draw(subMesh, true);
  20891. }
  20892. if (batch.visibleInstances[subMesh._id]) {
  20893. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20894. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20895. this._effect.setMatrix("world", instance.getWorldMatrix());
  20896. mesh._draw(subMesh, true);
  20897. }
  20898. }
  20899. }
  20900. };
  20901. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20902. var defines = [];
  20903. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20904. var mesh = subMesh.getMesh();
  20905. var material = subMesh.getMaterial();
  20906. if (material && material.needAlphaTesting()) {
  20907. defines.push("#define ALPHATEST");
  20908. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20909. attribs.push(BABYLON.VertexBuffer.UVKind);
  20910. defines.push("#define UV1");
  20911. }
  20912. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20913. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20914. defines.push("#define UV2");
  20915. }
  20916. }
  20917. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20918. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20919. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20920. defines.push("#define BONES");
  20921. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20922. }
  20923. if (useInstances) {
  20924. defines.push("#define INSTANCES");
  20925. attribs.push("world0");
  20926. attribs.push("world1");
  20927. attribs.push("world2");
  20928. attribs.push("world3");
  20929. }
  20930. var join = defines.join("\n");
  20931. if (this._cachedDefines != join) {
  20932. this._cachedDefines = join;
  20933. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20934. }
  20935. return this._effect.isReady();
  20936. };
  20937. return OutlineRenderer;
  20938. })();
  20939. BABYLON.OutlineRenderer = OutlineRenderer;
  20940. })(BABYLON || (BABYLON = {}));
  20941. var BABYLON;
  20942. (function (BABYLON) {
  20943. var MeshAssetTask = (function () {
  20944. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20945. this.name = name;
  20946. this.meshesNames = meshesNames;
  20947. this.rootUrl = rootUrl;
  20948. this.sceneFilename = sceneFilename;
  20949. this.isCompleted = false;
  20950. }
  20951. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20952. var _this = this;
  20953. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20954. _this.loadedMeshes = meshes;
  20955. _this.loadedParticleSystems = particleSystems;
  20956. _this.loadedSkeletons = skeletons;
  20957. _this.isCompleted = true;
  20958. if (_this.onSuccess) {
  20959. _this.onSuccess(_this);
  20960. }
  20961. onSuccess();
  20962. }, null, function () {
  20963. if (_this.onError) {
  20964. _this.onError(_this);
  20965. }
  20966. onError();
  20967. });
  20968. };
  20969. return MeshAssetTask;
  20970. })();
  20971. BABYLON.MeshAssetTask = MeshAssetTask;
  20972. var TextFileAssetTask = (function () {
  20973. function TextFileAssetTask(name, url) {
  20974. this.name = name;
  20975. this.url = url;
  20976. this.isCompleted = false;
  20977. }
  20978. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20979. var _this = this;
  20980. BABYLON.Tools.LoadFile(this.url, function (data) {
  20981. _this.text = data;
  20982. _this.isCompleted = true;
  20983. if (_this.onSuccess) {
  20984. _this.onSuccess(_this);
  20985. }
  20986. onSuccess();
  20987. }, null, scene.database, false, function () {
  20988. if (_this.onError) {
  20989. _this.onError(_this);
  20990. }
  20991. onError();
  20992. });
  20993. };
  20994. return TextFileAssetTask;
  20995. })();
  20996. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20997. var BinaryFileAssetTask = (function () {
  20998. function BinaryFileAssetTask(name, url) {
  20999. this.name = name;
  21000. this.url = url;
  21001. this.isCompleted = false;
  21002. }
  21003. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21004. var _this = this;
  21005. BABYLON.Tools.LoadFile(this.url, function (data) {
  21006. _this.data = data;
  21007. _this.isCompleted = true;
  21008. if (_this.onSuccess) {
  21009. _this.onSuccess(_this);
  21010. }
  21011. onSuccess();
  21012. }, null, scene.database, true, function () {
  21013. if (_this.onError) {
  21014. _this.onError(_this);
  21015. }
  21016. onError();
  21017. });
  21018. };
  21019. return BinaryFileAssetTask;
  21020. })();
  21021. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21022. var ImageAssetTask = (function () {
  21023. function ImageAssetTask(name, url) {
  21024. this.name = name;
  21025. this.url = url;
  21026. this.isCompleted = false;
  21027. }
  21028. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21029. var _this = this;
  21030. var img = new Image();
  21031. img.onload = function () {
  21032. _this.image = img;
  21033. _this.isCompleted = true;
  21034. if (_this.onSuccess) {
  21035. _this.onSuccess(_this);
  21036. }
  21037. onSuccess();
  21038. };
  21039. img.onerror = function () {
  21040. if (_this.onError) {
  21041. _this.onError(_this);
  21042. }
  21043. onError();
  21044. };
  21045. img.src = this.url;
  21046. };
  21047. return ImageAssetTask;
  21048. })();
  21049. BABYLON.ImageAssetTask = ImageAssetTask;
  21050. var TextureAssetTask = (function () {
  21051. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21052. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21053. this.name = name;
  21054. this.url = url;
  21055. this.noMipmap = noMipmap;
  21056. this.invertY = invertY;
  21057. this.samplingMode = samplingMode;
  21058. this.isCompleted = false;
  21059. }
  21060. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21061. var _this = this;
  21062. var onload = function () {
  21063. _this.isCompleted = true;
  21064. if (_this.onSuccess) {
  21065. _this.onSuccess(_this);
  21066. }
  21067. onSuccess();
  21068. };
  21069. var onerror = function () {
  21070. if (_this.onError) {
  21071. _this.onError(_this);
  21072. }
  21073. onError();
  21074. };
  21075. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21076. };
  21077. return TextureAssetTask;
  21078. })();
  21079. BABYLON.TextureAssetTask = TextureAssetTask;
  21080. var AssetsManager = (function () {
  21081. function AssetsManager(scene) {
  21082. this._tasks = new Array();
  21083. this._waitingTasksCount = 0;
  21084. this.useDefaultLoadingScreen = true;
  21085. this._scene = scene;
  21086. }
  21087. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21088. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21089. this._tasks.push(task);
  21090. return task;
  21091. };
  21092. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21093. var task = new TextFileAssetTask(taskName, url);
  21094. this._tasks.push(task);
  21095. return task;
  21096. };
  21097. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21098. var task = new BinaryFileAssetTask(taskName, url);
  21099. this._tasks.push(task);
  21100. return task;
  21101. };
  21102. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21103. var task = new ImageAssetTask(taskName, url);
  21104. this._tasks.push(task);
  21105. return task;
  21106. };
  21107. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21108. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21109. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21110. this._tasks.push(task);
  21111. return task;
  21112. };
  21113. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21114. this._waitingTasksCount--;
  21115. if (this._waitingTasksCount === 0) {
  21116. if (this.onFinish) {
  21117. this.onFinish(this._tasks);
  21118. }
  21119. this._scene.getEngine().hideLoadingUI();
  21120. }
  21121. };
  21122. AssetsManager.prototype._runTask = function (task) {
  21123. var _this = this;
  21124. task.run(this._scene, function () {
  21125. if (_this.onTaskSuccess) {
  21126. _this.onTaskSuccess(task);
  21127. }
  21128. _this._decreaseWaitingTasksCount();
  21129. }, function () {
  21130. if (_this.onTaskError) {
  21131. _this.onTaskError(task);
  21132. }
  21133. _this._decreaseWaitingTasksCount();
  21134. });
  21135. };
  21136. AssetsManager.prototype.reset = function () {
  21137. this._tasks = new Array();
  21138. return this;
  21139. };
  21140. AssetsManager.prototype.load = function () {
  21141. this._waitingTasksCount = this._tasks.length;
  21142. if (this._waitingTasksCount === 0) {
  21143. if (this.onFinish) {
  21144. this.onFinish(this._tasks);
  21145. }
  21146. return this;
  21147. }
  21148. if (this.useDefaultLoadingScreen) {
  21149. this._scene.getEngine().displayLoadingUI();
  21150. }
  21151. for (var index = 0; index < this._tasks.length; index++) {
  21152. var task = this._tasks[index];
  21153. this._runTask(task);
  21154. }
  21155. return this;
  21156. };
  21157. return AssetsManager;
  21158. })();
  21159. BABYLON.AssetsManager = AssetsManager;
  21160. })(BABYLON || (BABYLON = {}));
  21161. var __extends = this.__extends || function (d, b) {
  21162. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21163. function __() { this.constructor = d; }
  21164. __.prototype = b.prototype;
  21165. d.prototype = new __();
  21166. };
  21167. var BABYLON;
  21168. (function (BABYLON) {
  21169. var VRDeviceOrientationCamera = (function (_super) {
  21170. __extends(VRDeviceOrientationCamera, _super);
  21171. function VRDeviceOrientationCamera(name, position, scene) {
  21172. _super.call(this, name, position, scene);
  21173. this._alpha = 0;
  21174. this._beta = 0;
  21175. this._gamma = 0;
  21176. }
  21177. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21178. this._alpha = +evt.alpha | 0;
  21179. this._beta = +evt.beta | 0;
  21180. this._gamma = +evt.gamma | 0;
  21181. if (this._gamma < 0) {
  21182. this._gamma = 90 + this._gamma;
  21183. } else {
  21184. this._gamma = 270 - this._gamma;
  21185. }
  21186. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21187. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21188. this.rotation.z = this._beta / 180.0 * Math.PI;
  21189. };
  21190. return VRDeviceOrientationCamera;
  21191. })(BABYLON.OculusCamera);
  21192. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21193. })(BABYLON || (BABYLON = {}));
  21194. var __extends = this.__extends || function (d, b) {
  21195. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21196. function __() { this.constructor = d; }
  21197. __.prototype = b.prototype;
  21198. d.prototype = new __();
  21199. };
  21200. var BABYLON;
  21201. (function (BABYLON) {
  21202. var WebVRCamera = (function (_super) {
  21203. __extends(WebVRCamera, _super);
  21204. function WebVRCamera(name, position, scene) {
  21205. _super.call(this, name, position, scene);
  21206. this._hmdDevice = null;
  21207. this._sensorDevice = null;
  21208. this._cacheState = null;
  21209. this._cacheQuaternion = new BABYLON.Quaternion();
  21210. this._cacheRotation = BABYLON.Vector3.Zero();
  21211. this._vrEnabled = false;
  21212. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21213. }
  21214. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21215. var size = devices.length;
  21216. var i = 0;
  21217. this._sensorDevice = null;
  21218. this._hmdDevice = null;
  21219. while (i < size && this._hmdDevice === null) {
  21220. if (devices[i] instanceof HMDVRDevice) {
  21221. this._hmdDevice = devices[i];
  21222. }
  21223. i++;
  21224. }
  21225. i = 0;
  21226. while (i < size && this._sensorDevice === null) {
  21227. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21228. this._sensorDevice = devices[i];
  21229. }
  21230. i++;
  21231. }
  21232. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21233. };
  21234. WebVRCamera.prototype._update = function () {
  21235. if (this._vrEnabled) {
  21236. this._cacheState = this._sensorDevice.getState();
  21237. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21238. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21239. this.rotation.x = -this._cacheRotation.z;
  21240. this.rotation.y = -this._cacheRotation.y;
  21241. this.rotation.z = this._cacheRotation.x;
  21242. }
  21243. _super.prototype._update.call(this);
  21244. };
  21245. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21246. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21247. if (navigator.getVRDevices) {
  21248. navigator.getVRDevices().then(this._getWebVRDevices);
  21249. } else if (navigator.mozGetVRDevices) {
  21250. navigator.mozGetVRDevices(this._getWebVRDevices);
  21251. }
  21252. };
  21253. WebVRCamera.prototype.detachControl = function (element) {
  21254. _super.prototype.detachControl.call(this, element);
  21255. this._vrEnabled = false;
  21256. };
  21257. return WebVRCamera;
  21258. })(BABYLON.OculusCamera);
  21259. BABYLON.WebVRCamera = WebVRCamera;
  21260. })(BABYLON || (BABYLON = {}));
  21261. var __extends = this.__extends || function (d, b) {
  21262. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21263. function __() { this.constructor = d; }
  21264. __.prototype = b.prototype;
  21265. d.prototype = new __();
  21266. };
  21267. var BABYLON;
  21268. (function (BABYLON) {
  21269. var SceneOptimization = (function () {
  21270. function SceneOptimization(priority) {
  21271. if (typeof priority === "undefined") { priority = 0; }
  21272. this.priority = priority;
  21273. this.apply = function (scene) {
  21274. return true;
  21275. };
  21276. }
  21277. return SceneOptimization;
  21278. })();
  21279. BABYLON.SceneOptimization = SceneOptimization;
  21280. var TextureSceneOptimization = (function (_super) {
  21281. __extends(TextureSceneOptimization, _super);
  21282. function TextureSceneOptimization(maximumSize, priority) {
  21283. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21284. if (typeof priority === "undefined") { priority = 0; }
  21285. var _this = this;
  21286. _super.call(this, priority);
  21287. this.maximumSize = maximumSize;
  21288. this.priority = priority;
  21289. this.apply = function (scene) {
  21290. var allDone = true;
  21291. for (var index = 0; index < scene.textures.length; index++) {
  21292. var texture = scene.textures[index];
  21293. if (!texture.canRescale) {
  21294. continue;
  21295. }
  21296. var currentSize = texture.getSize();
  21297. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21298. if (maxDimension > _this.maximumSize) {
  21299. texture.scale(0.5);
  21300. allDone = false;
  21301. }
  21302. }
  21303. return allDone;
  21304. };
  21305. }
  21306. return TextureSceneOptimization;
  21307. })(SceneOptimization);
  21308. BABYLON.TextureSceneOptimization = TextureSceneOptimization;
  21309. var HardwareScalingSceneOptimization = (function (_super) {
  21310. __extends(HardwareScalingSceneOptimization, _super);
  21311. function HardwareScalingSceneOptimization(maximumScale, priority) {
  21312. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21313. if (typeof priority === "undefined") { priority = 0; }
  21314. var _this = this;
  21315. _super.call(this, priority);
  21316. this.maximumScale = maximumScale;
  21317. this.priority = priority;
  21318. this._currentScale = 1;
  21319. this.apply = function (scene) {
  21320. _this._currentScale++;
  21321. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21322. return _this._currentScale >= _this.maximumScale;
  21323. };
  21324. }
  21325. return HardwareScalingSceneOptimization;
  21326. })(SceneOptimization);
  21327. BABYLON.HardwareScalingSceneOptimization = HardwareScalingSceneOptimization;
  21328. var ShadowsSceneOptimization = (function (_super) {
  21329. __extends(ShadowsSceneOptimization, _super);
  21330. function ShadowsSceneOptimization() {
  21331. _super.apply(this, arguments);
  21332. this.apply = function (scene) {
  21333. scene.shadowsEnabled = false;
  21334. return true;
  21335. };
  21336. }
  21337. return ShadowsSceneOptimization;
  21338. })(SceneOptimization);
  21339. BABYLON.ShadowsSceneOptimization = ShadowsSceneOptimization;
  21340. var PostProcessesSceneOptimization = (function (_super) {
  21341. __extends(PostProcessesSceneOptimization, _super);
  21342. function PostProcessesSceneOptimization() {
  21343. _super.apply(this, arguments);
  21344. this.apply = function (scene) {
  21345. scene.postProcessesEnabled = false;
  21346. return true;
  21347. };
  21348. }
  21349. return PostProcessesSceneOptimization;
  21350. })(SceneOptimization);
  21351. BABYLON.PostProcessesSceneOptimization = PostProcessesSceneOptimization;
  21352. var LensFlaresSceneOptimization = (function (_super) {
  21353. __extends(LensFlaresSceneOptimization, _super);
  21354. function LensFlaresSceneOptimization() {
  21355. _super.apply(this, arguments);
  21356. this.apply = function (scene) {
  21357. scene.lensFlaresEnabled = false;
  21358. return true;
  21359. };
  21360. }
  21361. return LensFlaresSceneOptimization;
  21362. })(SceneOptimization);
  21363. BABYLON.LensFlaresSceneOptimization = LensFlaresSceneOptimization;
  21364. var ParticlesSceneOptimization = (function (_super) {
  21365. __extends(ParticlesSceneOptimization, _super);
  21366. function ParticlesSceneOptimization() {
  21367. _super.apply(this, arguments);
  21368. this.apply = function (scene) {
  21369. scene.particlesEnabled = false;
  21370. return true;
  21371. };
  21372. }
  21373. return ParticlesSceneOptimization;
  21374. })(SceneOptimization);
  21375. BABYLON.ParticlesSceneOptimization = ParticlesSceneOptimization;
  21376. var SceneOptimizerOptions = (function () {
  21377. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21378. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21379. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21380. this.targetFrameRate = targetFrameRate;
  21381. this.trackerDuration = trackerDuration;
  21382. this.optimizations = new Array();
  21383. }
  21384. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21385. var result = new SceneOptimizerOptions(targetFrameRate);
  21386. var priority = 0;
  21387. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21388. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21389. priority++;
  21390. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21391. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21392. priority++;
  21393. result.optimizations.push(new TextureSceneOptimization(priority, 1024));
  21394. return result;
  21395. };
  21396. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21397. var result = new SceneOptimizerOptions(targetFrameRate);
  21398. var priority = 0;
  21399. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21400. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21401. priority++;
  21402. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21403. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21404. priority++;
  21405. result.optimizations.push(new TextureSceneOptimization(priority, 512));
  21406. priority++;
  21407. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 2));
  21408. return result;
  21409. };
  21410. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21411. var result = new SceneOptimizerOptions(targetFrameRate);
  21412. var priority = 0;
  21413. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21414. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21415. priority++;
  21416. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21417. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21418. priority++;
  21419. result.optimizations.push(new TextureSceneOptimization(priority, 256));
  21420. priority++;
  21421. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 4));
  21422. return result;
  21423. };
  21424. return SceneOptimizerOptions;
  21425. })();
  21426. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21427. var SceneOptimizer = (function () {
  21428. function SceneOptimizer() {
  21429. }
  21430. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21431. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21432. if (onSuccess) {
  21433. onSuccess();
  21434. }
  21435. return;
  21436. }
  21437. var allDone = true;
  21438. var noOptimizationApplied = true;
  21439. for (var index = 0; index < options.optimizations.length; index++) {
  21440. var optimization = options.optimizations[index];
  21441. if (optimization.priority === currentPriorityLevel) {
  21442. noOptimizationApplied = false;
  21443. allDone = allDone && optimization.apply(scene);
  21444. }
  21445. }
  21446. if (noOptimizationApplied) {
  21447. if (onFailure) {
  21448. onFailure();
  21449. }
  21450. return;
  21451. }
  21452. if (allDone) {
  21453. currentPriorityLevel++;
  21454. }
  21455. scene.executeWhenReady(function () {
  21456. setTimeout(function () {
  21457. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21458. }, options.trackerDuration);
  21459. });
  21460. };
  21461. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21462. if (!options) {
  21463. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21464. }
  21465. scene.executeWhenReady(function () {
  21466. setTimeout(function () {
  21467. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21468. }, options.trackerDuration);
  21469. });
  21470. };
  21471. return SceneOptimizer;
  21472. })();
  21473. BABYLON.SceneOptimizer = SceneOptimizer;
  21474. })(BABYLON || (BABYLON = {}));