babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = 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);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. 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));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. 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]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. 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);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. 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);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. // Temporary pre-allocated objects for engine internal use
  2955. // usage in any internal function :
  2956. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2957. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2958. var Tmp = (function () {
  2959. function Tmp() {
  2960. }
  2961. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2962. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2963. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  2964. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2965. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2966. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2967. Matrix.Zero(), Matrix.Zero(),
  2968. Matrix.Zero(), Matrix.Zero(),
  2969. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2970. return Tmp;
  2971. })();
  2972. BABYLON.Tmp = Tmp;
  2973. })(BABYLON || (BABYLON = {}));
  2974. var BABYLON;
  2975. (function (BABYLON) {
  2976. var Database = (function () {
  2977. function Database(urlToScene, callbackManifestChecked) {
  2978. // Handling various flavors of prefixed version of IndexedDB
  2979. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2980. this.callbackManifestChecked = callbackManifestChecked;
  2981. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2982. this.db = null;
  2983. this.enableSceneOffline = false;
  2984. this.enableTexturesOffline = false;
  2985. this.manifestVersionFound = 0;
  2986. this.mustUpdateRessources = false;
  2987. this.hasReachedQuota = false;
  2988. if (!Database.IDBStorageEnabled) {
  2989. this.callbackManifestChecked(true);
  2990. }
  2991. else {
  2992. this.checkManifestFile();
  2993. }
  2994. }
  2995. Database.prototype.checkManifestFile = function () {
  2996. var _this = this;
  2997. function noManifestFile() {
  2998. that.enableSceneOffline = false;
  2999. that.enableTexturesOffline = false;
  3000. that.callbackManifestChecked(false);
  3001. }
  3002. var that = this;
  3003. var timeStampUsed = false;
  3004. var manifestURL = this.currentSceneUrl + ".manifest";
  3005. var xhr = new XMLHttpRequest();
  3006. if (navigator.onLine) {
  3007. // Adding a timestamp to by-pass browsers' cache
  3008. timeStampUsed = true;
  3009. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3010. }
  3011. xhr.open("GET", manifestURL, true);
  3012. xhr.addEventListener("load", function () {
  3013. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3014. try {
  3015. var manifestFile = JSON.parse(xhr.response);
  3016. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3017. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3018. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3019. _this.manifestVersionFound = manifestFile.version;
  3020. }
  3021. if (_this.callbackManifestChecked) {
  3022. _this.callbackManifestChecked(true);
  3023. }
  3024. }
  3025. catch (ex) {
  3026. noManifestFile();
  3027. }
  3028. }
  3029. else {
  3030. noManifestFile();
  3031. }
  3032. }, false);
  3033. xhr.addEventListener("error", function (event) {
  3034. if (timeStampUsed) {
  3035. timeStampUsed = false;
  3036. // Let's retry without the timeStamp
  3037. // It could fail when coupled with HTML5 Offline API
  3038. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3039. xhr.open("GET", retryManifestURL, true);
  3040. xhr.send();
  3041. }
  3042. else {
  3043. noManifestFile();
  3044. }
  3045. }, false);
  3046. try {
  3047. xhr.send();
  3048. }
  3049. catch (ex) {
  3050. BABYLON.Tools.Error("Error on XHR send request.");
  3051. that.callbackManifestChecked(false);
  3052. }
  3053. };
  3054. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3055. var _this = this;
  3056. function handleError() {
  3057. that.isSupported = false;
  3058. if (errorCallback)
  3059. errorCallback();
  3060. }
  3061. var that = this;
  3062. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3063. // Your browser doesn't support IndexedDB
  3064. this.isSupported = false;
  3065. if (errorCallback)
  3066. errorCallback();
  3067. }
  3068. else {
  3069. // If the DB hasn't been opened or created yet
  3070. if (!this.db) {
  3071. this.hasReachedQuota = false;
  3072. this.isSupported = true;
  3073. var request = this.idbFactory.open("babylonjs", 1);
  3074. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3075. request.onerror = function (event) {
  3076. handleError();
  3077. };
  3078. // executes when a version change transaction cannot complete due to other active transactions
  3079. request.onblocked = function (event) {
  3080. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3081. handleError();
  3082. };
  3083. // DB has been opened successfully
  3084. request.onsuccess = function (event) {
  3085. _this.db = request.result;
  3086. successCallback();
  3087. };
  3088. // Initialization of the DB. Creating Scenes & Textures stores
  3089. request.onupgradeneeded = function (event) {
  3090. _this.db = (event.target).result;
  3091. try {
  3092. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3093. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3094. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3095. }
  3096. catch (ex) {
  3097. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3098. handleError();
  3099. }
  3100. };
  3101. }
  3102. else {
  3103. if (successCallback)
  3104. successCallback();
  3105. }
  3106. }
  3107. };
  3108. Database.prototype.loadImageFromDB = function (url, image) {
  3109. var _this = this;
  3110. var completeURL = Database.ReturnFullUrlLocation(url);
  3111. var saveAndLoadImage = function () {
  3112. if (!_this.hasReachedQuota && _this.db !== null) {
  3113. // the texture is not yet in the DB, let's try to save it
  3114. _this._saveImageIntoDBAsync(completeURL, image);
  3115. }
  3116. else {
  3117. image.src = url;
  3118. }
  3119. };
  3120. if (!this.mustUpdateRessources) {
  3121. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3122. }
  3123. else {
  3124. saveAndLoadImage();
  3125. }
  3126. };
  3127. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3128. if (this.isSupported && this.db !== null) {
  3129. var texture;
  3130. var transaction = this.db.transaction(["textures"]);
  3131. transaction.onabort = function (event) {
  3132. image.src = url;
  3133. };
  3134. transaction.oncomplete = function (event) {
  3135. var blobTextureURL;
  3136. if (texture) {
  3137. var URL = window.URL || window.webkitURL;
  3138. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3139. image.onerror = function () {
  3140. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3141. image.src = url;
  3142. };
  3143. image.src = blobTextureURL;
  3144. }
  3145. else {
  3146. notInDBCallback();
  3147. }
  3148. };
  3149. var getRequest = transaction.objectStore("textures").get(url);
  3150. getRequest.onsuccess = function (event) {
  3151. texture = (event.target).result;
  3152. };
  3153. getRequest.onerror = function (event) {
  3154. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3155. image.src = url;
  3156. };
  3157. }
  3158. else {
  3159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3160. image.src = url;
  3161. }
  3162. };
  3163. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3164. var _this = this;
  3165. if (this.isSupported) {
  3166. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3167. var generateBlobUrl = function () {
  3168. var blobTextureURL;
  3169. if (blob) {
  3170. var URL = window.URL || window.webkitURL;
  3171. try {
  3172. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3173. }
  3174. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3175. catch (ex) {
  3176. blobTextureURL = URL.createObjectURL(blob);
  3177. }
  3178. }
  3179. image.src = blobTextureURL;
  3180. };
  3181. if (Database.IsUASupportingBlobStorage) {
  3182. var xhr = new XMLHttpRequest(), blob;
  3183. xhr.open("GET", url, true);
  3184. xhr.responseType = "blob";
  3185. xhr.addEventListener("load", function () {
  3186. if (xhr.status === 200) {
  3187. // Blob as response (XHR2)
  3188. blob = xhr.response;
  3189. var transaction = _this.db.transaction(["textures"], "readwrite");
  3190. // the transaction could abort because of a QuotaExceededError error
  3191. transaction.onabort = function (event) {
  3192. try {
  3193. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3194. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3195. this.hasReachedQuota = true;
  3196. }
  3197. }
  3198. catch (ex) { }
  3199. generateBlobUrl();
  3200. };
  3201. transaction.oncomplete = function (event) {
  3202. generateBlobUrl();
  3203. };
  3204. var newTexture = { textureUrl: url, data: blob };
  3205. try {
  3206. // Put the blob into the dabase
  3207. var addRequest = transaction.objectStore("textures").put(newTexture);
  3208. addRequest.onsuccess = function (event) {
  3209. };
  3210. addRequest.onerror = function (event) {
  3211. generateBlobUrl();
  3212. };
  3213. }
  3214. catch (ex) {
  3215. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3216. if (ex.code === 25) {
  3217. Database.IsUASupportingBlobStorage = false;
  3218. }
  3219. image.src = url;
  3220. }
  3221. }
  3222. else {
  3223. image.src = url;
  3224. }
  3225. }, false);
  3226. xhr.addEventListener("error", function (event) {
  3227. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3228. image.src = url;
  3229. }, false);
  3230. xhr.send();
  3231. }
  3232. else {
  3233. image.src = url;
  3234. }
  3235. }
  3236. else {
  3237. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3238. image.src = url;
  3239. }
  3240. };
  3241. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3242. var _this = this;
  3243. var updateVersion = function (event) {
  3244. // the version is not yet in the DB or we need to update it
  3245. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3246. };
  3247. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3248. };
  3249. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3250. var _this = this;
  3251. if (this.isSupported) {
  3252. var version;
  3253. try {
  3254. var transaction = this.db.transaction(["versions"]);
  3255. transaction.oncomplete = function (event) {
  3256. if (version) {
  3257. // If the version in the JSON file is > than the version in DB
  3258. if (_this.manifestVersionFound > version.data) {
  3259. _this.mustUpdateRessources = true;
  3260. updateInDBCallback();
  3261. }
  3262. else {
  3263. callback(version.data);
  3264. }
  3265. }
  3266. else {
  3267. _this.mustUpdateRessources = true;
  3268. updateInDBCallback();
  3269. }
  3270. };
  3271. transaction.onabort = function (event) {
  3272. callback(-1);
  3273. };
  3274. var getRequest = transaction.objectStore("versions").get(url);
  3275. getRequest.onsuccess = function (event) {
  3276. version = (event.target).result;
  3277. };
  3278. getRequest.onerror = function (event) {
  3279. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3280. callback(-1);
  3281. };
  3282. }
  3283. catch (ex) {
  3284. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3285. callback(-1);
  3286. }
  3287. }
  3288. else {
  3289. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3290. callback(-1);
  3291. }
  3292. };
  3293. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3294. var _this = this;
  3295. if (this.isSupported && !this.hasReachedQuota) {
  3296. try {
  3297. // Open a transaction to the database
  3298. var transaction = this.db.transaction(["versions"], "readwrite");
  3299. // the transaction could abort because of a QuotaExceededError error
  3300. transaction.onabort = function (event) {
  3301. try {
  3302. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3303. _this.hasReachedQuota = true;
  3304. }
  3305. }
  3306. catch (ex) { }
  3307. callback(-1);
  3308. };
  3309. transaction.oncomplete = function (event) {
  3310. callback(_this.manifestVersionFound);
  3311. };
  3312. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3313. // Put the scene into the database
  3314. var addRequest = transaction.objectStore("versions").put(newVersion);
  3315. addRequest.onsuccess = function (event) {
  3316. };
  3317. addRequest.onerror = function (event) {
  3318. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3319. };
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3323. callback(-1);
  3324. }
  3325. }
  3326. else {
  3327. callback(-1);
  3328. }
  3329. };
  3330. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3331. var _this = this;
  3332. var completeUrl = Database.ReturnFullUrlLocation(url);
  3333. var saveAndLoadFile = function (event) {
  3334. // the scene is not yet in the DB, let's try to save it
  3335. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3336. };
  3337. this._checkVersionFromDB(completeUrl, function (version) {
  3338. if (version !== -1) {
  3339. if (!_this.mustUpdateRessources) {
  3340. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3341. }
  3342. else {
  3343. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3344. }
  3345. }
  3346. else {
  3347. errorCallback();
  3348. }
  3349. });
  3350. };
  3351. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3352. if (this.isSupported) {
  3353. var targetStore;
  3354. if (url.indexOf(".babylon") !== -1) {
  3355. targetStore = "scenes";
  3356. }
  3357. else {
  3358. targetStore = "textures";
  3359. }
  3360. var file;
  3361. var transaction = this.db.transaction([targetStore]);
  3362. transaction.oncomplete = function (event) {
  3363. if (file) {
  3364. callback(file.data);
  3365. }
  3366. else {
  3367. notInDBCallback();
  3368. }
  3369. };
  3370. transaction.onabort = function (event) {
  3371. notInDBCallback();
  3372. };
  3373. var getRequest = transaction.objectStore(targetStore).get(url);
  3374. getRequest.onsuccess = function (event) {
  3375. file = (event.target).result;
  3376. };
  3377. getRequest.onerror = function (event) {
  3378. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3379. notInDBCallback();
  3380. };
  3381. }
  3382. else {
  3383. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3384. callback();
  3385. }
  3386. };
  3387. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3388. var _this = this;
  3389. if (this.isSupported) {
  3390. var targetStore;
  3391. if (url.indexOf(".babylon") !== -1) {
  3392. targetStore = "scenes";
  3393. }
  3394. else {
  3395. targetStore = "textures";
  3396. }
  3397. // Create XHR
  3398. var xhr = new XMLHttpRequest(), fileData;
  3399. xhr.open("GET", url, true);
  3400. if (useArrayBuffer) {
  3401. xhr.responseType = "arraybuffer";
  3402. }
  3403. xhr.onprogress = progressCallback;
  3404. xhr.addEventListener("load", function () {
  3405. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3406. // Blob as response (XHR2)
  3407. //fileData = xhr.responseText;
  3408. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3409. if (!_this.hasReachedQuota) {
  3410. // Open a transaction to the database
  3411. var transaction = _this.db.transaction([targetStore], "readwrite");
  3412. // the transaction could abort because of a QuotaExceededError error
  3413. transaction.onabort = function (event) {
  3414. try {
  3415. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3416. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3417. this.hasReachedQuota = true;
  3418. }
  3419. }
  3420. catch (ex) { }
  3421. callback(fileData);
  3422. };
  3423. transaction.oncomplete = function (event) {
  3424. callback(fileData);
  3425. };
  3426. var newFile;
  3427. if (targetStore === "scenes") {
  3428. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3429. }
  3430. else {
  3431. newFile = { textureUrl: url, data: fileData };
  3432. }
  3433. try {
  3434. // Put the scene into the database
  3435. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3436. addRequest.onsuccess = function (event) {
  3437. };
  3438. addRequest.onerror = function (event) {
  3439. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3440. };
  3441. }
  3442. catch (ex) {
  3443. callback(fileData);
  3444. }
  3445. }
  3446. else {
  3447. callback(fileData);
  3448. }
  3449. }
  3450. else {
  3451. callback();
  3452. }
  3453. }, false);
  3454. xhr.addEventListener("error", function (event) {
  3455. BABYLON.Tools.Error("error on XHR request.");
  3456. callback();
  3457. }, false);
  3458. xhr.send();
  3459. }
  3460. else {
  3461. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3462. callback();
  3463. }
  3464. };
  3465. Database.IsUASupportingBlobStorage = true;
  3466. Database.IDBStorageEnabled = true;
  3467. Database.parseURL = function (url) {
  3468. var a = document.createElement('a');
  3469. a.href = url;
  3470. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3471. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3472. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3473. return absLocation;
  3474. };
  3475. Database.ReturnFullUrlLocation = function (url) {
  3476. if (url.indexOf("http:/") === -1) {
  3477. return (Database.parseURL(window.location.href) + url);
  3478. }
  3479. else {
  3480. return url;
  3481. }
  3482. };
  3483. return Database;
  3484. })();
  3485. BABYLON.Database = Database;
  3486. })(BABYLON || (BABYLON = {}));
  3487. var BABYLON;
  3488. (function (BABYLON) {
  3489. var Internals;
  3490. (function (Internals) {
  3491. /*
  3492. * Based on jsTGALoader - Javascript loader for TGA file
  3493. * By Vincent Thibault
  3494. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3495. */
  3496. var TGATools = (function () {
  3497. function TGATools() {
  3498. }
  3499. TGATools.GetTGAHeader = function (data) {
  3500. var offset = 0;
  3501. var header = {
  3502. id_length: data[offset++],
  3503. colormap_type: data[offset++],
  3504. image_type: data[offset++],
  3505. colormap_index: data[offset++] | data[offset++] << 8,
  3506. colormap_length: data[offset++] | data[offset++] << 8,
  3507. colormap_size: data[offset++],
  3508. origin: [
  3509. data[offset++] | data[offset++] << 8,
  3510. data[offset++] | data[offset++] << 8
  3511. ],
  3512. width: data[offset++] | data[offset++] << 8,
  3513. height: data[offset++] | data[offset++] << 8,
  3514. pixel_size: data[offset++],
  3515. flags: data[offset++]
  3516. };
  3517. return header;
  3518. };
  3519. TGATools.UploadContent = function (gl, data) {
  3520. // Not enough data to contain header ?
  3521. if (data.length < 19) {
  3522. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3523. return;
  3524. }
  3525. // Read Header
  3526. var offset = 18;
  3527. var header = TGATools.GetTGAHeader(data);
  3528. // Assume it's a valid Targa file.
  3529. if (header.id_length + offset > data.length) {
  3530. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3531. return;
  3532. }
  3533. // Skip not needed data
  3534. offset += header.id_length;
  3535. var use_rle = false;
  3536. var use_pal = false;
  3537. var use_rgb = false;
  3538. var use_grey = false;
  3539. // Get some informations.
  3540. switch (header.image_type) {
  3541. case TGATools._TYPE_RLE_INDEXED:
  3542. use_rle = true;
  3543. case TGATools._TYPE_INDEXED:
  3544. use_pal = true;
  3545. break;
  3546. case TGATools._TYPE_RLE_RGB:
  3547. use_rle = true;
  3548. case TGATools._TYPE_RGB:
  3549. use_rgb = true;
  3550. break;
  3551. case TGATools._TYPE_RLE_GREY:
  3552. use_rle = true;
  3553. case TGATools._TYPE_GREY:
  3554. use_grey = true;
  3555. break;
  3556. }
  3557. var pixel_data;
  3558. var numAlphaBits = header.flags & 0xf;
  3559. var pixel_size = header.pixel_size >> 3;
  3560. var pixel_total = header.width * header.height * pixel_size;
  3561. // Read palettes
  3562. var palettes;
  3563. if (use_pal) {
  3564. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3565. }
  3566. // Read LRE
  3567. if (use_rle) {
  3568. pixel_data = new Uint8Array(pixel_total);
  3569. var c, count, i;
  3570. var localOffset = 0;
  3571. var pixels = new Uint8Array(pixel_size);
  3572. while (offset < pixel_total && localOffset < pixel_total) {
  3573. c = data[offset++];
  3574. count = (c & 0x7f) + 1;
  3575. // RLE pixels
  3576. if (c & 0x80) {
  3577. // Bind pixel tmp array
  3578. for (i = 0; i < pixel_size; ++i) {
  3579. pixels[i] = data[offset++];
  3580. }
  3581. // Copy pixel array
  3582. for (i = 0; i < count; ++i) {
  3583. pixel_data.set(pixels, localOffset + i * pixel_size);
  3584. }
  3585. localOffset += pixel_size * count;
  3586. }
  3587. else {
  3588. count *= pixel_size;
  3589. for (i = 0; i < count; ++i) {
  3590. pixel_data[localOffset + i] = data[offset++];
  3591. }
  3592. localOffset += count;
  3593. }
  3594. }
  3595. }
  3596. else {
  3597. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3598. }
  3599. // Load to texture
  3600. var x_start, y_start, x_step, y_step, y_end, x_end;
  3601. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3602. default:
  3603. case TGATools._ORIGIN_UL:
  3604. x_start = 0;
  3605. x_step = 1;
  3606. x_end = header.width;
  3607. y_start = 0;
  3608. y_step = 1;
  3609. y_end = header.height;
  3610. break;
  3611. case TGATools._ORIGIN_BL:
  3612. x_start = 0;
  3613. x_step = 1;
  3614. x_end = header.width;
  3615. y_start = header.height - 1;
  3616. y_step = -1;
  3617. y_end = -1;
  3618. break;
  3619. case TGATools._ORIGIN_UR:
  3620. x_start = header.width - 1;
  3621. x_step = -1;
  3622. x_end = -1;
  3623. y_start = 0;
  3624. y_step = 1;
  3625. y_end = header.height;
  3626. break;
  3627. case TGATools._ORIGIN_BR:
  3628. x_start = header.width - 1;
  3629. x_step = -1;
  3630. x_end = -1;
  3631. y_start = header.height - 1;
  3632. y_step = -1;
  3633. y_end = -1;
  3634. break;
  3635. }
  3636. // Load the specify method
  3637. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3638. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3639. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3640. };
  3641. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3642. var image = pixel_data, colormap = palettes;
  3643. var width = header.width, height = header.height;
  3644. var color, i = 0, x, y;
  3645. var imageData = new Uint8Array(width * height * 4);
  3646. for (y = y_start; y !== y_end; y += y_step) {
  3647. for (x = x_start; x !== x_end; x += x_step, i++) {
  3648. color = image[i];
  3649. imageData[(x + width * y) * 4 + 3] = 255;
  3650. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3651. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3652. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3653. }
  3654. }
  3655. return imageData;
  3656. };
  3657. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3658. var image = pixel_data;
  3659. var width = header.width, height = header.height;
  3660. var color, i = 0, x, y;
  3661. var imageData = new Uint8Array(width * height * 4);
  3662. for (y = y_start; y !== y_end; y += y_step) {
  3663. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3664. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3665. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3666. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3667. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3668. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3669. }
  3670. }
  3671. return imageData;
  3672. };
  3673. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3674. var image = pixel_data;
  3675. var width = header.width, height = header.height;
  3676. var i = 0, x, y;
  3677. var imageData = new Uint8Array(width * height * 4);
  3678. for (y = y_start; y !== y_end; y += y_step) {
  3679. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3680. imageData[(x + width * y) * 4 + 3] = 255;
  3681. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3682. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3683. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3684. }
  3685. }
  3686. return imageData;
  3687. };
  3688. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3689. var image = pixel_data;
  3690. var width = header.width, height = header.height;
  3691. var i = 0, x, y;
  3692. var imageData = new Uint8Array(width * height * 4);
  3693. for (y = y_start; y !== y_end; y += y_step) {
  3694. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3695. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3696. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3697. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3698. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3699. }
  3700. }
  3701. return imageData;
  3702. };
  3703. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3704. var image = pixel_data;
  3705. var width = header.width, height = header.height;
  3706. var color, i = 0, x, y;
  3707. var imageData = new Uint8Array(width * height * 4);
  3708. for (y = y_start; y !== y_end; y += y_step) {
  3709. for (x = x_start; x !== x_end; x += x_step, i++) {
  3710. color = image[i];
  3711. imageData[(x + width * y) * 4 + 0] = color;
  3712. imageData[(x + width * y) * 4 + 1] = color;
  3713. imageData[(x + width * y) * 4 + 2] = color;
  3714. imageData[(x + width * y) * 4 + 3] = 255;
  3715. }
  3716. }
  3717. return imageData;
  3718. };
  3719. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3720. var image = pixel_data;
  3721. var width = header.width, height = header.height;
  3722. var i = 0, x, y;
  3723. var imageData = new Uint8Array(width * height * 4);
  3724. for (y = y_start; y !== y_end; y += y_step) {
  3725. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3726. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3727. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3728. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3729. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3730. }
  3731. }
  3732. return imageData;
  3733. };
  3734. TGATools._TYPE_NO_DATA = 0;
  3735. TGATools._TYPE_INDEXED = 1;
  3736. TGATools._TYPE_RGB = 2;
  3737. TGATools._TYPE_GREY = 3;
  3738. TGATools._TYPE_RLE_INDEXED = 9;
  3739. TGATools._TYPE_RLE_RGB = 10;
  3740. TGATools._TYPE_RLE_GREY = 11;
  3741. TGATools._ORIGIN_MASK = 0x30;
  3742. TGATools._ORIGIN_SHIFT = 0x04;
  3743. TGATools._ORIGIN_BL = 0x00;
  3744. TGATools._ORIGIN_BR = 0x01;
  3745. TGATools._ORIGIN_UL = 0x02;
  3746. TGATools._ORIGIN_UR = 0x03;
  3747. return TGATools;
  3748. })();
  3749. Internals.TGATools = TGATools;
  3750. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3751. })(BABYLON || (BABYLON = {}));
  3752. var BABYLON;
  3753. (function (BABYLON) {
  3754. var SmartArray = (function () {
  3755. function SmartArray(capacity) {
  3756. this.length = 0;
  3757. this._duplicateId = 0;
  3758. this.data = new Array(capacity);
  3759. this._id = SmartArray._GlobalId++;
  3760. }
  3761. SmartArray.prototype.push = function (value) {
  3762. this.data[this.length++] = value;
  3763. if (this.length > this.data.length) {
  3764. this.data.length *= 2;
  3765. }
  3766. if (!value.__smartArrayFlags) {
  3767. value.__smartArrayFlags = {};
  3768. }
  3769. value.__smartArrayFlags[this._id] = this._duplicateId;
  3770. };
  3771. SmartArray.prototype.pushNoDuplicate = function (value) {
  3772. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3773. return;
  3774. }
  3775. this.push(value);
  3776. };
  3777. SmartArray.prototype.sort = function (compareFn) {
  3778. this.data.sort(compareFn);
  3779. };
  3780. SmartArray.prototype.reset = function () {
  3781. this.length = 0;
  3782. this._duplicateId++;
  3783. };
  3784. SmartArray.prototype.concat = function (array) {
  3785. if (array.length === 0) {
  3786. return;
  3787. }
  3788. if (this.length + array.length > this.data.length) {
  3789. this.data.length = (this.length + array.length) * 2;
  3790. }
  3791. for (var index = 0; index < array.length; index++) {
  3792. this.data[this.length++] = (array.data || array)[index];
  3793. }
  3794. };
  3795. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3796. if (array.length === 0) {
  3797. return;
  3798. }
  3799. if (this.length + array.length > this.data.length) {
  3800. this.data.length = (this.length + array.length) * 2;
  3801. }
  3802. for (var index = 0; index < array.length; index++) {
  3803. var item = (array.data || array)[index];
  3804. this.pushNoDuplicate(item);
  3805. }
  3806. };
  3807. SmartArray.prototype.indexOf = function (value) {
  3808. var position = this.data.indexOf(value);
  3809. if (position >= this.length) {
  3810. return -1;
  3811. }
  3812. return position;
  3813. };
  3814. // Statics
  3815. SmartArray._GlobalId = 0;
  3816. return SmartArray;
  3817. })();
  3818. BABYLON.SmartArray = SmartArray;
  3819. })(BABYLON || (BABYLON = {}));
  3820. var BABYLON;
  3821. (function (BABYLON) {
  3822. var SmartCollection = (function () {
  3823. function SmartCollection(capacity) {
  3824. if (capacity === void 0) { capacity = 10; }
  3825. this.count = 0;
  3826. this._initialCapacity = capacity;
  3827. this.items = {};
  3828. this._keys = new Array(this._initialCapacity);
  3829. }
  3830. SmartCollection.prototype.add = function (key, item) {
  3831. if (this.items[key] != undefined) {
  3832. return -1;
  3833. }
  3834. this.items[key] = item;
  3835. //literal keys are always strings, but we keep source type of key in _keys array
  3836. this._keys[this.count++] = key;
  3837. if (this.count > this._keys.length) {
  3838. this._keys.length *= 2;
  3839. }
  3840. return this.count;
  3841. };
  3842. SmartCollection.prototype.remove = function (key) {
  3843. if (this.items[key] == undefined) {
  3844. return -1;
  3845. }
  3846. return this.removeItemOfIndex(this.indexOf(key));
  3847. };
  3848. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3849. if (index < this.count && index > -1) {
  3850. delete this.items[this._keys[index]];
  3851. //here, shifting by hand is better optimised than .splice
  3852. while (index < this.count) {
  3853. this._keys[index] = this._keys[index + 1];
  3854. index++;
  3855. }
  3856. }
  3857. else {
  3858. return -1;
  3859. }
  3860. return --this.count;
  3861. };
  3862. SmartCollection.prototype.indexOf = function (key) {
  3863. for (var i = 0; i !== this.count; i++) {
  3864. if (this._keys[i] === key) {
  3865. return i;
  3866. }
  3867. }
  3868. return -1;
  3869. };
  3870. SmartCollection.prototype.item = function (key) {
  3871. return this.items[key];
  3872. };
  3873. SmartCollection.prototype.getAllKeys = function () {
  3874. if (this.count > 0) {
  3875. var keys = new Array(this.count);
  3876. for (var i = 0; i < this.count; i++) {
  3877. keys[i] = this._keys[i];
  3878. }
  3879. return keys;
  3880. }
  3881. else {
  3882. return undefined;
  3883. }
  3884. };
  3885. SmartCollection.prototype.getKeyByIndex = function (index) {
  3886. if (index < this.count && index > -1) {
  3887. return this._keys[index];
  3888. }
  3889. else {
  3890. return undefined;
  3891. }
  3892. };
  3893. SmartCollection.prototype.getItemByIndex = function (index) {
  3894. if (index < this.count && index > -1) {
  3895. return this.items[this._keys[index]];
  3896. }
  3897. else {
  3898. return undefined;
  3899. }
  3900. };
  3901. SmartCollection.prototype.empty = function () {
  3902. if (this.count > 0) {
  3903. this.count = 0;
  3904. this.items = {};
  3905. this._keys = new Array(this._initialCapacity);
  3906. }
  3907. };
  3908. SmartCollection.prototype.forEach = function (block) {
  3909. var key;
  3910. for (key in this.items) {
  3911. if (this.items.hasOwnProperty(key)) {
  3912. block(this.items[key]);
  3913. }
  3914. }
  3915. };
  3916. return SmartCollection;
  3917. })();
  3918. BABYLON.SmartCollection = SmartCollection;
  3919. })(BABYLON || (BABYLON = {}));
  3920. var BABYLON;
  3921. (function (BABYLON) {
  3922. // Screenshots
  3923. var screenshotCanvas;
  3924. var cloneValue = function (source, destinationObject) {
  3925. if (!source)
  3926. return null;
  3927. if (source instanceof BABYLON.Mesh) {
  3928. return null;
  3929. }
  3930. if (source instanceof BABYLON.SubMesh) {
  3931. return source.clone(destinationObject);
  3932. }
  3933. else if (source.clone) {
  3934. return source.clone();
  3935. }
  3936. return null;
  3937. };
  3938. var Tools = (function () {
  3939. function Tools() {
  3940. }
  3941. Tools.Instantiate = function (className) {
  3942. var arr = className.split(".");
  3943. var fn = (window || this);
  3944. for (var i = 0, len = arr.length; i < len; i++) {
  3945. fn = fn[arr[i]];
  3946. }
  3947. if (typeof fn !== "function") {
  3948. return null;
  3949. }
  3950. return fn;
  3951. };
  3952. Tools.GetConstructorName = function (obj) {
  3953. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3954. var cname = str.match(/function\s(\w*)/)[1];
  3955. var aliases = ["", "anonymous", "Anonymous"];
  3956. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3957. };
  3958. Tools.ToHex = function (i) {
  3959. var str = i.toString(16);
  3960. if (i <= 15) {
  3961. return ("0" + str).toUpperCase();
  3962. }
  3963. return str.toUpperCase();
  3964. };
  3965. Tools.SetImmediate = function (action) {
  3966. if (window.setImmediate) {
  3967. window.setImmediate(action);
  3968. }
  3969. else {
  3970. setTimeout(action, 1);
  3971. }
  3972. };
  3973. Tools.IsExponentOfTwo = function (value) {
  3974. var count = 1;
  3975. do {
  3976. count *= 2;
  3977. } while (count < value);
  3978. return count === value;
  3979. };
  3980. Tools.GetExponentOfTwo = function (value, max) {
  3981. var count = 1;
  3982. do {
  3983. count *= 2;
  3984. } while (count < value);
  3985. if (count > max)
  3986. count = max;
  3987. return count;
  3988. };
  3989. Tools.GetFilename = function (path) {
  3990. var index = path.lastIndexOf("/");
  3991. if (index < 0)
  3992. return path;
  3993. return path.substring(index + 1);
  3994. };
  3995. Tools.GetDOMTextContent = function (element) {
  3996. var result = "";
  3997. var child = element.firstChild;
  3998. while (child) {
  3999. if (child.nodeType === 3) {
  4000. result += child.textContent;
  4001. }
  4002. child = child.nextSibling;
  4003. }
  4004. return result;
  4005. };
  4006. Tools.ToDegrees = function (angle) {
  4007. return angle * 180 / Math.PI;
  4008. };
  4009. Tools.ToRadians = function (angle) {
  4010. return angle * Math.PI / 180;
  4011. };
  4012. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4013. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4014. var output = "";
  4015. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4016. var i = 0;
  4017. var bytes = new Uint8Array(buffer);
  4018. while (i < bytes.length) {
  4019. chr1 = bytes[i++];
  4020. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4021. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4022. enc1 = chr1 >> 2;
  4023. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4024. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4025. enc4 = chr3 & 63;
  4026. if (isNaN(chr2)) {
  4027. enc3 = enc4 = 64;
  4028. }
  4029. else if (isNaN(chr3)) {
  4030. enc4 = 64;
  4031. }
  4032. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4033. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4034. }
  4035. return "data:image/png;base64," + output;
  4036. };
  4037. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4038. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4039. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4040. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4041. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4042. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4043. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4044. }
  4045. return {
  4046. minimum: minimum,
  4047. maximum: maximum
  4048. };
  4049. };
  4050. Tools.ExtractMinAndMax = function (positions, start, count) {
  4051. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4052. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4053. for (var index = start; index < start + count; index++) {
  4054. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4055. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4056. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4057. }
  4058. return {
  4059. minimum: minimum,
  4060. maximum: maximum
  4061. };
  4062. };
  4063. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4064. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4065. return undefined;
  4066. return Array.isArray(obj) ? obj : [obj];
  4067. };
  4068. // Misc.
  4069. Tools.GetPointerPrefix = function () {
  4070. var eventPrefix = "pointer";
  4071. // Check if pointer events are supported
  4072. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4073. eventPrefix = "mouse";
  4074. }
  4075. return eventPrefix;
  4076. };
  4077. Tools.QueueNewFrame = function (func) {
  4078. if (window.requestAnimationFrame)
  4079. window.requestAnimationFrame(func);
  4080. else if (window.msRequestAnimationFrame)
  4081. window.msRequestAnimationFrame(func);
  4082. else if (window.webkitRequestAnimationFrame)
  4083. window.webkitRequestAnimationFrame(func);
  4084. else if (window.mozRequestAnimationFrame)
  4085. window.mozRequestAnimationFrame(func);
  4086. else if (window.oRequestAnimationFrame)
  4087. window.oRequestAnimationFrame(func);
  4088. else {
  4089. window.setTimeout(func, 16);
  4090. }
  4091. };
  4092. Tools.RequestFullscreen = function (element) {
  4093. if (element.requestFullscreen)
  4094. element.requestFullscreen();
  4095. else if (element.msRequestFullscreen)
  4096. element.msRequestFullscreen();
  4097. else if (element.webkitRequestFullscreen)
  4098. element.webkitRequestFullscreen();
  4099. else if (element.mozRequestFullScreen)
  4100. element.mozRequestFullScreen();
  4101. };
  4102. Tools.ExitFullscreen = function () {
  4103. if (document.exitFullscreen) {
  4104. document.exitFullscreen();
  4105. }
  4106. else if (document.mozCancelFullScreen) {
  4107. document.mozCancelFullScreen();
  4108. }
  4109. else if (document.webkitCancelFullScreen) {
  4110. document.webkitCancelFullScreen();
  4111. }
  4112. else if (document.msCancelFullScreen) {
  4113. document.msCancelFullScreen();
  4114. }
  4115. };
  4116. // External files
  4117. Tools.CleanUrl = function (url) {
  4118. url = url.replace(/#/mg, "%23");
  4119. return url;
  4120. };
  4121. Tools.LoadImage = function (url, onload, onerror, database) {
  4122. if (url instanceof ArrayBuffer) {
  4123. url = Tools.EncodeArrayBufferTobase64(url);
  4124. }
  4125. url = Tools.CleanUrl(url);
  4126. var img = new Image();
  4127. if (url.substr(0, 5) !== "data:") {
  4128. if (Tools.CorsBehavior) {
  4129. switch (typeof (Tools.CorsBehavior)) {
  4130. case "function":
  4131. var result = Tools.CorsBehavior(url);
  4132. if (result) {
  4133. img.crossOrigin = result;
  4134. }
  4135. break;
  4136. case "string":
  4137. default:
  4138. img.crossOrigin = Tools.CorsBehavior;
  4139. break;
  4140. }
  4141. }
  4142. }
  4143. img.onload = function () {
  4144. onload(img);
  4145. };
  4146. img.onerror = function (err) {
  4147. Tools.Error("Error while trying to load texture: " + url);
  4148. if (Tools.UseFallbackTexture) {
  4149. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4150. onload(img);
  4151. }
  4152. else {
  4153. onerror();
  4154. }
  4155. };
  4156. var noIndexedDB = function () {
  4157. img.src = url;
  4158. };
  4159. var loadFromIndexedDB = function () {
  4160. database.loadImageFromDB(url, img);
  4161. };
  4162. //ANY database to do!
  4163. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4164. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4165. }
  4166. else {
  4167. if (url.indexOf("file:") === -1) {
  4168. noIndexedDB();
  4169. }
  4170. else {
  4171. try {
  4172. var textureName = url.substring(5);
  4173. var blobURL;
  4174. try {
  4175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4176. }
  4177. catch (ex) {
  4178. // Chrome doesn't support oneTimeOnly parameter
  4179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4180. }
  4181. img.src = blobURL;
  4182. }
  4183. catch (e) {
  4184. img.src = null;
  4185. }
  4186. }
  4187. }
  4188. return img;
  4189. };
  4190. //ANY
  4191. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4192. url = Tools.CleanUrl(url);
  4193. var noIndexedDB = function () {
  4194. var request = new XMLHttpRequest();
  4195. var loadUrl = Tools.BaseUrl + url;
  4196. request.open('GET', loadUrl, true);
  4197. if (useArrayBuffer) {
  4198. request.responseType = "arraybuffer";
  4199. }
  4200. request.onprogress = progressCallBack;
  4201. request.onreadystatechange = function () {
  4202. if (request.readyState === 4) {
  4203. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4204. callback(!useArrayBuffer ? request.responseText : request.response);
  4205. }
  4206. else {
  4207. if (onError) {
  4208. onError();
  4209. }
  4210. else {
  4211. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4212. }
  4213. }
  4214. }
  4215. };
  4216. request.send(null);
  4217. };
  4218. var loadFromIndexedDB = function () {
  4219. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4220. };
  4221. if (url.indexOf("file:") !== -1) {
  4222. var fileName = url.substring(5);
  4223. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4224. }
  4225. else {
  4226. // Caching all files
  4227. if (database && database.enableSceneOffline) {
  4228. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4229. }
  4230. else {
  4231. noIndexedDB();
  4232. }
  4233. }
  4234. };
  4235. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4236. var reader = new FileReader();
  4237. reader.onload = function (e) {
  4238. //target doesn't have result from ts 1.3
  4239. callback(e.target['result']);
  4240. };
  4241. reader.onprogress = progressCallback;
  4242. reader.readAsDataURL(fileToLoad);
  4243. };
  4244. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4245. var reader = new FileReader();
  4246. reader.onerror = function (e) {
  4247. Tools.Log("Error while reading file: " + fileToLoad.name);
  4248. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4249. };
  4250. reader.onload = function (e) {
  4251. //target doesn't have result from ts 1.3
  4252. callback(e.target['result']);
  4253. };
  4254. reader.onprogress = progressCallBack;
  4255. if (!useArrayBuffer) {
  4256. // Asynchronous read
  4257. reader.readAsText(fileToLoad);
  4258. }
  4259. else {
  4260. reader.readAsArrayBuffer(fileToLoad);
  4261. }
  4262. };
  4263. //returns a downloadable url to a file content.
  4264. Tools.FileAsURL = function (content) {
  4265. var fileBlob = new Blob([content]);
  4266. var url = window.URL || window.webkitURL;
  4267. var link = url.createObjectURL(fileBlob);
  4268. return link;
  4269. };
  4270. // Misc.
  4271. Tools.Clamp = function (value, min, max) {
  4272. if (min === void 0) { min = 0; }
  4273. if (max === void 0) { max = 1; }
  4274. return Math.min(max, Math.max(min, value));
  4275. };
  4276. // Returns -1 when value is a negative number and
  4277. // +1 when value is a positive number.
  4278. Tools.Sign = function (value) {
  4279. value = +value; // convert to a number
  4280. if (value === 0 || isNaN(value))
  4281. return value;
  4282. return value > 0 ? 1 : -1;
  4283. };
  4284. Tools.Format = function (value, decimals) {
  4285. if (decimals === void 0) { decimals = 2; }
  4286. return value.toFixed(decimals);
  4287. };
  4288. Tools.CheckExtends = function (v, min, max) {
  4289. if (v.x < min.x)
  4290. min.x = v.x;
  4291. if (v.y < min.y)
  4292. min.y = v.y;
  4293. if (v.z < min.z)
  4294. min.z = v.z;
  4295. if (v.x > max.x)
  4296. max.x = v.x;
  4297. if (v.y > max.y)
  4298. max.y = v.y;
  4299. if (v.z > max.z)
  4300. max.z = v.z;
  4301. };
  4302. Tools.WithinEpsilon = function (a, b, epsilon) {
  4303. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4304. var num = a - b;
  4305. return -epsilon <= num && num <= epsilon;
  4306. };
  4307. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4308. for (var prop in source) {
  4309. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4310. continue;
  4311. }
  4312. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4313. continue;
  4314. }
  4315. var sourceValue = source[prop];
  4316. var typeOfSourceValue = typeof sourceValue;
  4317. if (typeOfSourceValue === "function") {
  4318. continue;
  4319. }
  4320. if (typeOfSourceValue === "object") {
  4321. if (sourceValue instanceof Array) {
  4322. destination[prop] = [];
  4323. if (sourceValue.length > 0) {
  4324. if (typeof sourceValue[0] == "object") {
  4325. for (var index = 0; index < sourceValue.length; index++) {
  4326. var clonedValue = cloneValue(sourceValue[index], destination);
  4327. if (destination[prop].indexOf(clonedValue) === -1) {
  4328. destination[prop].push(clonedValue);
  4329. }
  4330. }
  4331. }
  4332. else {
  4333. destination[prop] = sourceValue.slice(0);
  4334. }
  4335. }
  4336. }
  4337. else {
  4338. destination[prop] = cloneValue(sourceValue, destination);
  4339. }
  4340. }
  4341. else {
  4342. destination[prop] = sourceValue;
  4343. }
  4344. }
  4345. };
  4346. Tools.IsEmpty = function (obj) {
  4347. for (var i in obj) {
  4348. return false;
  4349. }
  4350. return true;
  4351. };
  4352. Tools.RegisterTopRootEvents = function (events) {
  4353. for (var index = 0; index < events.length; index++) {
  4354. var event = events[index];
  4355. window.addEventListener(event.name, event.handler, false);
  4356. try {
  4357. if (window.parent) {
  4358. window.parent.addEventListener(event.name, event.handler, false);
  4359. }
  4360. }
  4361. catch (e) {
  4362. }
  4363. }
  4364. };
  4365. Tools.UnregisterTopRootEvents = function (events) {
  4366. for (var index = 0; index < events.length; index++) {
  4367. var event = events[index];
  4368. window.removeEventListener(event.name, event.handler);
  4369. try {
  4370. if (window.parent) {
  4371. window.parent.removeEventListener(event.name, event.handler);
  4372. }
  4373. }
  4374. catch (e) {
  4375. }
  4376. }
  4377. };
  4378. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4379. // Read the contents of the framebuffer
  4380. var numberOfChannelsByLine = width * 4;
  4381. var halfHeight = height / 2;
  4382. //Reading datas from WebGL
  4383. var data = engine.readPixels(0, 0, width, height);
  4384. //To flip image on Y axis.
  4385. for (var i = 0; i < halfHeight; i++) {
  4386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4387. var currentCell = j + i * numberOfChannelsByLine;
  4388. var targetLine = height - i - 1;
  4389. var targetCell = j + targetLine * numberOfChannelsByLine;
  4390. var temp = data[currentCell];
  4391. data[currentCell] = data[targetCell];
  4392. data[targetCell] = temp;
  4393. }
  4394. }
  4395. // Create a 2D canvas to store the result
  4396. if (!screenshotCanvas) {
  4397. screenshotCanvas = document.createElement('canvas');
  4398. }
  4399. screenshotCanvas.width = width;
  4400. screenshotCanvas.height = height;
  4401. var context = screenshotCanvas.getContext('2d');
  4402. // Copy the pixels to a 2D canvas
  4403. var imageData = context.createImageData(width, height);
  4404. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4405. var castData = imageData.data;
  4406. castData.set(data);
  4407. context.putImageData(imageData, 0, 0);
  4408. var base64Image = screenshotCanvas.toDataURL();
  4409. if (successCallback) {
  4410. successCallback(base64Image);
  4411. }
  4412. else {
  4413. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4414. if (("download" in document.createElement("a"))) {
  4415. var a = window.document.createElement("a");
  4416. a.href = base64Image;
  4417. var date = new Date();
  4418. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4419. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4420. window.document.body.appendChild(a);
  4421. a.addEventListener("click", function () {
  4422. a.parentElement.removeChild(a);
  4423. });
  4424. a.click();
  4425. }
  4426. else {
  4427. var newWindow = window.open("");
  4428. var img = newWindow.document.createElement("img");
  4429. img.src = base64Image;
  4430. newWindow.document.body.appendChild(img);
  4431. }
  4432. }
  4433. };
  4434. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4435. var width;
  4436. var height;
  4437. //If a precision value is specified
  4438. if (size.precision) {
  4439. width = Math.round(engine.getRenderWidth() * size.precision);
  4440. height = Math.round(width / engine.getAspectRatio(camera));
  4441. size = { width: width, height: height };
  4442. }
  4443. else if (size.width && size.height) {
  4444. width = size.width;
  4445. height = size.height;
  4446. }
  4447. else if (size.width && !size.height) {
  4448. width = size.width;
  4449. height = Math.round(width / engine.getAspectRatio(camera));
  4450. size = { width: width, height: height };
  4451. }
  4452. else if (size.height && !size.width) {
  4453. height = size.height;
  4454. width = Math.round(height * engine.getAspectRatio(camera));
  4455. size = { width: width, height: height };
  4456. }
  4457. else if (!isNaN(size)) {
  4458. height = size;
  4459. width = size;
  4460. }
  4461. else {
  4462. Tools.Error("Invalid 'size' parameter !");
  4463. return;
  4464. }
  4465. var scene = camera.getScene();
  4466. var previousCamera = null;
  4467. if (scene.activeCamera !== camera) {
  4468. previousCamera = scene.activeCamera;
  4469. scene.activeCamera = camera;
  4470. }
  4471. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4472. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4473. texture.renderList = scene.meshes;
  4474. texture.onAfterRender = function () {
  4475. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4476. };
  4477. scene.incrementRenderId();
  4478. texture.render(true);
  4479. texture.dispose();
  4480. if (previousCamera) {
  4481. scene.activeCamera = previousCamera;
  4482. }
  4483. camera.getProjectionMatrix(true); // Force cache refresh;
  4484. };
  4485. // XHR response validator for local file scenario
  4486. Tools.ValidateXHRData = function (xhr, dataType) {
  4487. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4488. if (dataType === void 0) { dataType = 7; }
  4489. try {
  4490. if (dataType & 1) {
  4491. if (xhr.responseText && xhr.responseText.length > 0) {
  4492. return true;
  4493. }
  4494. else if (dataType === 1) {
  4495. return false;
  4496. }
  4497. }
  4498. if (dataType & 2) {
  4499. // Check header width and height since there is no "TGA" magic number
  4500. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4501. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4502. return true;
  4503. }
  4504. else if (dataType === 2) {
  4505. return false;
  4506. }
  4507. }
  4508. if (dataType & 4) {
  4509. // Check for the "DDS" magic number
  4510. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4511. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4512. return true;
  4513. }
  4514. else {
  4515. return false;
  4516. }
  4517. }
  4518. }
  4519. catch (e) {
  4520. }
  4521. return false;
  4522. };
  4523. Object.defineProperty(Tools, "NoneLogLevel", {
  4524. get: function () {
  4525. return Tools._NoneLogLevel;
  4526. },
  4527. enumerable: true,
  4528. configurable: true
  4529. });
  4530. Object.defineProperty(Tools, "MessageLogLevel", {
  4531. get: function () {
  4532. return Tools._MessageLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "WarningLogLevel", {
  4538. get: function () {
  4539. return Tools._WarningLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Object.defineProperty(Tools, "ErrorLogLevel", {
  4545. get: function () {
  4546. return Tools._ErrorLogLevel;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(Tools, "AllLogLevel", {
  4552. get: function () {
  4553. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Tools._AddLogEntry = function (entry) {
  4559. Tools._LogCache = entry + Tools._LogCache;
  4560. if (Tools.OnNewCacheEntry) {
  4561. Tools.OnNewCacheEntry(entry);
  4562. }
  4563. };
  4564. Tools._FormatMessage = function (message) {
  4565. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4566. var date = new Date();
  4567. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4568. };
  4569. Tools._LogDisabled = function (message) {
  4570. // nothing to do
  4571. };
  4572. Tools._LogEnabled = function (message) {
  4573. var formattedMessage = Tools._FormatMessage(message);
  4574. console.log("BJS - " + formattedMessage);
  4575. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4576. Tools._AddLogEntry(entry);
  4577. };
  4578. Tools._WarnDisabled = function (message) {
  4579. // nothing to do
  4580. };
  4581. Tools._WarnEnabled = function (message) {
  4582. var formattedMessage = Tools._FormatMessage(message);
  4583. console.warn("BJS - " + formattedMessage);
  4584. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4585. Tools._AddLogEntry(entry);
  4586. };
  4587. Tools._ErrorDisabled = function (message) {
  4588. // nothing to do
  4589. };
  4590. Tools._ErrorEnabled = function (message) {
  4591. Tools.errorsCount++;
  4592. var formattedMessage = Tools._FormatMessage(message);
  4593. console.error("BJS - " + formattedMessage);
  4594. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4595. Tools._AddLogEntry(entry);
  4596. };
  4597. Object.defineProperty(Tools, "LogCache", {
  4598. get: function () {
  4599. return Tools._LogCache;
  4600. },
  4601. enumerable: true,
  4602. configurable: true
  4603. });
  4604. Tools.ClearLogCache = function () {
  4605. Tools._LogCache = "";
  4606. Tools.errorsCount = 0;
  4607. };
  4608. Object.defineProperty(Tools, "LogLevels", {
  4609. set: function (level) {
  4610. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4611. Tools.Log = Tools._LogEnabled;
  4612. }
  4613. else {
  4614. Tools.Log = Tools._LogDisabled;
  4615. }
  4616. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4617. Tools.Warn = Tools._WarnEnabled;
  4618. }
  4619. else {
  4620. Tools.Warn = Tools._WarnDisabled;
  4621. }
  4622. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4623. Tools.Error = Tools._ErrorEnabled;
  4624. }
  4625. else {
  4626. Tools.Error = Tools._ErrorDisabled;
  4627. }
  4628. },
  4629. enumerable: true,
  4630. configurable: true
  4631. });
  4632. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4633. get: function () {
  4634. return Tools._PerformanceNoneLogLevel;
  4635. },
  4636. enumerable: true,
  4637. configurable: true
  4638. });
  4639. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4640. get: function () {
  4641. return Tools._PerformanceUserMarkLogLevel;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4647. get: function () {
  4648. return Tools._PerformanceConsoleLogLevel;
  4649. },
  4650. enumerable: true,
  4651. configurable: true
  4652. });
  4653. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4654. set: function (level) {
  4655. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4656. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4657. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4658. return;
  4659. }
  4660. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4661. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4662. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4663. return;
  4664. }
  4665. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4666. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4667. },
  4668. enumerable: true,
  4669. configurable: true
  4670. });
  4671. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4672. };
  4673. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4674. };
  4675. Tools._StartUserMark = function (counterName, condition) {
  4676. if (condition === void 0) { condition = true; }
  4677. if (!condition || !Tools._performance.mark) {
  4678. return;
  4679. }
  4680. Tools._performance.mark(counterName + "-Begin");
  4681. };
  4682. Tools._EndUserMark = function (counterName, condition) {
  4683. if (condition === void 0) { condition = true; }
  4684. if (!condition || !Tools._performance.mark) {
  4685. return;
  4686. }
  4687. Tools._performance.mark(counterName + "-End");
  4688. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4689. };
  4690. Tools._StartPerformanceConsole = function (counterName, condition) {
  4691. if (condition === void 0) { condition = true; }
  4692. if (!condition) {
  4693. return;
  4694. }
  4695. Tools._StartUserMark(counterName, condition);
  4696. if (console.time) {
  4697. console.time(counterName);
  4698. }
  4699. };
  4700. Tools._EndPerformanceConsole = function (counterName, condition) {
  4701. if (condition === void 0) { condition = true; }
  4702. if (!condition) {
  4703. return;
  4704. }
  4705. Tools._EndUserMark(counterName, condition);
  4706. if (console.time) {
  4707. console.timeEnd(counterName);
  4708. }
  4709. };
  4710. Object.defineProperty(Tools, "Now", {
  4711. get: function () {
  4712. if (window.performance && window.performance.now) {
  4713. return window.performance.now();
  4714. }
  4715. return new Date().getTime();
  4716. },
  4717. enumerable: true,
  4718. configurable: true
  4719. });
  4720. Tools.BaseUrl = "";
  4721. Tools.CorsBehavior = "anonymous";
  4722. Tools.UseFallbackTexture = true;
  4723. // Logs
  4724. Tools._NoneLogLevel = 0;
  4725. Tools._MessageLogLevel = 1;
  4726. Tools._WarningLogLevel = 2;
  4727. Tools._ErrorLogLevel = 4;
  4728. Tools._LogCache = "";
  4729. Tools.errorsCount = 0;
  4730. Tools.Log = Tools._LogEnabled;
  4731. Tools.Warn = Tools._WarnEnabled;
  4732. Tools.Error = Tools._ErrorEnabled;
  4733. // Performances
  4734. Tools._PerformanceNoneLogLevel = 0;
  4735. Tools._PerformanceUserMarkLogLevel = 1;
  4736. Tools._PerformanceConsoleLogLevel = 2;
  4737. Tools._performance = window.performance;
  4738. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4739. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4740. return Tools;
  4741. })();
  4742. BABYLON.Tools = Tools;
  4743. /**
  4744. * An implementation of a loop for asynchronous functions.
  4745. */
  4746. var AsyncLoop = (function () {
  4747. /**
  4748. * Constroctor.
  4749. * @param iterations the number of iterations.
  4750. * @param _fn the function to run each iteration
  4751. * @param _successCallback the callback that will be called upon succesful execution
  4752. * @param offset starting offset.
  4753. */
  4754. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4755. if (offset === void 0) { offset = 0; }
  4756. this.iterations = iterations;
  4757. this._fn = _fn;
  4758. this._successCallback = _successCallback;
  4759. this.index = offset - 1;
  4760. this._done = false;
  4761. }
  4762. /**
  4763. * Execute the next iteration. Must be called after the last iteration was finished.
  4764. */
  4765. AsyncLoop.prototype.executeNext = function () {
  4766. if (!this._done) {
  4767. if (this.index + 1 < this.iterations) {
  4768. ++this.index;
  4769. this._fn(this);
  4770. }
  4771. else {
  4772. this.breakLoop();
  4773. }
  4774. }
  4775. };
  4776. /**
  4777. * Break the loop and run the success callback.
  4778. */
  4779. AsyncLoop.prototype.breakLoop = function () {
  4780. this._done = true;
  4781. this._successCallback();
  4782. };
  4783. /**
  4784. * Helper function
  4785. */
  4786. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4787. if (offset === void 0) { offset = 0; }
  4788. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4789. loop.executeNext();
  4790. return loop;
  4791. };
  4792. /**
  4793. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4794. * @param iterations total number of iterations
  4795. * @param syncedIterations number of synchronous iterations in each async iteration.
  4796. * @param fn the function to call each iteration.
  4797. * @param callback a success call back that will be called when iterating stops.
  4798. * @param breakFunction a break condition (optional)
  4799. * @param timeout timeout settings for the setTimeout function. default - 0.
  4800. * @constructor
  4801. */
  4802. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4803. if (timeout === void 0) { timeout = 0; }
  4804. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4805. if (breakFunction && breakFunction())
  4806. loop.breakLoop();
  4807. else {
  4808. setTimeout(function () {
  4809. for (var i = 0; i < syncedIterations; ++i) {
  4810. var iteration = (loop.index * syncedIterations) + i;
  4811. if (iteration >= iterations)
  4812. break;
  4813. fn(iteration);
  4814. if (breakFunction && breakFunction()) {
  4815. loop.breakLoop();
  4816. break;
  4817. }
  4818. }
  4819. loop.executeNext();
  4820. }, timeout);
  4821. }
  4822. }, callback);
  4823. };
  4824. return AsyncLoop;
  4825. })();
  4826. BABYLON.AsyncLoop = AsyncLoop;
  4827. })(BABYLON || (BABYLON = {}));
  4828. var BABYLON;
  4829. (function (BABYLON) {
  4830. var _DepthCullingState = (function () {
  4831. function _DepthCullingState() {
  4832. this._isDepthTestDirty = false;
  4833. this._isDepthMaskDirty = false;
  4834. this._isDepthFuncDirty = false;
  4835. this._isCullFaceDirty = false;
  4836. this._isCullDirty = false;
  4837. this._isZOffsetDirty = false;
  4838. }
  4839. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4840. get: function () {
  4841. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4842. },
  4843. enumerable: true,
  4844. configurable: true
  4845. });
  4846. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4847. get: function () {
  4848. return this._zOffset;
  4849. },
  4850. set: function (value) {
  4851. if (this._zOffset === value) {
  4852. return;
  4853. }
  4854. this._zOffset = value;
  4855. this._isZOffsetDirty = true;
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4861. get: function () {
  4862. return this._cullFace;
  4863. },
  4864. set: function (value) {
  4865. if (this._cullFace === value) {
  4866. return;
  4867. }
  4868. this._cullFace = value;
  4869. this._isCullFaceDirty = true;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4875. get: function () {
  4876. return this._cull;
  4877. },
  4878. set: function (value) {
  4879. if (this._cull === value) {
  4880. return;
  4881. }
  4882. this._cull = value;
  4883. this._isCullDirty = true;
  4884. },
  4885. enumerable: true,
  4886. configurable: true
  4887. });
  4888. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4889. get: function () {
  4890. return this._depthFunc;
  4891. },
  4892. set: function (value) {
  4893. if (this._depthFunc === value) {
  4894. return;
  4895. }
  4896. this._depthFunc = value;
  4897. this._isDepthFuncDirty = true;
  4898. },
  4899. enumerable: true,
  4900. configurable: true
  4901. });
  4902. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4903. get: function () {
  4904. return this._depthMask;
  4905. },
  4906. set: function (value) {
  4907. if (this._depthMask === value) {
  4908. return;
  4909. }
  4910. this._depthMask = value;
  4911. this._isDepthMaskDirty = true;
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4917. get: function () {
  4918. return this._depthTest;
  4919. },
  4920. set: function (value) {
  4921. if (this._depthTest === value) {
  4922. return;
  4923. }
  4924. this._depthTest = value;
  4925. this._isDepthTestDirty = true;
  4926. },
  4927. enumerable: true,
  4928. configurable: true
  4929. });
  4930. _DepthCullingState.prototype.reset = function () {
  4931. this._depthMask = true;
  4932. this._depthTest = true;
  4933. this._depthFunc = null;
  4934. this._cull = null;
  4935. this._cullFace = null;
  4936. this._zOffset = 0;
  4937. this._isDepthTestDirty = true;
  4938. this._isDepthMaskDirty = true;
  4939. this._isDepthFuncDirty = false;
  4940. this._isCullFaceDirty = false;
  4941. this._isCullDirty = false;
  4942. this._isZOffsetDirty = false;
  4943. };
  4944. _DepthCullingState.prototype.apply = function (gl) {
  4945. if (!this.isDirty) {
  4946. return;
  4947. }
  4948. // Cull
  4949. if (this._isCullDirty) {
  4950. if (this.cull) {
  4951. gl.enable(gl.CULL_FACE);
  4952. }
  4953. else {
  4954. gl.disable(gl.CULL_FACE);
  4955. }
  4956. this._isCullDirty = false;
  4957. }
  4958. // Cull face
  4959. if (this._isCullFaceDirty) {
  4960. gl.cullFace(this.cullFace);
  4961. this._isCullFaceDirty = false;
  4962. }
  4963. // Depth mask
  4964. if (this._isDepthMaskDirty) {
  4965. gl.depthMask(this.depthMask);
  4966. this._isDepthMaskDirty = false;
  4967. }
  4968. // Depth test
  4969. if (this._isDepthTestDirty) {
  4970. if (this.depthTest) {
  4971. gl.enable(gl.DEPTH_TEST);
  4972. }
  4973. else {
  4974. gl.disable(gl.DEPTH_TEST);
  4975. }
  4976. this._isDepthTestDirty = false;
  4977. }
  4978. // Depth func
  4979. if (this._isDepthFuncDirty) {
  4980. gl.depthFunc(this.depthFunc);
  4981. this._isDepthFuncDirty = false;
  4982. }
  4983. // zOffset
  4984. if (this._isZOffsetDirty) {
  4985. if (this.zOffset) {
  4986. gl.enable(gl.POLYGON_OFFSET_FILL);
  4987. gl.polygonOffset(this.zOffset, 0);
  4988. }
  4989. else {
  4990. gl.disable(gl.POLYGON_OFFSET_FILL);
  4991. }
  4992. this._isZOffsetDirty = false;
  4993. }
  4994. };
  4995. return _DepthCullingState;
  4996. })();
  4997. BABYLON._DepthCullingState = _DepthCullingState;
  4998. var _AlphaState = (function () {
  4999. function _AlphaState() {
  5000. this._isAlphaBlendDirty = false;
  5001. this._isBlendFunctionParametersDirty = false;
  5002. this._alphaBlend = false;
  5003. this._blendFunctionParameters = new Array(4);
  5004. }
  5005. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5006. get: function () {
  5007. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5008. },
  5009. enumerable: true,
  5010. configurable: true
  5011. });
  5012. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5013. get: function () {
  5014. return this._alphaBlend;
  5015. },
  5016. set: function (value) {
  5017. if (this._alphaBlend === value) {
  5018. return;
  5019. }
  5020. this._alphaBlend = value;
  5021. this._isAlphaBlendDirty = true;
  5022. },
  5023. enumerable: true,
  5024. configurable: true
  5025. });
  5026. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5027. if (this._blendFunctionParameters[0] === value0 &&
  5028. this._blendFunctionParameters[1] === value1 &&
  5029. this._blendFunctionParameters[2] === value2 &&
  5030. this._blendFunctionParameters[3] === value3) {
  5031. return;
  5032. }
  5033. this._blendFunctionParameters[0] = value0;
  5034. this._blendFunctionParameters[1] = value1;
  5035. this._blendFunctionParameters[2] = value2;
  5036. this._blendFunctionParameters[3] = value3;
  5037. this._isBlendFunctionParametersDirty = true;
  5038. };
  5039. _AlphaState.prototype.reset = function () {
  5040. this._alphaBlend = false;
  5041. this._blendFunctionParameters[0] = null;
  5042. this._blendFunctionParameters[1] = null;
  5043. this._blendFunctionParameters[2] = null;
  5044. this._blendFunctionParameters[3] = null;
  5045. this._isAlphaBlendDirty = true;
  5046. this._isBlendFunctionParametersDirty = false;
  5047. };
  5048. _AlphaState.prototype.apply = function (gl) {
  5049. if (!this.isDirty) {
  5050. return;
  5051. }
  5052. // Alpha blend
  5053. if (this._isAlphaBlendDirty) {
  5054. if (this._alphaBlend) {
  5055. gl.enable(gl.BLEND);
  5056. }
  5057. else {
  5058. gl.disable(gl.BLEND);
  5059. }
  5060. this._isAlphaBlendDirty = false;
  5061. }
  5062. // Alpha function
  5063. if (this._isBlendFunctionParametersDirty) {
  5064. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5065. this._isBlendFunctionParametersDirty = false;
  5066. }
  5067. };
  5068. return _AlphaState;
  5069. })();
  5070. BABYLON._AlphaState = _AlphaState;
  5071. var compileShader = function (gl, source, type, defines) {
  5072. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5073. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5074. gl.compileShader(shader);
  5075. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5076. throw new Error(gl.getShaderInfoLog(shader));
  5077. }
  5078. return shader;
  5079. };
  5080. var getWebGLTextureType = function (gl, type) {
  5081. var textureType = gl.UNSIGNED_BYTE;
  5082. if (type === Engine.TEXTURETYPE_FLOAT)
  5083. textureType = gl.FLOAT;
  5084. return textureType;
  5085. };
  5086. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5087. var magFilter = gl.NEAREST;
  5088. var minFilter = gl.NEAREST;
  5089. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5090. magFilter = gl.LINEAR;
  5091. if (generateMipMaps) {
  5092. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5093. }
  5094. else {
  5095. minFilter = gl.LINEAR;
  5096. }
  5097. }
  5098. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5099. magFilter = gl.LINEAR;
  5100. if (generateMipMaps) {
  5101. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5102. }
  5103. else {
  5104. minFilter = gl.LINEAR;
  5105. }
  5106. }
  5107. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5108. magFilter = gl.NEAREST;
  5109. if (generateMipMaps) {
  5110. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5111. }
  5112. else {
  5113. minFilter = gl.NEAREST;
  5114. }
  5115. }
  5116. return {
  5117. min: minFilter,
  5118. mag: magFilter
  5119. };
  5120. };
  5121. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5123. var engine = scene.getEngine();
  5124. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5125. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5126. gl.bindTexture(gl.TEXTURE_2D, texture);
  5127. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5128. texture._baseWidth = width;
  5129. texture._baseHeight = height;
  5130. texture._width = potWidth;
  5131. texture._height = potHeight;
  5132. texture.isReady = true;
  5133. processFunction(potWidth, potHeight);
  5134. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5137. if (!noMipmap && !isCompressed) {
  5138. gl.generateMipmap(gl.TEXTURE_2D);
  5139. }
  5140. gl.bindTexture(gl.TEXTURE_2D, null);
  5141. engine.resetTextureCache();
  5142. scene._removePendingData(texture);
  5143. if (onLoad) {
  5144. onLoad();
  5145. }
  5146. };
  5147. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5148. var img;
  5149. var onload = function () {
  5150. loadedImages[index] = img;
  5151. loadedImages._internalCount++;
  5152. scene._removePendingData(img);
  5153. if (loadedImages._internalCount === 6) {
  5154. onfinish(loadedImages);
  5155. }
  5156. };
  5157. var onerror = function () {
  5158. scene._removePendingData(img);
  5159. };
  5160. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5161. scene._addPendingData(img);
  5162. };
  5163. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5164. var loadedImages = [];
  5165. loadedImages._internalCount = 0;
  5166. for (var index = 0; index < 6; index++) {
  5167. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5168. }
  5169. };
  5170. var EngineCapabilities = (function () {
  5171. function EngineCapabilities() {
  5172. }
  5173. return EngineCapabilities;
  5174. })();
  5175. BABYLON.EngineCapabilities = EngineCapabilities;
  5176. /**
  5177. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5178. */
  5179. var Engine = (function () {
  5180. /**
  5181. * @constructor
  5182. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5183. * @param {boolean} [antialias] - enable antialias
  5184. * @param options - further options to be sent to the getContext function
  5185. */
  5186. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5187. var _this = this;
  5188. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5189. // Public members
  5190. this.isFullscreen = false;
  5191. this.isPointerLock = false;
  5192. this.cullBackFaces = true;
  5193. this.renderEvenInBackground = true;
  5194. // To enable/disable IDB support and avoid XHR on .manifest
  5195. this.enableOfflineSupport = true;
  5196. this.scenes = new Array();
  5197. this._windowIsBackground = false;
  5198. this._webGLVersion = "1.0";
  5199. this._drawCalls = 0;
  5200. this._renderingQueueLaunched = false;
  5201. this._activeRenderLoops = [];
  5202. // FPS
  5203. this.fpsRange = 60;
  5204. this.previousFramesDuration = [];
  5205. this.fps = 60;
  5206. this.deltaTime = 0;
  5207. // States
  5208. this._depthCullingState = new _DepthCullingState();
  5209. this._alphaState = new _AlphaState();
  5210. this._alphaMode = Engine.ALPHA_DISABLE;
  5211. // Cache
  5212. this._loadedTexturesCache = new Array();
  5213. this._maxTextureChannels = 16;
  5214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5215. this._compiledEffects = {};
  5216. this._uintIndicesCurrentlySet = false;
  5217. this.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  5218. var _this = this;
  5219. var gl = this._gl;
  5220. var texture = gl.createTexture();
  5221. scene._addPendingData(texture);
  5222. texture.isCube = true;
  5223. texture.references = 1;
  5224. texture.url = url;
  5225. var internalFormat = gl.RGBA;
  5226. switch (format) {
  5227. case Engine.TEXTUREFORMAT_ALPHA:
  5228. internalFormat = gl.ALPHA;
  5229. break;
  5230. case Engine.TEXTUREFORMAT_LUMINANCE:
  5231. internalFormat = gl.LUMINANCE;
  5232. break;
  5233. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5234. internalFormat = gl.LUMINANCE_ALPHA;
  5235. break;
  5236. case Engine.TEXTUREFORMAT_RGB:
  5237. internalFormat = gl.RGB;
  5238. break;
  5239. case Engine.TEXTUREFORMAT_RGBA:
  5240. internalFormat = gl.RGBA;
  5241. break;
  5242. }
  5243. var textureType = gl.UNSIGNED_BYTE;
  5244. if (type === Engine.TEXTURETYPE_FLOAT) {
  5245. textureType = gl.FLOAT;
  5246. }
  5247. var width = size;
  5248. var height = width;
  5249. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  5250. texture._width = width;
  5251. texture._height = height;
  5252. var onerror = function () {
  5253. scene._removePendingData(texture);
  5254. };
  5255. var internalCallback = function (data) {
  5256. var rgbeDataArrays = callback(data);
  5257. var facesIndex = [
  5258. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5259. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5260. ];
  5261. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5262. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5263. for (var index = 0; index < facesIndex.length; index++) {
  5264. var faceData = rgbeDataArrays[index];
  5265. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  5266. }
  5267. if (!noMipmap && isPot) {
  5268. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5269. }
  5270. else {
  5271. noMipmap = true;
  5272. }
  5273. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  5274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5276. }
  5277. else {
  5278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5280. }
  5281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5283. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5284. texture.isReady = true;
  5285. _this.resetTextureCache();
  5286. scene._removePendingData(texture);
  5287. };
  5288. BABYLON.Tools.LoadFile(url, function (data) {
  5289. internalCallback(data);
  5290. }, onerror, scene.database, true);
  5291. return texture;
  5292. };
  5293. this._renderingCanvas = canvas;
  5294. options = options || {};
  5295. options.antialias = antialias;
  5296. if (options.preserveDrawingBuffer === undefined) {
  5297. options.preserveDrawingBuffer = false;
  5298. }
  5299. // GL
  5300. try {
  5301. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5302. if (this._gl) {
  5303. this._webGLVersion = "2.0";
  5304. }
  5305. }
  5306. catch (e) {
  5307. }
  5308. if (!this._gl) {
  5309. try {
  5310. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5311. }
  5312. catch (e) {
  5313. throw new Error("WebGL not supported");
  5314. }
  5315. }
  5316. if (!this._gl) {
  5317. throw new Error("WebGL not supported");
  5318. }
  5319. this._onBlur = function () {
  5320. _this._windowIsBackground = true;
  5321. };
  5322. this._onFocus = function () {
  5323. _this._windowIsBackground = false;
  5324. };
  5325. window.addEventListener("blur", this._onBlur);
  5326. window.addEventListener("focus", this._onFocus);
  5327. // Viewport
  5328. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5329. this.resize();
  5330. // Caps
  5331. this._caps = new EngineCapabilities();
  5332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5333. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5334. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5335. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5336. // Infos
  5337. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5338. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5339. if (rendererInfo != null) {
  5340. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5341. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5342. }
  5343. if (!this._glVendor) {
  5344. this._glVendor = "Unknown vendor";
  5345. }
  5346. if (!this._glRenderer) {
  5347. this._glRenderer = "Unknown renderer";
  5348. }
  5349. // Extensions
  5350. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5351. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5352. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5353. 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');
  5354. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5355. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5356. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5357. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5358. this._caps.highPrecisionShaderSupported = true;
  5359. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5360. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5361. if (this._gl.getShaderPrecisionFormat) {
  5362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5364. }
  5365. // Depth buffer
  5366. this.setDepthBuffer(true);
  5367. this.setDepthFunctionToLessOrEqual();
  5368. this.setDepthWrite(true);
  5369. // Fullscreen
  5370. this._onFullscreenChange = function () {
  5371. if (document.fullscreen !== undefined) {
  5372. _this.isFullscreen = document.fullscreen;
  5373. }
  5374. else if (document.mozFullScreen !== undefined) {
  5375. _this.isFullscreen = document.mozFullScreen;
  5376. }
  5377. else if (document.webkitIsFullScreen !== undefined) {
  5378. _this.isFullscreen = document.webkitIsFullScreen;
  5379. }
  5380. else if (document.msIsFullScreen !== undefined) {
  5381. _this.isFullscreen = document.msIsFullScreen;
  5382. }
  5383. // Pointer lock
  5384. if (_this.isFullscreen && _this._pointerLockRequested) {
  5385. canvas.requestPointerLock = canvas.requestPointerLock ||
  5386. canvas.msRequestPointerLock ||
  5387. canvas.mozRequestPointerLock ||
  5388. canvas.webkitRequestPointerLock;
  5389. if (canvas.requestPointerLock) {
  5390. canvas.requestPointerLock();
  5391. }
  5392. }
  5393. };
  5394. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5395. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5396. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5397. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5398. // Pointer lock
  5399. this._onPointerLockChange = function () {
  5400. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5401. document.webkitPointerLockElement === canvas ||
  5402. document.msPointerLockElement === canvas ||
  5403. document.pointerLockElement === canvas);
  5404. };
  5405. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5406. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5407. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5408. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5409. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5410. Engine.audioEngine = new BABYLON.AudioEngine();
  5411. }
  5412. //default loading screen
  5413. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5414. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5415. }
  5416. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5417. get: function () {
  5418. return Engine._ALPHA_DISABLE;
  5419. },
  5420. enumerable: true,
  5421. configurable: true
  5422. });
  5423. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5424. get: function () {
  5425. return Engine._ALPHA_ONEONE;
  5426. },
  5427. enumerable: true,
  5428. configurable: true
  5429. });
  5430. Object.defineProperty(Engine, "ALPHA_ADD", {
  5431. get: function () {
  5432. return Engine._ALPHA_ADD;
  5433. },
  5434. enumerable: true,
  5435. configurable: true
  5436. });
  5437. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5438. get: function () {
  5439. return Engine._ALPHA_COMBINE;
  5440. },
  5441. enumerable: true,
  5442. configurable: true
  5443. });
  5444. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5445. get: function () {
  5446. return Engine._ALPHA_SUBTRACT;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5452. get: function () {
  5453. return Engine._ALPHA_MULTIPLY;
  5454. },
  5455. enumerable: true,
  5456. configurable: true
  5457. });
  5458. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5459. get: function () {
  5460. return Engine._ALPHA_MAXIMIZED;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5466. get: function () {
  5467. return Engine._DELAYLOADSTATE_NONE;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5473. get: function () {
  5474. return Engine._DELAYLOADSTATE_LOADED;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5480. get: function () {
  5481. return Engine._DELAYLOADSTATE_LOADING;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5487. get: function () {
  5488. return Engine._DELAYLOADSTATE_NOTLOADED;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5494. get: function () {
  5495. return Engine._TEXTUREFORMAT_ALPHA;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5501. get: function () {
  5502. return Engine._TEXTUREFORMAT_LUMINANCE;
  5503. },
  5504. enumerable: true,
  5505. configurable: true
  5506. });
  5507. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5508. get: function () {
  5509. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5515. get: function () {
  5516. return Engine._TEXTUREFORMAT_RGB;
  5517. },
  5518. enumerable: true,
  5519. configurable: true
  5520. });
  5521. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5522. get: function () {
  5523. return Engine._TEXTUREFORMAT_RGBA;
  5524. },
  5525. enumerable: true,
  5526. configurable: true
  5527. });
  5528. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5529. get: function () {
  5530. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5531. },
  5532. enumerable: true,
  5533. configurable: true
  5534. });
  5535. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5536. get: function () {
  5537. return Engine._TEXTURETYPE_FLOAT;
  5538. },
  5539. enumerable: true,
  5540. configurable: true
  5541. });
  5542. Object.defineProperty(Engine, "Version", {
  5543. get: function () {
  5544. return "2.4.0-alpha";
  5545. },
  5546. enumerable: true,
  5547. configurable: true
  5548. });
  5549. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5550. get: function () {
  5551. return this._webGLVersion;
  5552. },
  5553. enumerable: true,
  5554. configurable: true
  5555. });
  5556. Engine.prototype._prepareWorkingCanvas = function () {
  5557. if (this._workingCanvas) {
  5558. return;
  5559. }
  5560. this._workingCanvas = document.createElement("canvas");
  5561. this._workingContext = this._workingCanvas.getContext("2d");
  5562. };
  5563. Engine.prototype.resetTextureCache = function () {
  5564. for (var index = 0; index < this._maxTextureChannels; index++) {
  5565. this._activeTexturesCache[index] = null;
  5566. }
  5567. };
  5568. Engine.prototype.getGlInfo = function () {
  5569. return {
  5570. vendor: this._glVendor,
  5571. renderer: this._glRenderer,
  5572. version: this._glVersion
  5573. };
  5574. };
  5575. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5576. if (useScreen === void 0) { useScreen = false; }
  5577. var viewport = camera.viewport;
  5578. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5579. };
  5580. Engine.prototype.getRenderWidth = function (useScreen) {
  5581. if (useScreen === void 0) { useScreen = false; }
  5582. if (!useScreen && this._currentRenderTarget) {
  5583. return this._currentRenderTarget._width;
  5584. }
  5585. return this._renderingCanvas.width;
  5586. };
  5587. Engine.prototype.getRenderHeight = function (useScreen) {
  5588. if (useScreen === void 0) { useScreen = false; }
  5589. if (!useScreen && this._currentRenderTarget) {
  5590. return this._currentRenderTarget._height;
  5591. }
  5592. return this._renderingCanvas.height;
  5593. };
  5594. Engine.prototype.getRenderingCanvas = function () {
  5595. return this._renderingCanvas;
  5596. };
  5597. Engine.prototype.getRenderingCanvasClientRect = function () {
  5598. return this._renderingCanvas.getBoundingClientRect();
  5599. };
  5600. Engine.prototype.setHardwareScalingLevel = function (level) {
  5601. this._hardwareScalingLevel = level;
  5602. this.resize();
  5603. };
  5604. Engine.prototype.getHardwareScalingLevel = function () {
  5605. return this._hardwareScalingLevel;
  5606. };
  5607. Engine.prototype.getLoadedTexturesCache = function () {
  5608. return this._loadedTexturesCache;
  5609. };
  5610. Engine.prototype.getCaps = function () {
  5611. return this._caps;
  5612. };
  5613. Object.defineProperty(Engine.prototype, "drawCalls", {
  5614. get: function () {
  5615. return this._drawCalls;
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. // Methods
  5621. Engine.prototype.resetDrawCalls = function () {
  5622. this._drawCalls = 0;
  5623. };
  5624. Engine.prototype.setDepthFunctionToGreater = function () {
  5625. this._depthCullingState.depthFunc = this._gl.GREATER;
  5626. };
  5627. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5628. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5629. };
  5630. Engine.prototype.setDepthFunctionToLess = function () {
  5631. this._depthCullingState.depthFunc = this._gl.LESS;
  5632. };
  5633. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5634. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5635. };
  5636. /**
  5637. * stop executing a render loop function and remove it from the execution array
  5638. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5639. */
  5640. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5641. if (!renderFunction) {
  5642. this._activeRenderLoops = [];
  5643. return;
  5644. }
  5645. var index = this._activeRenderLoops.indexOf(renderFunction);
  5646. if (index >= 0) {
  5647. this._activeRenderLoops.splice(index, 1);
  5648. }
  5649. };
  5650. Engine.prototype._renderLoop = function () {
  5651. var shouldRender = true;
  5652. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5653. shouldRender = false;
  5654. }
  5655. if (shouldRender) {
  5656. // Start new frame
  5657. this.beginFrame();
  5658. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5659. var renderFunction = this._activeRenderLoops[index];
  5660. renderFunction();
  5661. }
  5662. // Present
  5663. this.endFrame();
  5664. }
  5665. if (this._activeRenderLoops.length > 0) {
  5666. // Register new frame
  5667. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5668. }
  5669. else {
  5670. this._renderingQueueLaunched = false;
  5671. }
  5672. };
  5673. /**
  5674. * Register and execute a render loop. The engine can have more than one render function.
  5675. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5676. * @example
  5677. * engine.runRenderLoop(function () {
  5678. * scene.render()
  5679. * })
  5680. */
  5681. Engine.prototype.runRenderLoop = function (renderFunction) {
  5682. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5683. return;
  5684. }
  5685. this._activeRenderLoops.push(renderFunction);
  5686. if (!this._renderingQueueLaunched) {
  5687. this._renderingQueueLaunched = true;
  5688. this._bindedRenderFunction = this._renderLoop.bind(this);
  5689. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5690. }
  5691. };
  5692. /**
  5693. * Toggle full screen mode.
  5694. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5695. */
  5696. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5697. if (this.isFullscreen) {
  5698. BABYLON.Tools.ExitFullscreen();
  5699. }
  5700. else {
  5701. this._pointerLockRequested = requestPointerLock;
  5702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5703. }
  5704. };
  5705. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5706. this.applyStates();
  5707. if (backBuffer) {
  5708. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5709. }
  5710. if (depthStencil && this._depthCullingState.depthMask) {
  5711. this._gl.clearDepth(1.0);
  5712. }
  5713. var mode = 0;
  5714. if (backBuffer) {
  5715. mode |= this._gl.COLOR_BUFFER_BIT;
  5716. }
  5717. if (depthStencil && this._depthCullingState.depthMask) {
  5718. mode |= this._gl.DEPTH_BUFFER_BIT;
  5719. }
  5720. this._gl.clear(mode);
  5721. };
  5722. /**
  5723. * Set the WebGL's viewport
  5724. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5725. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5726. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5727. */
  5728. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5729. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5730. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5731. var x = viewport.x || 0;
  5732. var y = viewport.y || 0;
  5733. this._cachedViewport = viewport;
  5734. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5735. };
  5736. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5737. this._cachedViewport = null;
  5738. this._gl.viewport(x, y, width, height);
  5739. };
  5740. Engine.prototype.beginFrame = function () {
  5741. this._measureFps();
  5742. };
  5743. Engine.prototype.endFrame = function () {
  5744. //this.flushFramebuffer();
  5745. };
  5746. /**
  5747. * resize the view according to the canvas' size.
  5748. * @example
  5749. * window.addEventListener("resize", function () {
  5750. * engine.resize();
  5751. * });
  5752. */
  5753. Engine.prototype.resize = function () {
  5754. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5755. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5756. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5757. for (var index = 0; index < this.scenes.length; index++) {
  5758. var scene = this.scenes[index];
  5759. if (scene.debugLayer.isVisible()) {
  5760. scene.debugLayer._syncPositions();
  5761. }
  5762. }
  5763. };
  5764. /**
  5765. * force a specific size of the canvas
  5766. * @param {number} width - the new canvas' width
  5767. * @param {number} height - the new canvas' height
  5768. */
  5769. Engine.prototype.setSize = function (width, height) {
  5770. this._renderingCanvas.width = width;
  5771. this._renderingCanvas.height = height;
  5772. for (var index = 0; index < this.scenes.length; index++) {
  5773. var scene = this.scenes[index];
  5774. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5775. var cam = scene.cameras[camIndex];
  5776. cam._currentRenderId = 0;
  5777. }
  5778. }
  5779. };
  5780. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5781. this._currentRenderTarget = texture;
  5782. var gl = this._gl;
  5783. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5784. if (texture.isCube) {
  5785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5786. }
  5787. else {
  5788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5789. }
  5790. this._gl.viewport(0, 0, texture._width, texture._height);
  5791. this.wipeCaches();
  5792. };
  5793. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5794. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5795. this._currentRenderTarget = null;
  5796. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5797. var gl = this._gl;
  5798. gl.bindTexture(gl.TEXTURE_2D, texture);
  5799. gl.generateMipmap(gl.TEXTURE_2D);
  5800. gl.bindTexture(gl.TEXTURE_2D, null);
  5801. }
  5802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5803. };
  5804. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5805. if (texture.generateMipMaps) {
  5806. var gl = this._gl;
  5807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5808. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5809. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5810. }
  5811. };
  5812. Engine.prototype.flushFramebuffer = function () {
  5813. this._gl.flush();
  5814. };
  5815. Engine.prototype.restoreDefaultFramebuffer = function () {
  5816. this._currentRenderTarget = null;
  5817. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5818. this.setViewport(this._cachedViewport);
  5819. this.wipeCaches();
  5820. };
  5821. // VBOs
  5822. Engine.prototype._resetVertexBufferBinding = function () {
  5823. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5824. this._cachedVertexBuffers = null;
  5825. };
  5826. Engine.prototype.createVertexBuffer = function (vertices) {
  5827. var vbo = this._gl.createBuffer();
  5828. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5829. if (vertices instanceof Float32Array) {
  5830. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5831. }
  5832. else {
  5833. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5834. }
  5835. this._resetVertexBufferBinding();
  5836. vbo.references = 1;
  5837. return vbo;
  5838. };
  5839. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5840. var vbo = this._gl.createBuffer();
  5841. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5842. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5843. this._resetVertexBufferBinding();
  5844. vbo.references = 1;
  5845. return vbo;
  5846. };
  5847. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5848. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5849. if (offset === undefined) {
  5850. offset = 0;
  5851. }
  5852. if (vertices instanceof Float32Array) {
  5853. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5854. }
  5855. else {
  5856. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5857. }
  5858. this._resetVertexBufferBinding();
  5859. };
  5860. Engine.prototype._resetIndexBufferBinding = function () {
  5861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5862. this._cachedIndexBuffer = null;
  5863. };
  5864. Engine.prototype.createIndexBuffer = function (indices) {
  5865. var vbo = this._gl.createBuffer();
  5866. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5867. // Check for 32 bits indices
  5868. var arrayBuffer;
  5869. var need32Bits = false;
  5870. if (this._caps.uintIndices) {
  5871. for (var index = 0; index < indices.length; index++) {
  5872. if (indices[index] > 65535) {
  5873. need32Bits = true;
  5874. break;
  5875. }
  5876. }
  5877. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5878. }
  5879. else {
  5880. arrayBuffer = new Uint16Array(indices);
  5881. }
  5882. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5883. this._resetIndexBufferBinding();
  5884. vbo.references = 1;
  5885. vbo.is32Bits = need32Bits;
  5886. return vbo;
  5887. };
  5888. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5889. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5890. this._cachedVertexBuffers = vertexBuffer;
  5891. this._cachedEffectForVertexBuffers = effect;
  5892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5893. var offset = 0;
  5894. for (var index = 0; index < vertexDeclaration.length; index++) {
  5895. var order = effect.getAttributeLocation(index);
  5896. if (order >= 0) {
  5897. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5898. }
  5899. offset += vertexDeclaration[index] * 4;
  5900. }
  5901. }
  5902. if (this._cachedIndexBuffer !== indexBuffer) {
  5903. this._cachedIndexBuffer = indexBuffer;
  5904. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5905. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5906. }
  5907. };
  5908. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5909. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5910. this._cachedVertexBuffers = vertexBuffers;
  5911. this._cachedEffectForVertexBuffers = effect;
  5912. var attributes = effect.getAttributesNames();
  5913. for (var index = 0; index < attributes.length; index++) {
  5914. var order = effect.getAttributeLocation(index);
  5915. if (order >= 0) {
  5916. var vertexBuffer = vertexBuffers[attributes[index]];
  5917. if (!vertexBuffer) {
  5918. continue;
  5919. }
  5920. var stride = vertexBuffer.getStrideSize();
  5921. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5922. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5923. }
  5924. }
  5925. }
  5926. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5927. this._cachedIndexBuffer = indexBuffer;
  5928. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5929. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5930. }
  5931. };
  5932. Engine.prototype._releaseBuffer = function (buffer) {
  5933. buffer.references--;
  5934. if (buffer.references === 0) {
  5935. this._gl.deleteBuffer(buffer);
  5936. return true;
  5937. }
  5938. return false;
  5939. };
  5940. Engine.prototype.createInstancesBuffer = function (capacity) {
  5941. var buffer = this._gl.createBuffer();
  5942. buffer.capacity = capacity;
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5944. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5945. return buffer;
  5946. };
  5947. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5948. this._gl.deleteBuffer(buffer);
  5949. };
  5950. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5951. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5952. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5953. for (var index = 0; index < 4; index++) {
  5954. var offsetLocation = offsetLocations[index];
  5955. this._gl.enableVertexAttribArray(offsetLocation);
  5956. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5957. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5958. }
  5959. };
  5960. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5962. for (var index = 0; index < 4; index++) {
  5963. var offsetLocation = offsetLocations[index];
  5964. this._gl.disableVertexAttribArray(offsetLocation);
  5965. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5966. }
  5967. };
  5968. Engine.prototype.applyStates = function () {
  5969. this._depthCullingState.apply(this._gl);
  5970. this._alphaState.apply(this._gl);
  5971. };
  5972. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5973. // Apply states
  5974. this.applyStates();
  5975. this._drawCalls++;
  5976. // Render
  5977. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5978. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5979. if (instancesCount) {
  5980. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5981. return;
  5982. }
  5983. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5984. };
  5985. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5986. // Apply states
  5987. this.applyStates();
  5988. this._drawCalls++;
  5989. if (instancesCount) {
  5990. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5991. return;
  5992. }
  5993. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5994. };
  5995. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5996. // Apply states
  5997. this.applyStates();
  5998. this._drawCalls++;
  5999. if (instancesCount) {
  6000. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6001. return;
  6002. }
  6003. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6004. };
  6005. // Shaders
  6006. Engine.prototype._releaseEffect = function (effect) {
  6007. if (this._compiledEffects[effect._key]) {
  6008. delete this._compiledEffects[effect._key];
  6009. if (effect.getProgram()) {
  6010. this._gl.deleteProgram(effect.getProgram());
  6011. }
  6012. }
  6013. };
  6014. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6015. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6016. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6017. var name = vertex + "+" + fragment + "@" + defines;
  6018. if (this._compiledEffects[name]) {
  6019. return this._compiledEffects[name];
  6020. }
  6021. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6022. effect._key = name;
  6023. this._compiledEffects[name] = effect;
  6024. return effect;
  6025. };
  6026. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6027. if (uniformsNames === void 0) { uniformsNames = []; }
  6028. if (samplers === void 0) { samplers = []; }
  6029. if (defines === void 0) { defines = ""; }
  6030. return this.createEffect({
  6031. vertex: "particles",
  6032. fragmentElement: fragmentName
  6033. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6034. };
  6035. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6036. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6037. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6038. var shaderProgram = this._gl.createProgram();
  6039. this._gl.attachShader(shaderProgram, vertexShader);
  6040. this._gl.attachShader(shaderProgram, fragmentShader);
  6041. this._gl.linkProgram(shaderProgram);
  6042. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6043. if (!linked) {
  6044. var error = this._gl.getProgramInfoLog(shaderProgram);
  6045. if (error) {
  6046. throw new Error(error);
  6047. }
  6048. }
  6049. this._gl.deleteShader(vertexShader);
  6050. this._gl.deleteShader(fragmentShader);
  6051. return shaderProgram;
  6052. };
  6053. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6054. var results = [];
  6055. for (var index = 0; index < uniformsNames.length; index++) {
  6056. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6057. }
  6058. return results;
  6059. };
  6060. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6061. var results = [];
  6062. for (var index = 0; index < attributesNames.length; index++) {
  6063. try {
  6064. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6065. }
  6066. catch (e) {
  6067. results.push(-1);
  6068. }
  6069. }
  6070. return results;
  6071. };
  6072. Engine.prototype.enableEffect = function (effect) {
  6073. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6074. if (effect && effect.onBind) {
  6075. effect.onBind(effect);
  6076. }
  6077. return;
  6078. }
  6079. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6080. // Use program
  6081. this._gl.useProgram(effect.getProgram());
  6082. for (var i in this._vertexAttribArrays) {
  6083. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6084. continue;
  6085. }
  6086. this._vertexAttribArrays[i] = false;
  6087. this._gl.disableVertexAttribArray(i);
  6088. }
  6089. var attributesCount = effect.getAttributesCount();
  6090. for (var index = 0; index < attributesCount; index++) {
  6091. // Attributes
  6092. var order = effect.getAttributeLocation(index);
  6093. if (order >= 0) {
  6094. this._vertexAttribArrays[order] = true;
  6095. this._gl.enableVertexAttribArray(order);
  6096. }
  6097. }
  6098. this._currentEffect = effect;
  6099. if (effect.onBind) {
  6100. effect.onBind(effect);
  6101. }
  6102. };
  6103. Engine.prototype.setArray = function (uniform, array) {
  6104. if (!uniform)
  6105. return;
  6106. this._gl.uniform1fv(uniform, array);
  6107. };
  6108. Engine.prototype.setArray2 = function (uniform, array) {
  6109. if (!uniform || array.length % 2 !== 0)
  6110. return;
  6111. this._gl.uniform2fv(uniform, array);
  6112. };
  6113. Engine.prototype.setArray3 = function (uniform, array) {
  6114. if (!uniform || array.length % 3 !== 0)
  6115. return;
  6116. this._gl.uniform3fv(uniform, array);
  6117. };
  6118. Engine.prototype.setArray4 = function (uniform, array) {
  6119. if (!uniform || array.length % 4 !== 0)
  6120. return;
  6121. this._gl.uniform4fv(uniform, array);
  6122. };
  6123. Engine.prototype.setMatrices = function (uniform, matrices) {
  6124. if (!uniform)
  6125. return;
  6126. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6127. };
  6128. Engine.prototype.setMatrix = function (uniform, matrix) {
  6129. if (!uniform)
  6130. return;
  6131. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6132. };
  6133. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6134. if (!uniform)
  6135. return;
  6136. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6137. };
  6138. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6139. if (!uniform)
  6140. return;
  6141. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6142. };
  6143. Engine.prototype.setFloat = function (uniform, value) {
  6144. if (!uniform)
  6145. return;
  6146. this._gl.uniform1f(uniform, value);
  6147. };
  6148. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6149. if (!uniform)
  6150. return;
  6151. this._gl.uniform2f(uniform, x, y);
  6152. };
  6153. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6154. if (!uniform)
  6155. return;
  6156. this._gl.uniform3f(uniform, x, y, z);
  6157. };
  6158. Engine.prototype.setBool = function (uniform, bool) {
  6159. if (!uniform)
  6160. return;
  6161. this._gl.uniform1i(uniform, bool);
  6162. };
  6163. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6164. if (!uniform)
  6165. return;
  6166. this._gl.uniform4f(uniform, x, y, z, w);
  6167. };
  6168. Engine.prototype.setColor3 = function (uniform, color3) {
  6169. if (!uniform)
  6170. return;
  6171. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6172. };
  6173. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6174. if (!uniform)
  6175. return;
  6176. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6177. };
  6178. // States
  6179. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6180. if (zOffset === void 0) { zOffset = 0; }
  6181. if (reverseSide === void 0) { reverseSide = false; }
  6182. // Culling
  6183. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6184. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6185. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6186. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6187. if (culling) {
  6188. this._depthCullingState.cullFace = cullFace;
  6189. this._depthCullingState.cull = true;
  6190. }
  6191. else {
  6192. this._depthCullingState.cull = false;
  6193. }
  6194. }
  6195. // Z offset
  6196. this._depthCullingState.zOffset = zOffset;
  6197. };
  6198. Engine.prototype.setDepthBuffer = function (enable) {
  6199. this._depthCullingState.depthTest = enable;
  6200. };
  6201. Engine.prototype.getDepthWrite = function () {
  6202. return this._depthCullingState.depthMask;
  6203. };
  6204. Engine.prototype.setDepthWrite = function (enable) {
  6205. this._depthCullingState.depthMask = enable;
  6206. };
  6207. Engine.prototype.setColorWrite = function (enable) {
  6208. this._gl.colorMask(enable, enable, enable, enable);
  6209. };
  6210. Engine.prototype.setAlphaMode = function (mode) {
  6211. if (this._alphaMode === mode) {
  6212. return;
  6213. }
  6214. switch (mode) {
  6215. case Engine.ALPHA_DISABLE:
  6216. this.setDepthWrite(true);
  6217. this._alphaState.alphaBlend = false;
  6218. break;
  6219. case Engine.ALPHA_COMBINE:
  6220. this.setDepthWrite(false);
  6221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6222. this._alphaState.alphaBlend = true;
  6223. break;
  6224. case Engine.ALPHA_ONEONE:
  6225. this.setDepthWrite(false);
  6226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6227. this._alphaState.alphaBlend = true;
  6228. break;
  6229. case Engine.ALPHA_ADD:
  6230. this.setDepthWrite(false);
  6231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6232. this._alphaState.alphaBlend = true;
  6233. break;
  6234. case Engine.ALPHA_SUBTRACT:
  6235. this.setDepthWrite(false);
  6236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6237. this._alphaState.alphaBlend = true;
  6238. break;
  6239. case Engine.ALPHA_MULTIPLY:
  6240. this.setDepthWrite(false);
  6241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6242. this._alphaState.alphaBlend = true;
  6243. break;
  6244. case Engine.ALPHA_MAXIMIZED:
  6245. this.setDepthWrite(false);
  6246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6247. this._alphaState.alphaBlend = true;
  6248. break;
  6249. }
  6250. this._alphaMode = mode;
  6251. };
  6252. Engine.prototype.getAlphaMode = function () {
  6253. return this._alphaMode;
  6254. };
  6255. Engine.prototype.setAlphaTesting = function (enable) {
  6256. this._alphaTest = enable;
  6257. };
  6258. Engine.prototype.getAlphaTesting = function () {
  6259. return this._alphaTest;
  6260. };
  6261. // Textures
  6262. Engine.prototype.wipeCaches = function () {
  6263. this.resetTextureCache();
  6264. this._currentEffect = null;
  6265. this._depthCullingState.reset();
  6266. this._alphaState.reset();
  6267. this._cachedVertexBuffers = null;
  6268. this._cachedIndexBuffer = null;
  6269. this._cachedEffectForVertexBuffers = null;
  6270. };
  6271. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6272. var gl = this._gl;
  6273. gl.bindTexture(gl.TEXTURE_2D, texture);
  6274. var magFilter = gl.NEAREST;
  6275. var minFilter = gl.NEAREST;
  6276. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6277. magFilter = gl.LINEAR;
  6278. minFilter = gl.LINEAR;
  6279. }
  6280. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6281. magFilter = gl.LINEAR;
  6282. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6283. }
  6284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6286. gl.bindTexture(gl.TEXTURE_2D, null);
  6287. texture.samplingMode = samplingMode;
  6288. };
  6289. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6290. var _this = this;
  6291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6292. if (onLoad === void 0) { onLoad = null; }
  6293. if (onError === void 0) { onError = null; }
  6294. if (buffer === void 0) { buffer = null; }
  6295. var texture = this._gl.createTexture();
  6296. var extension;
  6297. var fromData = false;
  6298. if (url.substr(0, 5) === "data:") {
  6299. fromData = true;
  6300. }
  6301. if (!fromData)
  6302. extension = url.substr(url.length - 4, 4).toLowerCase();
  6303. else {
  6304. var oldUrl = url;
  6305. fromData = oldUrl.split(':');
  6306. url = oldUrl;
  6307. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6308. }
  6309. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6310. var isTGA = (extension === ".tga");
  6311. scene._addPendingData(texture);
  6312. texture.url = url;
  6313. texture.noMipmap = noMipmap;
  6314. texture.references = 1;
  6315. texture.samplingMode = samplingMode;
  6316. this._loadedTexturesCache.push(texture);
  6317. var onerror = function () {
  6318. scene._removePendingData(texture);
  6319. if (onError) {
  6320. onError();
  6321. }
  6322. };
  6323. var callback;
  6324. if (isTGA) {
  6325. callback = function (arrayBuffer) {
  6326. var data = new Uint8Array(arrayBuffer);
  6327. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6328. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6329. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6330. }, onLoad, samplingMode);
  6331. };
  6332. if (!(fromData instanceof Array))
  6333. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6334. callback(arrayBuffer);
  6335. }, onerror, scene.database, true);
  6336. else
  6337. callback(buffer);
  6338. }
  6339. else if (isDDS) {
  6340. callback = function (data) {
  6341. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6342. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6343. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6344. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6345. }, onLoad, samplingMode);
  6346. };
  6347. if (!(fromData instanceof Array))
  6348. BABYLON.Tools.LoadFile(url, function (data) {
  6349. callback(data);
  6350. }, onerror, scene.database, true);
  6351. else
  6352. callback(buffer);
  6353. }
  6354. else {
  6355. var onload = function (img) {
  6356. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6357. var isPot = (img.width === potWidth && img.height === potHeight);
  6358. if (!isPot) {
  6359. _this._prepareWorkingCanvas();
  6360. _this._workingCanvas.width = potWidth;
  6361. _this._workingCanvas.height = potHeight;
  6362. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6363. _this._workingContext.imageSmoothingEnabled = false;
  6364. _this._workingContext.mozImageSmoothingEnabled = false;
  6365. _this._workingContext.oImageSmoothingEnabled = false;
  6366. _this._workingContext.webkitImageSmoothingEnabled = false;
  6367. _this._workingContext.msImageSmoothingEnabled = false;
  6368. }
  6369. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6370. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6371. _this._workingContext.imageSmoothingEnabled = true;
  6372. _this._workingContext.mozImageSmoothingEnabled = true;
  6373. _this._workingContext.oImageSmoothingEnabled = true;
  6374. _this._workingContext.webkitImageSmoothingEnabled = true;
  6375. _this._workingContext.msImageSmoothingEnabled = true;
  6376. }
  6377. }
  6378. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6379. }, onLoad, samplingMode);
  6380. };
  6381. if (!(fromData instanceof Array))
  6382. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6383. else
  6384. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6385. }
  6386. return texture;
  6387. };
  6388. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6389. if (compression === void 0) { compression = null; }
  6390. var internalFormat = this._gl.RGBA;
  6391. switch (format) {
  6392. case Engine.TEXTUREFORMAT_ALPHA:
  6393. internalFormat = this._gl.ALPHA;
  6394. break;
  6395. case Engine.TEXTUREFORMAT_LUMINANCE:
  6396. internalFormat = this._gl.LUMINANCE;
  6397. break;
  6398. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6399. internalFormat = this._gl.LUMINANCE_ALPHA;
  6400. break;
  6401. case Engine.TEXTUREFORMAT_RGB:
  6402. internalFormat = this._gl.RGB;
  6403. break;
  6404. case Engine.TEXTUREFORMAT_RGBA:
  6405. internalFormat = this._gl.RGBA;
  6406. break;
  6407. }
  6408. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6409. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6410. if (compression) {
  6411. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6412. }
  6413. else {
  6414. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6415. }
  6416. if (texture.generateMipMaps) {
  6417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6418. }
  6419. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6420. this.resetTextureCache();
  6421. texture.isReady = true;
  6422. };
  6423. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6424. if (compression === void 0) { compression = null; }
  6425. var texture = this._gl.createTexture();
  6426. texture._baseWidth = width;
  6427. texture._baseHeight = height;
  6428. texture._width = width;
  6429. texture._height = height;
  6430. texture.references = 1;
  6431. this.updateRawTexture(texture, data, format, invertY, compression);
  6432. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6433. // Filters
  6434. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6435. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6436. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6437. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6438. texture.samplingMode = samplingMode;
  6439. this._loadedTexturesCache.push(texture);
  6440. return texture;
  6441. };
  6442. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6443. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6444. var texture = this._gl.createTexture();
  6445. texture._baseWidth = width;
  6446. texture._baseHeight = height;
  6447. if (forceExponantOfTwo) {
  6448. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6449. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6450. }
  6451. this.resetTextureCache();
  6452. texture._width = width;
  6453. texture._height = height;
  6454. texture.isReady = false;
  6455. texture.generateMipMaps = generateMipMaps;
  6456. texture.references = 1;
  6457. texture.samplingMode = samplingMode;
  6458. this.updateTextureSamplingMode(samplingMode, texture);
  6459. this._loadedTexturesCache.push(texture);
  6460. return texture;
  6461. };
  6462. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6463. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6464. if (texture.isCube) {
  6465. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6466. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6467. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6468. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6469. }
  6470. else {
  6471. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6472. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6473. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6474. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6475. }
  6476. };
  6477. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6478. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6479. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6480. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6481. if (texture.generateMipMaps) {
  6482. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6483. }
  6484. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6485. this.resetTextureCache();
  6486. texture.isReady = true;
  6487. };
  6488. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6489. if (texture._isDisabled) {
  6490. return;
  6491. }
  6492. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6493. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6494. try {
  6495. // Testing video texture support
  6496. if (this._videoTextureSupported === undefined) {
  6497. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6498. if (this._gl.getError() !== 0) {
  6499. this._videoTextureSupported = false;
  6500. }
  6501. else {
  6502. this._videoTextureSupported = true;
  6503. }
  6504. }
  6505. // Copy video through the current working canvas if video texture is not supported
  6506. if (!this._videoTextureSupported) {
  6507. if (!texture._workingCanvas) {
  6508. texture._workingCanvas = document.createElement("canvas");
  6509. texture._workingContext = texture._workingCanvas.getContext("2d");
  6510. texture._workingCanvas.width = texture._width;
  6511. texture._workingCanvas.height = texture._height;
  6512. }
  6513. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6514. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6515. }
  6516. else {
  6517. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6518. }
  6519. if (texture.generateMipMaps) {
  6520. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6521. }
  6522. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6523. this.resetTextureCache();
  6524. texture.isReady = true;
  6525. }
  6526. catch (ex) {
  6527. // Something unexpected
  6528. // Let's disable the texture
  6529. texture._isDisabled = true;
  6530. }
  6531. };
  6532. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6533. // old version had a "generateMipMaps" arg instead of options.
  6534. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6535. // in the same way, generateDepthBuffer is defaulted to true
  6536. var generateMipMaps = false;
  6537. var generateDepthBuffer = true;
  6538. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6539. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6540. if (options !== undefined) {
  6541. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6542. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6543. type = options.type === undefined ? type : options.type;
  6544. if (options.samplingMode !== undefined) {
  6545. samplingMode = options.samplingMode;
  6546. }
  6547. if (type === Engine.TEXTURETYPE_FLOAT) {
  6548. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6549. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6550. }
  6551. }
  6552. var gl = this._gl;
  6553. var texture = gl.createTexture();
  6554. gl.bindTexture(gl.TEXTURE_2D, texture);
  6555. var width = size.width || size;
  6556. var height = size.height || size;
  6557. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6558. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6559. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6560. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6561. }
  6562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6566. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6567. var depthBuffer;
  6568. // Create the depth buffer
  6569. if (generateDepthBuffer) {
  6570. depthBuffer = gl.createRenderbuffer();
  6571. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6572. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6573. }
  6574. // Create the framebuffer
  6575. var framebuffer = gl.createFramebuffer();
  6576. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6577. if (generateDepthBuffer) {
  6578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6579. }
  6580. if (generateMipMaps) {
  6581. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6582. }
  6583. // Unbind
  6584. gl.bindTexture(gl.TEXTURE_2D, null);
  6585. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6586. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6587. texture._framebuffer = framebuffer;
  6588. if (generateDepthBuffer) {
  6589. texture._depthBuffer = depthBuffer;
  6590. }
  6591. texture._width = width;
  6592. texture._height = height;
  6593. texture.isReady = true;
  6594. texture.generateMipMaps = generateMipMaps;
  6595. texture.references = 1;
  6596. texture.samplingMode = samplingMode;
  6597. this.resetTextureCache();
  6598. this._loadedTexturesCache.push(texture);
  6599. return texture;
  6600. };
  6601. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6602. var gl = this._gl;
  6603. var texture = gl.createTexture();
  6604. var generateMipMaps = true;
  6605. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6606. if (options !== undefined) {
  6607. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6608. if (options.samplingMode !== undefined) {
  6609. samplingMode = options.samplingMode;
  6610. }
  6611. }
  6612. texture.isCube = true;
  6613. texture.references = 1;
  6614. texture.generateMipMaps = generateMipMaps;
  6615. texture.references = 1;
  6616. texture.samplingMode = samplingMode;
  6617. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6618. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6619. for (var face = 0; face < 6; face++) {
  6620. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6621. }
  6622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6626. // Create the depth buffer
  6627. var depthBuffer = gl.createRenderbuffer();
  6628. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6629. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6630. // Create the framebuffer
  6631. var framebuffer = gl.createFramebuffer();
  6632. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6633. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6634. // Mipmaps
  6635. if (texture.generateMipMaps) {
  6636. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6637. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6638. }
  6639. // Unbind
  6640. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6641. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6642. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6643. texture._framebuffer = framebuffer;
  6644. texture._depthBuffer = depthBuffer;
  6645. this.resetTextureCache();
  6646. texture._width = size;
  6647. texture._height = size;
  6648. texture.isReady = true;
  6649. return texture;
  6650. };
  6651. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6652. var _this = this;
  6653. var gl = this._gl;
  6654. var texture = gl.createTexture();
  6655. texture.isCube = true;
  6656. texture.url = rootUrl;
  6657. texture.references = 1;
  6658. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6659. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6660. if (isDDS) {
  6661. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6662. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6663. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6664. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6665. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6666. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6667. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6668. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6669. }
  6670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6674. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6675. _this.resetTextureCache();
  6676. texture._width = info.width;
  6677. texture._height = info.height;
  6678. texture.isReady = true;
  6679. }, null, null, true);
  6680. }
  6681. else {
  6682. cascadeLoad(rootUrl, scene, function (imgs) {
  6683. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6684. var height = width;
  6685. _this._prepareWorkingCanvas();
  6686. _this._workingCanvas.width = width;
  6687. _this._workingCanvas.height = height;
  6688. var faces = [
  6689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6691. ];
  6692. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6694. for (var index = 0; index < faces.length; index++) {
  6695. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6696. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6697. }
  6698. if (!noMipmap) {
  6699. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6700. }
  6701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6705. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6706. _this.resetTextureCache();
  6707. texture._width = width;
  6708. texture._height = height;
  6709. texture.isReady = true;
  6710. }, files);
  6711. }
  6712. return texture;
  6713. };
  6714. Engine.prototype._releaseTexture = function (texture) {
  6715. var gl = this._gl;
  6716. if (texture._framebuffer) {
  6717. gl.deleteFramebuffer(texture._framebuffer);
  6718. }
  6719. if (texture._depthBuffer) {
  6720. gl.deleteRenderbuffer(texture._depthBuffer);
  6721. }
  6722. gl.deleteTexture(texture);
  6723. // Unbind channels
  6724. this.unbindAllTextures();
  6725. var index = this._loadedTexturesCache.indexOf(texture);
  6726. if (index !== -1) {
  6727. this._loadedTexturesCache.splice(index, 1);
  6728. }
  6729. };
  6730. Engine.prototype.bindSamplers = function (effect) {
  6731. this._gl.useProgram(effect.getProgram());
  6732. var samplers = effect.getSamplers();
  6733. for (var index = 0; index < samplers.length; index++) {
  6734. var uniform = effect.getUniform(samplers[index]);
  6735. this._gl.uniform1i(uniform, index);
  6736. }
  6737. this._currentEffect = null;
  6738. };
  6739. Engine.prototype._bindTexture = function (channel, texture) {
  6740. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6741. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6742. this._activeTexturesCache[channel] = null;
  6743. };
  6744. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6745. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6746. };
  6747. Engine.prototype.unbindAllTextures = function () {
  6748. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6749. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6750. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6751. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6752. this._activeTexturesCache[channel] = null;
  6753. }
  6754. };
  6755. Engine.prototype.setTexture = function (channel, texture) {
  6756. if (channel < 0) {
  6757. return;
  6758. }
  6759. // Not ready?
  6760. if (!texture || !texture.isReady()) {
  6761. if (this._activeTexturesCache[channel] != null) {
  6762. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6763. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6764. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6765. this._activeTexturesCache[channel] = null;
  6766. }
  6767. return;
  6768. }
  6769. // Video
  6770. var alreadyActivated = false;
  6771. if (texture instanceof BABYLON.VideoTexture) {
  6772. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6773. alreadyActivated = true;
  6774. texture.update();
  6775. }
  6776. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6777. texture.delayLoad();
  6778. return;
  6779. }
  6780. if (this._activeTexturesCache[channel] === texture) {
  6781. return;
  6782. }
  6783. this._activeTexturesCache[channel] = texture;
  6784. var internalTexture = texture.getInternalTexture();
  6785. if (!alreadyActivated) {
  6786. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6787. }
  6788. if (internalTexture.isCube) {
  6789. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6790. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6791. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6792. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6793. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6794. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6795. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6796. }
  6797. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6798. }
  6799. else {
  6800. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6801. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6802. internalTexture._cachedWrapU = texture.wrapU;
  6803. switch (texture.wrapU) {
  6804. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6806. break;
  6807. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6808. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6809. break;
  6810. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6811. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6812. break;
  6813. }
  6814. }
  6815. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6816. internalTexture._cachedWrapV = texture.wrapV;
  6817. switch (texture.wrapV) {
  6818. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6820. break;
  6821. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6822. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6823. break;
  6824. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6826. break;
  6827. }
  6828. }
  6829. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6830. }
  6831. };
  6832. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6833. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6834. var value = texture.anisotropicFilteringLevel;
  6835. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6836. value = 1;
  6837. }
  6838. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6839. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6840. texture._cachedAnisotropicFilteringLevel = value;
  6841. }
  6842. };
  6843. Engine.prototype.readPixels = function (x, y, width, height) {
  6844. var data = new Uint8Array(height * width * 4);
  6845. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6846. return data;
  6847. };
  6848. Engine.prototype.releaseInternalTexture = function (texture) {
  6849. if (!texture) {
  6850. return;
  6851. }
  6852. texture.references--;
  6853. // Final reference ?
  6854. if (texture.references === 0) {
  6855. var texturesCache = this.getLoadedTexturesCache();
  6856. var index = texturesCache.indexOf(texture);
  6857. if (index > -1) {
  6858. texturesCache.splice(index, 1);
  6859. }
  6860. this._releaseTexture(texture);
  6861. }
  6862. };
  6863. // Dispose
  6864. Engine.prototype.dispose = function () {
  6865. this.hideLoadingUI();
  6866. this.stopRenderLoop();
  6867. // Release scenes
  6868. while (this.scenes.length) {
  6869. this.scenes[0].dispose();
  6870. }
  6871. // Release audio engine
  6872. Engine.audioEngine.dispose();
  6873. // Release effects
  6874. for (var name in this._compiledEffects) {
  6875. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6876. }
  6877. // Unbind
  6878. for (var i in this._vertexAttribArrays) {
  6879. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6880. continue;
  6881. }
  6882. this._gl.disableVertexAttribArray(i);
  6883. }
  6884. this._gl = null;
  6885. // Events
  6886. window.removeEventListener("blur", this._onBlur);
  6887. window.removeEventListener("focus", this._onFocus);
  6888. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6889. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6890. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6891. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6892. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6893. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6894. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6895. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6896. };
  6897. // Loading screen
  6898. Engine.prototype.displayLoadingUI = function () {
  6899. this._loadingScreen.displayLoadingUI();
  6900. };
  6901. Engine.prototype.hideLoadingUI = function () {
  6902. this._loadingScreen.hideLoadingUI();
  6903. };
  6904. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6905. get: function () {
  6906. return this._loadingScreen;
  6907. },
  6908. set: function (loadingScreen) {
  6909. this._loadingScreen = loadingScreen;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6915. set: function (text) {
  6916. this._loadingScreen.loadingUIText = text;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6922. set: function (color) {
  6923. this._loadingScreen.loadingUIBackgroundColor = color;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. // FPS
  6929. Engine.prototype.getFps = function () {
  6930. return this.fps;
  6931. };
  6932. Engine.prototype.getDeltaTime = function () {
  6933. return this.deltaTime;
  6934. };
  6935. Engine.prototype._measureFps = function () {
  6936. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6937. var length = this.previousFramesDuration.length;
  6938. if (length >= 2) {
  6939. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6940. }
  6941. if (length >= this.fpsRange) {
  6942. if (length > this.fpsRange) {
  6943. this.previousFramesDuration.splice(0, 1);
  6944. length = this.previousFramesDuration.length;
  6945. }
  6946. var sum = 0;
  6947. for (var id = 0; id < length - 1; id++) {
  6948. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6949. }
  6950. this.fps = 1000.0 / (sum / (length - 1));
  6951. }
  6952. };
  6953. // Statics
  6954. Engine.isSupported = function () {
  6955. try {
  6956. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6957. if (navigator.isCocoonJS) {
  6958. return true;
  6959. }
  6960. var tempcanvas = document.createElement("canvas");
  6961. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6962. return gl != null && !!window.WebGLRenderingContext;
  6963. }
  6964. catch (e) {
  6965. return false;
  6966. }
  6967. };
  6968. // Const statics
  6969. Engine._ALPHA_DISABLE = 0;
  6970. Engine._ALPHA_ADD = 1;
  6971. Engine._ALPHA_COMBINE = 2;
  6972. Engine._ALPHA_SUBTRACT = 3;
  6973. Engine._ALPHA_MULTIPLY = 4;
  6974. Engine._ALPHA_MAXIMIZED = 5;
  6975. Engine._ALPHA_ONEONE = 6;
  6976. Engine._DELAYLOADSTATE_NONE = 0;
  6977. Engine._DELAYLOADSTATE_LOADED = 1;
  6978. Engine._DELAYLOADSTATE_LOADING = 2;
  6979. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6980. Engine._TEXTUREFORMAT_ALPHA = 0;
  6981. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6982. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6983. Engine._TEXTUREFORMAT_RGB = 4;
  6984. Engine._TEXTUREFORMAT_RGBA = 5;
  6985. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6986. Engine._TEXTURETYPE_FLOAT = 1;
  6987. // Updatable statics so stick with vars here
  6988. Engine.Epsilon = 0.001;
  6989. Engine.CollisionsEpsilon = 0.001;
  6990. Engine.CodeRepository = "src/";
  6991. Engine.ShadersRepository = "src/Shaders/";
  6992. return Engine;
  6993. })();
  6994. BABYLON.Engine = Engine;
  6995. })(BABYLON || (BABYLON = {}));
  6996. var BABYLON;
  6997. (function (BABYLON) {
  6998. /**
  6999. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7000. */
  7001. var Node = (function () {
  7002. /**
  7003. * @constructor
  7004. * @param {string} name - the name and id to be given to this node
  7005. * @param {BABYLON.Scene} the scene this node will be added to
  7006. */
  7007. function Node(name, scene) {
  7008. this.state = "";
  7009. this.animations = new Array();
  7010. this._ranges = {};
  7011. this._childrenFlag = -1;
  7012. this._isEnabled = true;
  7013. this._isReady = true;
  7014. this._currentRenderId = -1;
  7015. this._parentRenderId = -1;
  7016. this.name = name;
  7017. this.id = name;
  7018. this._scene = scene;
  7019. this._initCache();
  7020. }
  7021. Node.prototype.getScene = function () {
  7022. return this._scene;
  7023. };
  7024. Node.prototype.getEngine = function () {
  7025. return this._scene.getEngine();
  7026. };
  7027. // override it in derived class
  7028. Node.prototype.getWorldMatrix = function () {
  7029. return BABYLON.Matrix.Identity();
  7030. };
  7031. // override it in derived class if you add new variables to the cache
  7032. // and call the parent class method
  7033. Node.prototype._initCache = function () {
  7034. this._cache = {};
  7035. this._cache.parent = undefined;
  7036. };
  7037. Node.prototype.updateCache = function (force) {
  7038. if (!force && this.isSynchronized())
  7039. return;
  7040. this._cache.parent = this.parent;
  7041. this._updateCache();
  7042. };
  7043. // override it in derived class if you add new variables to the cache
  7044. // and call the parent class method if !ignoreParentClass
  7045. Node.prototype._updateCache = function (ignoreParentClass) {
  7046. };
  7047. // override it in derived class if you add new variables to the cache
  7048. Node.prototype._isSynchronized = function () {
  7049. return true;
  7050. };
  7051. Node.prototype._markSyncedWithParent = function () {
  7052. this._parentRenderId = this.parent._currentRenderId;
  7053. };
  7054. Node.prototype.isSynchronizedWithParent = function () {
  7055. if (!this.parent) {
  7056. return true;
  7057. }
  7058. if (this._parentRenderId !== this.parent._currentRenderId) {
  7059. return false;
  7060. }
  7061. return this.parent.isSynchronized();
  7062. };
  7063. Node.prototype.isSynchronized = function (updateCache) {
  7064. var check = this.hasNewParent();
  7065. check = check || !this.isSynchronizedWithParent();
  7066. check = check || !this._isSynchronized();
  7067. if (updateCache)
  7068. this.updateCache(true);
  7069. return !check;
  7070. };
  7071. Node.prototype.hasNewParent = function (update) {
  7072. if (this._cache.parent === this.parent)
  7073. return false;
  7074. if (update)
  7075. this._cache.parent = this.parent;
  7076. return true;
  7077. };
  7078. /**
  7079. * Is this node ready to be used/rendered
  7080. * @return {boolean} is it ready
  7081. */
  7082. Node.prototype.isReady = function () {
  7083. return this._isReady;
  7084. };
  7085. /**
  7086. * Is this node enabled.
  7087. * If the node has a parent and is enabled, the parent will be inspected as well.
  7088. * @return {boolean} whether this node (and its parent) is enabled.
  7089. * @see setEnabled
  7090. */
  7091. Node.prototype.isEnabled = function () {
  7092. if (!this._isEnabled) {
  7093. return false;
  7094. }
  7095. if (this.parent) {
  7096. return this.parent.isEnabled();
  7097. }
  7098. return true;
  7099. };
  7100. /**
  7101. * Set the enabled state of this node.
  7102. * @param {boolean} value - the new enabled state
  7103. * @see isEnabled
  7104. */
  7105. Node.prototype.setEnabled = function (value) {
  7106. this._isEnabled = value;
  7107. };
  7108. /**
  7109. * Is this node a descendant of the given node.
  7110. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7111. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7112. * @see parent
  7113. */
  7114. Node.prototype.isDescendantOf = function (ancestor) {
  7115. if (this.parent) {
  7116. if (this.parent === ancestor) {
  7117. return true;
  7118. }
  7119. return this.parent.isDescendantOf(ancestor);
  7120. }
  7121. return false;
  7122. };
  7123. Node.prototype._getDescendants = function (list, results) {
  7124. for (var index = 0; index < list.length; index++) {
  7125. var item = list[index];
  7126. if (item.isDescendantOf(this)) {
  7127. results.push(item);
  7128. }
  7129. }
  7130. };
  7131. /**
  7132. * Will return all nodes that have this node as parent.
  7133. * @return {BABYLON.Node[]} all children nodes of all types.
  7134. */
  7135. Node.prototype.getDescendants = function () {
  7136. var results = [];
  7137. this._getDescendants(this._scene.meshes, results);
  7138. this._getDescendants(this._scene.lights, results);
  7139. this._getDescendants(this._scene.cameras, results);
  7140. return results;
  7141. };
  7142. Node.prototype._setReady = function (state) {
  7143. if (state === this._isReady) {
  7144. return;
  7145. }
  7146. if (!state) {
  7147. this._isReady = false;
  7148. return;
  7149. }
  7150. this._isReady = true;
  7151. if (this.onReady) {
  7152. this.onReady(this);
  7153. }
  7154. };
  7155. Node.prototype.getAnimationByName = function (name) {
  7156. for (var i = 0; i < this.animations.length; i++) {
  7157. var animation = this.animations[i];
  7158. if (animation.name === name) {
  7159. return animation;
  7160. }
  7161. }
  7162. return null;
  7163. };
  7164. Node.prototype.createAnimationRange = function (name, from, to) {
  7165. // check name not already in use
  7166. if (!this._ranges[name]) {
  7167. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7168. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7169. if (this.animations[i]) {
  7170. this.animations[i].createRange(name, from, to);
  7171. }
  7172. }
  7173. }
  7174. };
  7175. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7176. if (deleteFrames === void 0) { deleteFrames = true; }
  7177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7178. if (this.animations[i]) {
  7179. this.animations[i].deleteRange(name, deleteFrames);
  7180. }
  7181. }
  7182. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7183. };
  7184. Node.prototype.getAnimationRange = function (name) {
  7185. return this._ranges[name];
  7186. };
  7187. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7188. var range = this.getAnimationRange(name);
  7189. if (!range) {
  7190. return null;
  7191. }
  7192. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7193. };
  7194. Node.prototype.serializeAnimationRanges = function () {
  7195. var serializationRanges = [];
  7196. for (var name in this._ranges) {
  7197. var range = {};
  7198. range.name = name;
  7199. range.from = this._ranges[name].from;
  7200. range.to = this._ranges[name].to;
  7201. serializationRanges.push(range);
  7202. }
  7203. return serializationRanges;
  7204. };
  7205. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7206. if (parsedNode.ranges) {
  7207. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7208. var data = parsedNode.ranges[index];
  7209. node.createAnimationRange(data.name, data.from, data.to);
  7210. }
  7211. }
  7212. };
  7213. return Node;
  7214. })();
  7215. BABYLON.Node = Node;
  7216. })(BABYLON || (BABYLON = {}));
  7217. var BABYLON;
  7218. (function (BABYLON) {
  7219. var FilesInput = (function () {
  7220. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7221. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7222. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7223. this._engine = p_engine;
  7224. this._canvas = p_canvas;
  7225. this._currentScene = p_scene;
  7226. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7227. this._progressCallback = p_progressCallback;
  7228. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7229. this._textureLoadingCallback = p_textureLoadingCallback;
  7230. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7231. }
  7232. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7233. var _this = this;
  7234. if (p_elementToMonitor) {
  7235. this._elementToMonitor = p_elementToMonitor;
  7236. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7237. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7238. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7239. }
  7240. };
  7241. FilesInput.prototype.renderFunction = function () {
  7242. if (this._additionnalRenderLoopLogicCallback) {
  7243. this._additionnalRenderLoopLogicCallback();
  7244. }
  7245. if (this._currentScene) {
  7246. if (this._textureLoadingCallback) {
  7247. var remaining = this._currentScene.getWaitingItemsCount();
  7248. if (remaining > 0) {
  7249. this._textureLoadingCallback(remaining);
  7250. }
  7251. }
  7252. this._currentScene.render();
  7253. }
  7254. };
  7255. FilesInput.prototype.drag = function (e) {
  7256. e.stopPropagation();
  7257. e.preventDefault();
  7258. };
  7259. FilesInput.prototype.drop = function (eventDrop) {
  7260. eventDrop.stopPropagation();
  7261. eventDrop.preventDefault();
  7262. this.loadFiles(eventDrop);
  7263. };
  7264. FilesInput.prototype.loadFiles = function (event) {
  7265. if (this._startingProcessingFilesCallback)
  7266. this._startingProcessingFilesCallback();
  7267. // Handling data transfer via drag'n'drop
  7268. if (event && event.dataTransfer && event.dataTransfer.files) {
  7269. this._filesToLoad = event.dataTransfer.files;
  7270. }
  7271. // Handling files from input files
  7272. if (event && event.target && event.target.files) {
  7273. this._filesToLoad = event.target.files;
  7274. }
  7275. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7276. for (var i = 0; i < this._filesToLoad.length; i++) {
  7277. switch (this._filesToLoad[i].type) {
  7278. case "image/jpeg":
  7279. case "image/png":
  7280. case "image/bmp":
  7281. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7282. break;
  7283. case "image/targa":
  7284. case "image/vnd.ms-dds":
  7285. case "audio/wav":
  7286. case "audio/x-wav":
  7287. case "audio/mp3":
  7288. case "audio/mpeg":
  7289. case "audio/mpeg3":
  7290. case "audio/x-mpeg-3":
  7291. case "audio/ogg":
  7292. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7293. break;
  7294. default:
  7295. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7296. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7297. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7298. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7299. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7300. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7301. this._sceneFileToLoad = this._filesToLoad[i];
  7302. }
  7303. break;
  7304. }
  7305. }
  7306. this.reload();
  7307. }
  7308. };
  7309. FilesInput.prototype.reload = function () {
  7310. var _this = this;
  7311. var that = this;
  7312. // If a ".babylon" file has been provided
  7313. if (this._sceneFileToLoad) {
  7314. if (this._currentScene) {
  7315. if (BABYLON.Tools.errorsCount > 0) {
  7316. BABYLON.Tools.ClearLogCache();
  7317. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7318. }
  7319. this._engine.stopRenderLoop();
  7320. this._currentScene.dispose();
  7321. }
  7322. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7323. that._currentScene = newScene;
  7324. // Wait for textures and shaders to be ready
  7325. that._currentScene.executeWhenReady(function () {
  7326. // Attach camera to canvas inputs
  7327. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7328. that._currentScene.createDefaultCameraOrLight();
  7329. }
  7330. that._currentScene.activeCamera.attachControl(that._canvas);
  7331. if (that._sceneLoadedCallback) {
  7332. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7333. }
  7334. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7335. });
  7336. }, function (progress) {
  7337. if (_this._progressCallback) {
  7338. _this._progressCallback(progress);
  7339. }
  7340. });
  7341. }
  7342. else {
  7343. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7344. }
  7345. };
  7346. FilesInput.FilesTextures = new Array();
  7347. FilesInput.FilesToLoad = new Array();
  7348. return FilesInput;
  7349. })();
  7350. BABYLON.FilesInput = FilesInput;
  7351. })(BABYLON || (BABYLON = {}));
  7352. var BABYLON;
  7353. (function (BABYLON) {
  7354. var IntersectionInfo = (function () {
  7355. function IntersectionInfo(bu, bv, distance) {
  7356. this.bu = bu;
  7357. this.bv = bv;
  7358. this.distance = distance;
  7359. this.faceId = 0;
  7360. this.subMeshId = 0;
  7361. }
  7362. return IntersectionInfo;
  7363. })();
  7364. BABYLON.IntersectionInfo = IntersectionInfo;
  7365. var PickingInfo = (function () {
  7366. function PickingInfo() {
  7367. this.hit = false;
  7368. this.distance = 0;
  7369. this.pickedPoint = null;
  7370. this.pickedMesh = null;
  7371. this.bu = 0;
  7372. this.bv = 0;
  7373. this.faceId = -1;
  7374. this.subMeshId = 0;
  7375. this.pickedSprite = null;
  7376. }
  7377. // Methods
  7378. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7379. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7380. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7381. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7382. return null;
  7383. }
  7384. var indices = this.pickedMesh.getIndices();
  7385. var result;
  7386. if (useVerticesNormals) {
  7387. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7388. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7389. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7390. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7391. normal0 = normal0.scale(this.bu);
  7392. normal1 = normal1.scale(this.bv);
  7393. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7394. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7395. }
  7396. else {
  7397. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7398. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7399. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7400. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7401. var p1p2 = vertex1.subtract(vertex2);
  7402. var p3p2 = vertex3.subtract(vertex2);
  7403. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7404. }
  7405. if (useWorldCoordinates) {
  7406. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7407. }
  7408. return BABYLON.Vector3.Normalize(result);
  7409. };
  7410. PickingInfo.prototype.getTextureCoordinates = function () {
  7411. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7412. return null;
  7413. }
  7414. var indices = this.pickedMesh.getIndices();
  7415. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7416. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7417. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7418. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7419. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7420. uv1 = uv1.scale(this.bu);
  7421. uv2 = uv2.scale(this.bv);
  7422. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7423. };
  7424. return PickingInfo;
  7425. })();
  7426. BABYLON.PickingInfo = PickingInfo;
  7427. })(BABYLON || (BABYLON = {}));
  7428. var BABYLON;
  7429. (function (BABYLON) {
  7430. var BoundingSphere = (function () {
  7431. function BoundingSphere(minimum, maximum) {
  7432. this.minimum = minimum;
  7433. this.maximum = maximum;
  7434. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7435. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7436. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7437. this.radius = distance * 0.5;
  7438. this.centerWorld = BABYLON.Vector3.Zero();
  7439. this._update(BABYLON.Matrix.Identity());
  7440. }
  7441. // Methods
  7442. BoundingSphere.prototype._update = function (world) {
  7443. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7444. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7445. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7446. };
  7447. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7448. for (var i = 0; i < 6; i++) {
  7449. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7450. return false;
  7451. }
  7452. return true;
  7453. };
  7454. BoundingSphere.prototype.intersectsPoint = function (point) {
  7455. var x = this.centerWorld.x - point.x;
  7456. var y = this.centerWorld.y - point.y;
  7457. var z = this.centerWorld.z - point.z;
  7458. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7459. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7460. return false;
  7461. return true;
  7462. };
  7463. // Statics
  7464. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7465. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7466. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7467. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7468. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7469. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7470. return false;
  7471. return true;
  7472. };
  7473. return BoundingSphere;
  7474. })();
  7475. BABYLON.BoundingSphere = BoundingSphere;
  7476. })(BABYLON || (BABYLON = {}));
  7477. var BABYLON;
  7478. (function (BABYLON) {
  7479. var BoundingBox = (function () {
  7480. function BoundingBox(minimum, maximum) {
  7481. this.minimum = minimum;
  7482. this.maximum = maximum;
  7483. this.vectors = new Array();
  7484. this.vectorsWorld = new Array();
  7485. // Bounding vectors
  7486. this.vectors.push(this.minimum.clone());
  7487. this.vectors.push(this.maximum.clone());
  7488. this.vectors.push(this.minimum.clone());
  7489. this.vectors[2].x = this.maximum.x;
  7490. this.vectors.push(this.minimum.clone());
  7491. this.vectors[3].y = this.maximum.y;
  7492. this.vectors.push(this.minimum.clone());
  7493. this.vectors[4].z = this.maximum.z;
  7494. this.vectors.push(this.maximum.clone());
  7495. this.vectors[5].z = this.minimum.z;
  7496. this.vectors.push(this.maximum.clone());
  7497. this.vectors[6].x = this.minimum.x;
  7498. this.vectors.push(this.maximum.clone());
  7499. this.vectors[7].y = this.minimum.y;
  7500. // OBB
  7501. this.center = this.maximum.add(this.minimum).scale(0.5);
  7502. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7503. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7504. // World
  7505. for (var index = 0; index < this.vectors.length; index++) {
  7506. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7507. }
  7508. this.minimumWorld = BABYLON.Vector3.Zero();
  7509. this.maximumWorld = BABYLON.Vector3.Zero();
  7510. this._update(BABYLON.Matrix.Identity());
  7511. }
  7512. // Methods
  7513. BoundingBox.prototype.getWorldMatrix = function () {
  7514. return this._worldMatrix;
  7515. };
  7516. BoundingBox.prototype._update = function (world) {
  7517. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7518. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7519. for (var index = 0; index < this.vectors.length; index++) {
  7520. var v = this.vectorsWorld[index];
  7521. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7522. if (v.x < this.minimumWorld.x)
  7523. this.minimumWorld.x = v.x;
  7524. if (v.y < this.minimumWorld.y)
  7525. this.minimumWorld.y = v.y;
  7526. if (v.z < this.minimumWorld.z)
  7527. this.minimumWorld.z = v.z;
  7528. if (v.x > this.maximumWorld.x)
  7529. this.maximumWorld.x = v.x;
  7530. if (v.y > this.maximumWorld.y)
  7531. this.maximumWorld.y = v.y;
  7532. if (v.z > this.maximumWorld.z)
  7533. this.maximumWorld.z = v.z;
  7534. }
  7535. // OBB
  7536. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7537. this.center.scaleInPlace(0.5);
  7538. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7539. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7540. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7541. this._worldMatrix = world;
  7542. };
  7543. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7544. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7545. };
  7546. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7547. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7548. };
  7549. BoundingBox.prototype.intersectsPoint = function (point) {
  7550. var delta = -BABYLON.Engine.Epsilon;
  7551. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7552. return false;
  7553. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7554. return false;
  7555. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7556. return false;
  7557. return true;
  7558. };
  7559. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7560. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7561. };
  7562. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7563. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7564. return false;
  7565. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7566. return false;
  7567. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7568. return false;
  7569. return true;
  7570. };
  7571. // Statics
  7572. BoundingBox.Intersects = function (box0, box1) {
  7573. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7574. return false;
  7575. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7576. return false;
  7577. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7578. return false;
  7579. return true;
  7580. };
  7581. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7582. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7583. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7584. return (num <= (sphereRadius * sphereRadius));
  7585. };
  7586. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7587. for (var p = 0; p < 6; p++) {
  7588. for (var i = 0; i < 8; i++) {
  7589. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7590. return false;
  7591. }
  7592. }
  7593. }
  7594. return true;
  7595. };
  7596. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7597. for (var p = 0; p < 6; p++) {
  7598. var inCount = 8;
  7599. for (var i = 0; i < 8; i++) {
  7600. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7601. --inCount;
  7602. }
  7603. else {
  7604. break;
  7605. }
  7606. }
  7607. if (inCount === 0)
  7608. return false;
  7609. }
  7610. return true;
  7611. };
  7612. return BoundingBox;
  7613. })();
  7614. BABYLON.BoundingBox = BoundingBox;
  7615. })(BABYLON || (BABYLON = {}));
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. var computeBoxExtents = function (axis, box) {
  7619. var p = BABYLON.Vector3.Dot(box.center, axis);
  7620. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7621. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7622. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7623. var r = r0 + r1 + r2;
  7624. return {
  7625. min: p - r,
  7626. max: p + r
  7627. };
  7628. };
  7629. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7630. var axisOverlap = function (axis, box0, box1) {
  7631. var result0 = computeBoxExtents(axis, box0);
  7632. var result1 = computeBoxExtents(axis, box1);
  7633. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7634. };
  7635. var BoundingInfo = (function () {
  7636. function BoundingInfo(minimum, maximum) {
  7637. this.minimum = minimum;
  7638. this.maximum = maximum;
  7639. this._isLocked = false;
  7640. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7641. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7642. }
  7643. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7644. get: function () {
  7645. return this._isLocked;
  7646. },
  7647. set: function (value) {
  7648. this._isLocked = value;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. // Methods
  7654. BoundingInfo.prototype.update = function (world) {
  7655. if (this._isLocked) {
  7656. return;
  7657. }
  7658. this.boundingBox._update(world);
  7659. this.boundingSphere._update(world);
  7660. };
  7661. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7662. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7663. return false;
  7664. return this.boundingBox.isInFrustum(frustumPlanes);
  7665. };
  7666. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7667. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7668. };
  7669. BoundingInfo.prototype._checkCollision = function (collider) {
  7670. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7671. };
  7672. BoundingInfo.prototype.intersectsPoint = function (point) {
  7673. if (!this.boundingSphere.centerWorld) {
  7674. return false;
  7675. }
  7676. if (!this.boundingSphere.intersectsPoint(point)) {
  7677. return false;
  7678. }
  7679. if (!this.boundingBox.intersectsPoint(point)) {
  7680. return false;
  7681. }
  7682. return true;
  7683. };
  7684. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7685. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7686. return false;
  7687. }
  7688. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7689. return false;
  7690. }
  7691. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7692. return false;
  7693. }
  7694. if (!precise) {
  7695. return true;
  7696. }
  7697. var box0 = this.boundingBox;
  7698. var box1 = boundingInfo.boundingBox;
  7699. if (!axisOverlap(box0.directions[0], box0, box1))
  7700. return false;
  7701. if (!axisOverlap(box0.directions[1], box0, box1))
  7702. return false;
  7703. if (!axisOverlap(box0.directions[2], box0, box1))
  7704. return false;
  7705. if (!axisOverlap(box1.directions[0], box0, box1))
  7706. return false;
  7707. if (!axisOverlap(box1.directions[1], box0, box1))
  7708. return false;
  7709. if (!axisOverlap(box1.directions[2], box0, box1))
  7710. return false;
  7711. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7712. return false;
  7713. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7714. return false;
  7715. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7716. return false;
  7717. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7718. return false;
  7719. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7720. return false;
  7721. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7722. return false;
  7723. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7724. return false;
  7725. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7726. return false;
  7727. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7728. return false;
  7729. return true;
  7730. };
  7731. return BoundingInfo;
  7732. })();
  7733. BABYLON.BoundingInfo = BoundingInfo;
  7734. })(BABYLON || (BABYLON = {}));
  7735. var BABYLON;
  7736. (function (BABYLON) {
  7737. var AbstractMesh = (function (_super) {
  7738. __extends(AbstractMesh, _super);
  7739. // Constructor
  7740. function AbstractMesh(name, scene) {
  7741. var _this = this;
  7742. _super.call(this, name, scene);
  7743. // Properties
  7744. this.definedFacingForward = true; // orientation for POV movement & rotation
  7745. this.position = new BABYLON.Vector3(0, 0, 0);
  7746. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7747. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7748. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7749. this.visibility = 1.0;
  7750. this.alphaIndex = Number.MAX_VALUE;
  7751. this.infiniteDistance = false;
  7752. this.isVisible = true;
  7753. this.isPickable = true;
  7754. this.showBoundingBox = false;
  7755. this.showSubMeshesBoundingBox = false;
  7756. this.onDispose = null;
  7757. this.isBlocker = false;
  7758. this.renderingGroupId = 0;
  7759. this.receiveShadows = false;
  7760. this.renderOutline = false;
  7761. this.outlineColor = BABYLON.Color3.Red();
  7762. this.outlineWidth = 0.02;
  7763. this.renderOverlay = false;
  7764. this.overlayColor = BABYLON.Color3.Red();
  7765. this.overlayAlpha = 0.5;
  7766. this.hasVertexAlpha = false;
  7767. this.useVertexColors = true;
  7768. this.applyFog = true;
  7769. this.computeBonesUsingShaders = true;
  7770. this.scalingDeterminant = 1;
  7771. this.numBoneInfluencers = 4;
  7772. this.useOctreeForRenderingSelection = true;
  7773. this.useOctreeForPicking = true;
  7774. this.useOctreeForCollisions = true;
  7775. this.layerMask = 0x0FFFFFFF;
  7776. this.alwaysSelectAsActiveMesh = false;
  7777. // Physics
  7778. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7779. // Collisions
  7780. this._checkCollisions = false;
  7781. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7782. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7783. this._collider = new BABYLON.Collider();
  7784. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7785. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7786. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7787. // Edges
  7788. this.edgesWidth = 1;
  7789. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7790. // Cache
  7791. this._localWorld = BABYLON.Matrix.Zero();
  7792. this._worldMatrix = BABYLON.Matrix.Zero();
  7793. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7794. this._absolutePosition = BABYLON.Vector3.Zero();
  7795. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7796. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7797. this._isDirty = false;
  7798. this._pivotMatrix = BABYLON.Matrix.Identity();
  7799. this._isDisposed = false;
  7800. this._renderId = 0;
  7801. this._intersectionsInProgress = new Array();
  7802. this._onAfterWorldMatrixUpdate = new Array();
  7803. this._isWorldMatrixFrozen = false;
  7804. this._unIndexed = false;
  7805. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7806. if (collidedMesh === void 0) { collidedMesh = null; }
  7807. //TODO move this to the collision coordinator!
  7808. if (_this.getScene().workerCollisions)
  7809. newPosition.multiplyInPlace(_this._collider.radius);
  7810. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7811. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7812. _this.position.addInPlace(_this._diffPositionForCollisions);
  7813. }
  7814. if (_this.onCollide && collidedMesh) {
  7815. _this.onCollide(collidedMesh);
  7816. }
  7817. if (_this.onCollisionPositionChange) {
  7818. _this.onCollisionPositionChange(_this.position);
  7819. }
  7820. };
  7821. scene.addMesh(this);
  7822. }
  7823. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7824. get: function () {
  7825. return AbstractMesh._BILLBOARDMODE_NONE;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7831. get: function () {
  7832. return AbstractMesh._BILLBOARDMODE_X;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7838. get: function () {
  7839. return AbstractMesh._BILLBOARDMODE_Y;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7845. get: function () {
  7846. return AbstractMesh._BILLBOARDMODE_Z;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7852. get: function () {
  7853. return AbstractMesh._BILLBOARDMODE_ALL;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7859. get: function () {
  7860. return this._skeleton;
  7861. },
  7862. set: function (value) {
  7863. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7864. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7865. }
  7866. if (value && value.needInitialSkinMatrix) {
  7867. value._registerMeshWithPoseMatrix(this);
  7868. }
  7869. this._skeleton = value;
  7870. if (!this._skeleton) {
  7871. this._bonesTransformMatrices = null;
  7872. }
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. // Methods
  7878. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7879. this._poseMatrix.copyFrom(matrix);
  7880. };
  7881. AbstractMesh.prototype.getPoseMatrix = function () {
  7882. return this._poseMatrix;
  7883. };
  7884. AbstractMesh.prototype.disableEdgesRendering = function () {
  7885. if (this._edgesRenderer !== undefined) {
  7886. this._edgesRenderer.dispose();
  7887. this._edgesRenderer = undefined;
  7888. }
  7889. };
  7890. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7891. if (epsilon === void 0) { epsilon = 0.95; }
  7892. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7893. this.disableEdgesRendering();
  7894. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7895. };
  7896. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7897. get: function () {
  7898. return false;
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. AbstractMesh.prototype.getLOD = function (camera) {
  7904. return this;
  7905. };
  7906. AbstractMesh.prototype.getTotalVertices = function () {
  7907. return 0;
  7908. };
  7909. AbstractMesh.prototype.getIndices = function () {
  7910. return null;
  7911. };
  7912. AbstractMesh.prototype.getVerticesData = function (kind) {
  7913. return null;
  7914. };
  7915. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7916. return false;
  7917. };
  7918. AbstractMesh.prototype.getBoundingInfo = function () {
  7919. if (this._masterMesh) {
  7920. return this._masterMesh.getBoundingInfo();
  7921. }
  7922. if (!this._boundingInfo) {
  7923. this._updateBoundingInfo();
  7924. }
  7925. return this._boundingInfo;
  7926. };
  7927. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7928. get: function () {
  7929. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. AbstractMesh.prototype._preActivate = function () {
  7935. };
  7936. AbstractMesh.prototype._activate = function (renderId) {
  7937. this._renderId = renderId;
  7938. };
  7939. AbstractMesh.prototype.getWorldMatrix = function () {
  7940. if (this._masterMesh) {
  7941. return this._masterMesh.getWorldMatrix();
  7942. }
  7943. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7944. this.computeWorldMatrix();
  7945. }
  7946. return this._worldMatrix;
  7947. };
  7948. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7949. get: function () {
  7950. return this._worldMatrix;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7956. get: function () {
  7957. return this._absolutePosition;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7963. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7964. this.computeWorldMatrix(true);
  7965. this._isWorldMatrixFrozen = true;
  7966. };
  7967. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7968. this._isWorldMatrixFrozen = false;
  7969. this.computeWorldMatrix(true);
  7970. };
  7971. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7972. get: function () {
  7973. return this._isWorldMatrixFrozen;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7979. axis.normalize();
  7980. if (!this.rotationQuaternion) {
  7981. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7982. this.rotation = BABYLON.Vector3.Zero();
  7983. }
  7984. var rotationQuaternion;
  7985. if (!space || space === BABYLON.Space.LOCAL) {
  7986. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7987. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7988. }
  7989. else {
  7990. if (this.parent) {
  7991. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7992. invertParentWorldMatrix.invert();
  7993. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7994. }
  7995. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7996. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7997. }
  7998. };
  7999. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8000. var displacementVector = axis.scale(distance);
  8001. if (!space || space === BABYLON.Space.LOCAL) {
  8002. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8003. this.setPositionWithLocalVector(tempV3);
  8004. }
  8005. else {
  8006. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8007. }
  8008. };
  8009. AbstractMesh.prototype.getAbsolutePosition = function () {
  8010. this.computeWorldMatrix();
  8011. return this._absolutePosition;
  8012. };
  8013. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8014. if (!absolutePosition) {
  8015. return;
  8016. }
  8017. var absolutePositionX;
  8018. var absolutePositionY;
  8019. var absolutePositionZ;
  8020. if (absolutePosition.x === undefined) {
  8021. if (arguments.length < 3) {
  8022. return;
  8023. }
  8024. absolutePositionX = arguments[0];
  8025. absolutePositionY = arguments[1];
  8026. absolutePositionZ = arguments[2];
  8027. }
  8028. else {
  8029. absolutePositionX = absolutePosition.x;
  8030. absolutePositionY = absolutePosition.y;
  8031. absolutePositionZ = absolutePosition.z;
  8032. }
  8033. if (this.parent) {
  8034. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8035. invertParentWorldMatrix.invert();
  8036. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8037. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8038. }
  8039. else {
  8040. this.position.x = absolutePositionX;
  8041. this.position.y = absolutePositionY;
  8042. this.position.z = absolutePositionZ;
  8043. }
  8044. };
  8045. // ================================== Point of View Movement =================================
  8046. /**
  8047. * Perform relative position change from the point of view of behind the front of the mesh.
  8048. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8049. * Supports definition of mesh facing forward or backward.
  8050. * @param {number} amountRight
  8051. * @param {number} amountUp
  8052. * @param {number} amountForward
  8053. */
  8054. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8055. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8056. };
  8057. /**
  8058. * Calculate relative position change from the point of view of behind the front of the mesh.
  8059. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8060. * Supports definition of mesh facing forward or backward.
  8061. * @param {number} amountRight
  8062. * @param {number} amountUp
  8063. * @param {number} amountForward
  8064. */
  8065. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8066. var rotMatrix = new BABYLON.Matrix();
  8067. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8068. rotQuaternion.toRotationMatrix(rotMatrix);
  8069. var translationDelta = BABYLON.Vector3.Zero();
  8070. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8071. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8072. return translationDelta;
  8073. };
  8074. // ================================== Point of View Rotation =================================
  8075. /**
  8076. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8077. * Supports definition of mesh facing forward or backward.
  8078. * @param {number} flipBack
  8079. * @param {number} twirlClockwise
  8080. * @param {number} tiltRight
  8081. */
  8082. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8083. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8084. };
  8085. /**
  8086. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8087. * Supports definition of mesh facing forward or backward.
  8088. * @param {number} flipBack
  8089. * @param {number} twirlClockwise
  8090. * @param {number} tiltRight
  8091. */
  8092. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8093. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8094. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8095. };
  8096. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8097. this._pivotMatrix = matrix;
  8098. this._cache.pivotMatrixUpdated = true;
  8099. };
  8100. AbstractMesh.prototype.getPivotMatrix = function () {
  8101. return this._pivotMatrix;
  8102. };
  8103. AbstractMesh.prototype._isSynchronized = function () {
  8104. if (this._isDirty) {
  8105. return false;
  8106. }
  8107. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8108. return false;
  8109. if (this._cache.pivotMatrixUpdated) {
  8110. return false;
  8111. }
  8112. if (this.infiniteDistance) {
  8113. return false;
  8114. }
  8115. if (!this._cache.position.equals(this.position))
  8116. return false;
  8117. if (this.rotationQuaternion) {
  8118. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8119. return false;
  8120. }
  8121. else {
  8122. if (!this._cache.rotation.equals(this.rotation))
  8123. return false;
  8124. }
  8125. if (!this._cache.scaling.equals(this.scaling))
  8126. return false;
  8127. return true;
  8128. };
  8129. AbstractMesh.prototype._initCache = function () {
  8130. _super.prototype._initCache.call(this);
  8131. this._cache.localMatrixUpdated = false;
  8132. this._cache.position = BABYLON.Vector3.Zero();
  8133. this._cache.scaling = BABYLON.Vector3.Zero();
  8134. this._cache.rotation = BABYLON.Vector3.Zero();
  8135. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8136. this._cache.billboardMode = -1;
  8137. };
  8138. AbstractMesh.prototype.markAsDirty = function (property) {
  8139. if (property === "rotation") {
  8140. this.rotationQuaternion = null;
  8141. }
  8142. this._currentRenderId = Number.MAX_VALUE;
  8143. this._isDirty = true;
  8144. };
  8145. AbstractMesh.prototype._updateBoundingInfo = function () {
  8146. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8147. this._boundingInfo.update(this.worldMatrixFromCache);
  8148. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8149. };
  8150. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8151. if (!this.subMeshes) {
  8152. return;
  8153. }
  8154. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8155. var subMesh = this.subMeshes[subIndex];
  8156. if (!subMesh.IsGlobal) {
  8157. subMesh.updateBoundingInfo(matrix);
  8158. }
  8159. }
  8160. };
  8161. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8162. if (this._isWorldMatrixFrozen) {
  8163. return this._worldMatrix;
  8164. }
  8165. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8166. this._currentRenderId = this.getScene().getRenderId();
  8167. return this._worldMatrix;
  8168. }
  8169. this._cache.position.copyFrom(this.position);
  8170. this._cache.scaling.copyFrom(this.scaling);
  8171. this._cache.pivotMatrixUpdated = false;
  8172. this._cache.billboardMode = this.billboardMode;
  8173. this._currentRenderId = this.getScene().getRenderId();
  8174. this._isDirty = false;
  8175. // Scaling
  8176. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8177. // Rotation
  8178. if (this.rotationQuaternion) {
  8179. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8180. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8181. }
  8182. else {
  8183. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8184. this._cache.rotation.copyFrom(this.rotation);
  8185. }
  8186. // Translation
  8187. if (this.infiniteDistance && !this.parent) {
  8188. var camera = this.getScene().activeCamera;
  8189. if (camera) {
  8190. var cameraWorldMatrix = camera.getWorldMatrix();
  8191. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8192. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8193. }
  8194. }
  8195. else {
  8196. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8197. }
  8198. // Composing transformations
  8199. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8200. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8201. // Billboarding
  8202. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8203. var localPosition = this.position.clone();
  8204. var zero = this.getScene().activeCamera.globalPosition.clone();
  8205. if (this.parent && this.parent.position) {
  8206. localPosition.addInPlace(this.parent.position);
  8207. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8208. }
  8209. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8210. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8211. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8212. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8213. zero.y = localPosition.y + 0.001;
  8214. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8215. zero.z = localPosition.z + 0.001;
  8216. }
  8217. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8218. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8219. BABYLON.Tmp.Matrix[3].invert();
  8220. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8221. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8222. }
  8223. // Local world
  8224. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8225. // Parent
  8226. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8227. this._markSyncedWithParent();
  8228. if (this._meshToBoneReferal) {
  8229. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8230. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8231. }
  8232. else {
  8233. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8234. }
  8235. }
  8236. else {
  8237. this._worldMatrix.copyFrom(this._localWorld);
  8238. }
  8239. // Bounding info
  8240. this._updateBoundingInfo();
  8241. // Absolute position
  8242. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8243. // Callbacks
  8244. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8245. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8246. }
  8247. if (!this._poseMatrix) {
  8248. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8249. }
  8250. return this._worldMatrix;
  8251. };
  8252. /**
  8253. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8254. * @param func: callback function to add
  8255. */
  8256. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8257. this._onAfterWorldMatrixUpdate.push(func);
  8258. };
  8259. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8260. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8261. if (index > -1) {
  8262. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8263. }
  8264. };
  8265. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8266. this.computeWorldMatrix();
  8267. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8268. };
  8269. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8270. this.computeWorldMatrix();
  8271. var invLocalWorldMatrix = this._localWorld.clone();
  8272. invLocalWorldMatrix.invert();
  8273. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8274. };
  8275. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8276. this.computeWorldMatrix(true);
  8277. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8278. };
  8279. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8280. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8281. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8282. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8283. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8284. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8285. /// <returns>Mesh oriented towards targetMesh</returns>
  8286. yawCor = yawCor || 0; // default to zero if undefined
  8287. pitchCor = pitchCor || 0;
  8288. rollCor = rollCor || 0;
  8289. var dv = targetPoint.subtract(this.position);
  8290. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8291. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8292. var pitch = Math.atan2(dv.y, len);
  8293. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8294. };
  8295. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8296. this._meshToBoneReferal = affectedMesh;
  8297. this.parent = bone;
  8298. if (bone.getWorldMatrix().determinant() < 0) {
  8299. this.scalingDeterminant *= -1;
  8300. }
  8301. };
  8302. AbstractMesh.prototype.detachFromBone = function () {
  8303. if (this.parent.getWorldMatrix().determinant() < 0) {
  8304. this.scalingDeterminant *= -1;
  8305. }
  8306. this._meshToBoneReferal = null;
  8307. this.parent = null;
  8308. };
  8309. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8310. return this._boundingInfo.isInFrustum(frustumPlanes);
  8311. };
  8312. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8313. if (!camera) {
  8314. camera = this.getScene().activeCamera;
  8315. }
  8316. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8317. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8318. return false;
  8319. }
  8320. return true;
  8321. };
  8322. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8323. if (!this._boundingInfo || !mesh._boundingInfo) {
  8324. return false;
  8325. }
  8326. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8327. };
  8328. AbstractMesh.prototype.intersectsPoint = function (point) {
  8329. if (!this._boundingInfo) {
  8330. return false;
  8331. }
  8332. return this._boundingInfo.intersectsPoint(point);
  8333. };
  8334. // Physics
  8335. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8336. var physicsEngine = this.getScene().getPhysicsEngine();
  8337. if (!physicsEngine) {
  8338. return null;
  8339. }
  8340. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8341. if (impostor.impostor) {
  8342. // Old API
  8343. options = impostor;
  8344. impostor = impostor.impostor;
  8345. }
  8346. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8347. physicsEngine._unregisterMesh(this);
  8348. return null;
  8349. }
  8350. if (!options) {
  8351. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8352. }
  8353. else {
  8354. if (!options.mass && options.mass !== 0)
  8355. options.mass = 0;
  8356. if (!options.friction && options.friction !== 0)
  8357. options.friction = 0.2;
  8358. if (!options.restitution && options.restitution !== 0)
  8359. options.restitution = 0.2;
  8360. }
  8361. this._physicImpostor = impostor;
  8362. this._physicsMass = options.mass;
  8363. this._physicsFriction = options.friction;
  8364. this._physicRestitution = options.restitution;
  8365. return physicsEngine._registerMesh(this, impostor, options);
  8366. };
  8367. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8368. if (!this._physicImpostor) {
  8369. return BABYLON.PhysicsEngine.NoImpostor;
  8370. }
  8371. return this._physicImpostor;
  8372. };
  8373. AbstractMesh.prototype.getPhysicsMass = function () {
  8374. if (!this._physicsMass) {
  8375. return 0;
  8376. }
  8377. return this._physicsMass;
  8378. };
  8379. AbstractMesh.prototype.getPhysicsFriction = function () {
  8380. if (!this._physicsFriction) {
  8381. return 0;
  8382. }
  8383. return this._physicsFriction;
  8384. };
  8385. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8386. if (!this._physicRestitution) {
  8387. return 0;
  8388. }
  8389. return this._physicRestitution;
  8390. };
  8391. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8392. if (!camera) {
  8393. camera = this.getScene().activeCamera;
  8394. }
  8395. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8396. };
  8397. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8398. if (!camera) {
  8399. camera = this.getScene().activeCamera;
  8400. }
  8401. return this.absolutePosition.subtract(camera.position).length();
  8402. };
  8403. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8404. if (!this._physicImpostor) {
  8405. return;
  8406. }
  8407. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8408. };
  8409. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8410. if (!this._physicImpostor) {
  8411. return;
  8412. }
  8413. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8414. };
  8415. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8416. if (!this._physicImpostor) {
  8417. return;
  8418. }
  8419. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8420. };
  8421. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8422. // Collisions
  8423. get: function () {
  8424. return this._checkCollisions;
  8425. },
  8426. set: function (collisionEnabled) {
  8427. this._checkCollisions = collisionEnabled;
  8428. if (this.getScene().workerCollisions) {
  8429. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8430. }
  8431. },
  8432. enumerable: true,
  8433. configurable: true
  8434. });
  8435. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8436. var globalPosition = this.getAbsolutePosition();
  8437. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8438. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8439. this._collider.radius = this.ellipsoid;
  8440. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8441. };
  8442. // Submeshes octree
  8443. /**
  8444. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8445. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8446. */
  8447. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8448. if (maxCapacity === void 0) { maxCapacity = 64; }
  8449. if (maxDepth === void 0) { maxDepth = 2; }
  8450. if (!this._submeshesOctree) {
  8451. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8452. }
  8453. this.computeWorldMatrix(true);
  8454. // Update octree
  8455. var bbox = this.getBoundingInfo().boundingBox;
  8456. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8457. return this._submeshesOctree;
  8458. };
  8459. // Collisions
  8460. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8461. this._generatePointsArray();
  8462. // Transformation
  8463. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8464. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8465. subMesh._lastColliderWorldVertices = [];
  8466. subMesh._trianglePlanes = [];
  8467. var start = subMesh.verticesStart;
  8468. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8469. for (var i = start; i < end; i++) {
  8470. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8471. }
  8472. }
  8473. // Collide
  8474. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8475. if (collider.collisionFound) {
  8476. collider.collidedMesh = this;
  8477. }
  8478. };
  8479. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8480. var subMeshes;
  8481. var len;
  8482. // Octrees
  8483. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8484. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8485. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8486. len = intersections.length;
  8487. subMeshes = intersections.data;
  8488. }
  8489. else {
  8490. subMeshes = this.subMeshes;
  8491. len = subMeshes.length;
  8492. }
  8493. for (var index = 0; index < len; index++) {
  8494. var subMesh = subMeshes[index];
  8495. // Bounding test
  8496. if (len > 1 && !subMesh._checkCollision(collider))
  8497. continue;
  8498. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8499. }
  8500. };
  8501. AbstractMesh.prototype._checkCollision = function (collider) {
  8502. // Bounding box test
  8503. if (!this._boundingInfo._checkCollision(collider))
  8504. return;
  8505. // Transformation matrix
  8506. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8507. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8508. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8509. };
  8510. // Picking
  8511. AbstractMesh.prototype._generatePointsArray = function () {
  8512. return false;
  8513. };
  8514. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8515. var pickingInfo = new BABYLON.PickingInfo();
  8516. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8517. return pickingInfo;
  8518. }
  8519. if (!this._generatePointsArray()) {
  8520. return pickingInfo;
  8521. }
  8522. var intersectInfo = null;
  8523. // Octrees
  8524. var subMeshes;
  8525. var len;
  8526. if (this._submeshesOctree && this.useOctreeForPicking) {
  8527. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8528. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8529. len = intersections.length;
  8530. subMeshes = intersections.data;
  8531. }
  8532. else {
  8533. subMeshes = this.subMeshes;
  8534. len = subMeshes.length;
  8535. }
  8536. for (var index = 0; index < len; index++) {
  8537. var subMesh = subMeshes[index];
  8538. // Bounding test
  8539. if (len > 1 && !subMesh.canIntersects(ray))
  8540. continue;
  8541. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8542. if (currentIntersectInfo) {
  8543. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8544. intersectInfo = currentIntersectInfo;
  8545. intersectInfo.subMeshId = index;
  8546. if (fastCheck) {
  8547. break;
  8548. }
  8549. }
  8550. }
  8551. }
  8552. if (intersectInfo) {
  8553. // Get picked point
  8554. var world = this.getWorldMatrix();
  8555. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8556. var direction = ray.direction.clone();
  8557. direction = direction.scale(intersectInfo.distance);
  8558. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8559. var pickedPoint = worldOrigin.add(worldDirection);
  8560. // Return result
  8561. pickingInfo.hit = true;
  8562. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8563. pickingInfo.pickedPoint = pickedPoint;
  8564. pickingInfo.pickedMesh = this;
  8565. pickingInfo.bu = intersectInfo.bu;
  8566. pickingInfo.bv = intersectInfo.bv;
  8567. pickingInfo.faceId = intersectInfo.faceId;
  8568. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8569. return pickingInfo;
  8570. }
  8571. return pickingInfo;
  8572. };
  8573. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8574. return null;
  8575. };
  8576. AbstractMesh.prototype.releaseSubMeshes = function () {
  8577. if (this.subMeshes) {
  8578. while (this.subMeshes.length) {
  8579. this.subMeshes[0].dispose();
  8580. }
  8581. }
  8582. else {
  8583. this.subMeshes = new Array();
  8584. }
  8585. };
  8586. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8587. var index;
  8588. // Skeleton
  8589. this.skeleton = null;
  8590. // Animations
  8591. this.getScene().stopAnimation(this);
  8592. // Physics
  8593. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8594. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8595. }
  8596. // Intersections in progress
  8597. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8598. var other = this._intersectionsInProgress[index];
  8599. var pos = other._intersectionsInProgress.indexOf(this);
  8600. other._intersectionsInProgress.splice(pos, 1);
  8601. }
  8602. this._intersectionsInProgress = [];
  8603. // Edges
  8604. if (this._edgesRenderer) {
  8605. this._edgesRenderer.dispose();
  8606. this._edgesRenderer = null;
  8607. }
  8608. // SubMeshes
  8609. this.releaseSubMeshes();
  8610. // Remove from scene
  8611. this.getScene().removeMesh(this);
  8612. if (!doNotRecurse) {
  8613. // Particles
  8614. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8615. if (this.getScene().particleSystems[index].emitter === this) {
  8616. this.getScene().particleSystems[index].dispose();
  8617. index--;
  8618. }
  8619. }
  8620. // Children
  8621. var objects = this.getScene().meshes.slice(0);
  8622. for (index = 0; index < objects.length; index++) {
  8623. if (objects[index].parent === this) {
  8624. objects[index].dispose();
  8625. }
  8626. }
  8627. }
  8628. else {
  8629. for (index = 0; index < this.getScene().meshes.length; index++) {
  8630. var obj = this.getScene().meshes[index];
  8631. if (obj.parent === this) {
  8632. obj.parent = null;
  8633. obj.computeWorldMatrix(true);
  8634. }
  8635. }
  8636. }
  8637. this._onAfterWorldMatrixUpdate = [];
  8638. this._isDisposed = true;
  8639. // Callback
  8640. if (this.onDispose) {
  8641. this.onDispose();
  8642. }
  8643. };
  8644. // Statics
  8645. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8646. AbstractMesh._BILLBOARDMODE_X = 1;
  8647. AbstractMesh._BILLBOARDMODE_Y = 2;
  8648. AbstractMesh._BILLBOARDMODE_Z = 4;
  8649. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8650. return AbstractMesh;
  8651. })(BABYLON.Node);
  8652. BABYLON.AbstractMesh = AbstractMesh;
  8653. })(BABYLON || (BABYLON = {}));
  8654. var BABYLON;
  8655. (function (BABYLON) {
  8656. var Light = (function (_super) {
  8657. __extends(Light, _super);
  8658. function Light(name, scene) {
  8659. _super.call(this, name, scene);
  8660. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8661. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8662. this.intensity = 1.0;
  8663. this.range = Number.MAX_VALUE;
  8664. this.includeOnlyWithLayerMask = 0;
  8665. this.includedOnlyMeshes = new Array();
  8666. this.excludedMeshes = new Array();
  8667. this.excludeWithLayerMask = 0;
  8668. this._excludedMeshesIds = new Array();
  8669. this._includedOnlyMeshesIds = new Array();
  8670. scene.addLight(this);
  8671. }
  8672. Light.prototype.getShadowGenerator = function () {
  8673. return this._shadowGenerator;
  8674. };
  8675. Light.prototype.getAbsolutePosition = function () {
  8676. return BABYLON.Vector3.Zero();
  8677. };
  8678. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8679. };
  8680. Light.prototype._getWorldMatrix = function () {
  8681. return BABYLON.Matrix.Identity();
  8682. };
  8683. Light.prototype.canAffectMesh = function (mesh) {
  8684. if (!mesh) {
  8685. return true;
  8686. }
  8687. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8688. return false;
  8689. }
  8690. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8691. return false;
  8692. }
  8693. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8694. return false;
  8695. }
  8696. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8697. return false;
  8698. }
  8699. return true;
  8700. };
  8701. Light.prototype.getWorldMatrix = function () {
  8702. this._currentRenderId = this.getScene().getRenderId();
  8703. var worldMatrix = this._getWorldMatrix();
  8704. if (this.parent && this.parent.getWorldMatrix) {
  8705. if (!this._parentedWorldMatrix) {
  8706. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8707. }
  8708. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8709. this._markSyncedWithParent();
  8710. return this._parentedWorldMatrix;
  8711. }
  8712. return worldMatrix;
  8713. };
  8714. Light.prototype.dispose = function () {
  8715. if (this._shadowGenerator) {
  8716. this._shadowGenerator.dispose();
  8717. this._shadowGenerator = null;
  8718. }
  8719. // Animations
  8720. this.getScene().stopAnimation(this);
  8721. // Remove from scene
  8722. this.getScene().removeLight(this);
  8723. };
  8724. Light.prototype.serialize = function () {
  8725. var serializationObject = {};
  8726. serializationObject.name = this.name;
  8727. serializationObject.id = this.id;
  8728. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8729. if (this.intensity) {
  8730. serializationObject.intensity = this.intensity;
  8731. }
  8732. // Parent
  8733. if (this.parent) {
  8734. serializationObject.parentId = this.parent.id;
  8735. }
  8736. serializationObject.range = this.range;
  8737. serializationObject.diffuse = this.diffuse.asArray();
  8738. serializationObject.specular = this.specular.asArray();
  8739. return serializationObject;
  8740. };
  8741. Light.Parse = function (parsedLight, scene) {
  8742. var light;
  8743. switch (parsedLight.type) {
  8744. case 0:
  8745. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8746. break;
  8747. case 1:
  8748. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8749. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8750. break;
  8751. case 2:
  8752. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8753. break;
  8754. case 3:
  8755. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8756. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8757. break;
  8758. }
  8759. light.id = parsedLight.id;
  8760. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8761. if (parsedLight.intensity !== undefined) {
  8762. light.intensity = parsedLight.intensity;
  8763. }
  8764. if (parsedLight.range) {
  8765. light.range = parsedLight.range;
  8766. }
  8767. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8768. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8769. if (parsedLight.excludedMeshesIds) {
  8770. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8771. }
  8772. // Parent
  8773. if (parsedLight.parentId) {
  8774. light._waitingParentId = parsedLight.parentId;
  8775. }
  8776. if (parsedLight.includedOnlyMeshesIds) {
  8777. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8778. }
  8779. // Animations
  8780. if (parsedLight.animations) {
  8781. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8782. var parsedAnimation = parsedLight.animations[animationIndex];
  8783. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8784. }
  8785. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8786. }
  8787. if (parsedLight.autoAnimate) {
  8788. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8789. }
  8790. return light;
  8791. };
  8792. return Light;
  8793. })(BABYLON.Node);
  8794. BABYLON.Light = Light;
  8795. })(BABYLON || (BABYLON = {}));
  8796. var BABYLON;
  8797. (function (BABYLON) {
  8798. var PointLight = (function (_super) {
  8799. __extends(PointLight, _super);
  8800. function PointLight(name, position, scene) {
  8801. _super.call(this, name, scene);
  8802. this.position = position;
  8803. }
  8804. PointLight.prototype.getAbsolutePosition = function () {
  8805. return this.transformedPosition ? this.transformedPosition : this.position;
  8806. };
  8807. PointLight.prototype.computeTransformedPosition = function () {
  8808. if (this.parent && this.parent.getWorldMatrix) {
  8809. if (!this.transformedPosition) {
  8810. this.transformedPosition = BABYLON.Vector3.Zero();
  8811. }
  8812. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8813. return true;
  8814. }
  8815. return false;
  8816. };
  8817. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8818. if (this.parent && this.parent.getWorldMatrix) {
  8819. this.computeTransformedPosition();
  8820. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8821. return;
  8822. }
  8823. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8824. };
  8825. PointLight.prototype.needCube = function () {
  8826. return true;
  8827. };
  8828. PointLight.prototype.supportsVSM = function () {
  8829. return false;
  8830. };
  8831. PointLight.prototype.needRefreshPerFrame = function () {
  8832. return false;
  8833. };
  8834. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8835. switch (faceIndex) {
  8836. case 0:
  8837. return new BABYLON.Vector3(1, 0, 0);
  8838. case 1:
  8839. return new BABYLON.Vector3(-1, 0, 0);
  8840. case 2:
  8841. return new BABYLON.Vector3(0, -1, 0);
  8842. case 3:
  8843. return new BABYLON.Vector3(0, 1, 0);
  8844. case 4:
  8845. return new BABYLON.Vector3(0, 0, 1);
  8846. case 5:
  8847. return new BABYLON.Vector3(0, 0, -1);
  8848. }
  8849. return BABYLON.Vector3.Zero();
  8850. };
  8851. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8852. var activeCamera = this.getScene().activeCamera;
  8853. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8854. };
  8855. PointLight.prototype._getWorldMatrix = function () {
  8856. if (!this._worldMatrix) {
  8857. this._worldMatrix = BABYLON.Matrix.Identity();
  8858. }
  8859. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8860. return this._worldMatrix;
  8861. };
  8862. PointLight.prototype.serialize = function () {
  8863. var serializationObject = _super.prototype.serialize.call(this);
  8864. serializationObject.type = 0;
  8865. serializationObject.position = this.position.asArray();
  8866. return serializationObject;
  8867. };
  8868. return PointLight;
  8869. })(BABYLON.Light);
  8870. BABYLON.PointLight = PointLight;
  8871. })(BABYLON || (BABYLON = {}));
  8872. var BABYLON;
  8873. (function (BABYLON) {
  8874. var SpotLight = (function (_super) {
  8875. __extends(SpotLight, _super);
  8876. function SpotLight(name, position, direction, angle, exponent, scene) {
  8877. _super.call(this, name, scene);
  8878. this.position = position;
  8879. this.direction = direction;
  8880. this.angle = angle;
  8881. this.exponent = exponent;
  8882. }
  8883. SpotLight.prototype.getAbsolutePosition = function () {
  8884. return this.transformedPosition ? this.transformedPosition : this.position;
  8885. };
  8886. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8887. var activeCamera = this.getScene().activeCamera;
  8888. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8889. };
  8890. SpotLight.prototype.needCube = function () {
  8891. return false;
  8892. };
  8893. SpotLight.prototype.supportsVSM = function () {
  8894. return true;
  8895. };
  8896. SpotLight.prototype.needRefreshPerFrame = function () {
  8897. return false;
  8898. };
  8899. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8900. return this.direction;
  8901. };
  8902. SpotLight.prototype.setDirectionToTarget = function (target) {
  8903. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8904. return this.direction;
  8905. };
  8906. SpotLight.prototype.computeTransformedPosition = function () {
  8907. if (this.parent && this.parent.getWorldMatrix) {
  8908. if (!this.transformedPosition) {
  8909. this.transformedPosition = BABYLON.Vector3.Zero();
  8910. }
  8911. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8912. return true;
  8913. }
  8914. return false;
  8915. };
  8916. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8917. var normalizeDirection;
  8918. if (this.parent && this.parent.getWorldMatrix) {
  8919. if (!this._transformedDirection) {
  8920. this._transformedDirection = BABYLON.Vector3.Zero();
  8921. }
  8922. this.computeTransformedPosition();
  8923. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8924. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8925. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8926. }
  8927. else {
  8928. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8929. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8930. }
  8931. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8932. };
  8933. SpotLight.prototype._getWorldMatrix = function () {
  8934. if (!this._worldMatrix) {
  8935. this._worldMatrix = BABYLON.Matrix.Identity();
  8936. }
  8937. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8938. return this._worldMatrix;
  8939. };
  8940. SpotLight.prototype.serialize = function () {
  8941. var serializationObject = _super.prototype.serialize.call(this);
  8942. serializationObject.type = 2;
  8943. serializationObject.position = this.position.asArray();
  8944. serializationObject.direction = this.position.asArray();
  8945. serializationObject.angle = this.angle;
  8946. serializationObject.exponent = this.exponent;
  8947. return serializationObject;
  8948. };
  8949. return SpotLight;
  8950. })(BABYLON.Light);
  8951. BABYLON.SpotLight = SpotLight;
  8952. })(BABYLON || (BABYLON = {}));
  8953. var BABYLON;
  8954. (function (BABYLON) {
  8955. var HemisphericLight = (function (_super) {
  8956. __extends(HemisphericLight, _super);
  8957. function HemisphericLight(name, direction, scene) {
  8958. _super.call(this, name, scene);
  8959. this.direction = direction;
  8960. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8961. }
  8962. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8963. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8964. return this.direction;
  8965. };
  8966. HemisphericLight.prototype.getShadowGenerator = function () {
  8967. return null;
  8968. };
  8969. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8970. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8971. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8972. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8973. };
  8974. HemisphericLight.prototype._getWorldMatrix = function () {
  8975. if (!this._worldMatrix) {
  8976. this._worldMatrix = BABYLON.Matrix.Identity();
  8977. }
  8978. return this._worldMatrix;
  8979. };
  8980. HemisphericLight.prototype.serialize = function () {
  8981. var serializationObject = _super.prototype.serialize.call(this);
  8982. serializationObject.type = 3;
  8983. serializationObject.direction = this.direction.asArray();
  8984. serializationObject.groundColor = this.groundColor.asArray();
  8985. return serializationObject;
  8986. };
  8987. return HemisphericLight;
  8988. })(BABYLON.Light);
  8989. BABYLON.HemisphericLight = HemisphericLight;
  8990. })(BABYLON || (BABYLON = {}));
  8991. var BABYLON;
  8992. (function (BABYLON) {
  8993. var DirectionalLight = (function (_super) {
  8994. __extends(DirectionalLight, _super);
  8995. function DirectionalLight(name, direction, scene) {
  8996. _super.call(this, name, scene);
  8997. this.direction = direction;
  8998. this.shadowOrthoScale = 0.5;
  8999. this.autoUpdateExtends = true;
  9000. // Cache
  9001. this._orthoLeft = Number.MAX_VALUE;
  9002. this._orthoRight = Number.MIN_VALUE;
  9003. this._orthoTop = Number.MIN_VALUE;
  9004. this._orthoBottom = Number.MAX_VALUE;
  9005. this.position = direction.scale(-1);
  9006. }
  9007. DirectionalLight.prototype.getAbsolutePosition = function () {
  9008. return this.transformedPosition ? this.transformedPosition : this.position;
  9009. };
  9010. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9011. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9012. return this.direction;
  9013. };
  9014. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9015. var activeCamera = this.getScene().activeCamera;
  9016. // Check extends
  9017. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9018. var tempVector3 = BABYLON.Vector3.Zero();
  9019. this._orthoLeft = Number.MAX_VALUE;
  9020. this._orthoRight = Number.MIN_VALUE;
  9021. this._orthoTop = Number.MIN_VALUE;
  9022. this._orthoBottom = Number.MAX_VALUE;
  9023. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9024. var mesh = renderList[meshIndex];
  9025. if (!mesh) {
  9026. continue;
  9027. }
  9028. var boundingInfo = mesh.getBoundingInfo();
  9029. if (!boundingInfo) {
  9030. continue;
  9031. }
  9032. var boundingBox = boundingInfo.boundingBox;
  9033. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9034. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9035. if (tempVector3.x < this._orthoLeft)
  9036. this._orthoLeft = tempVector3.x;
  9037. if (tempVector3.y < this._orthoBottom)
  9038. this._orthoBottom = tempVector3.y;
  9039. if (tempVector3.x > this._orthoRight)
  9040. this._orthoRight = tempVector3.x;
  9041. if (tempVector3.y > this._orthoTop)
  9042. this._orthoTop = tempVector3.y;
  9043. }
  9044. }
  9045. }
  9046. var xOffset = this._orthoRight - this._orthoLeft;
  9047. var yOffset = this._orthoTop - this._orthoBottom;
  9048. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  9049. };
  9050. DirectionalLight.prototype.supportsVSM = function () {
  9051. return true;
  9052. };
  9053. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9054. return true;
  9055. };
  9056. DirectionalLight.prototype.needCube = function () {
  9057. return false;
  9058. };
  9059. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9060. return this.direction;
  9061. };
  9062. DirectionalLight.prototype.computeTransformedPosition = function () {
  9063. if (this.parent && this.parent.getWorldMatrix) {
  9064. if (!this.transformedPosition) {
  9065. this.transformedPosition = BABYLON.Vector3.Zero();
  9066. }
  9067. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9068. return true;
  9069. }
  9070. return false;
  9071. };
  9072. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9073. if (this.parent && this.parent.getWorldMatrix) {
  9074. if (!this._transformedDirection) {
  9075. this._transformedDirection = BABYLON.Vector3.Zero();
  9076. }
  9077. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9078. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9079. return;
  9080. }
  9081. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9082. };
  9083. DirectionalLight.prototype._getWorldMatrix = function () {
  9084. if (!this._worldMatrix) {
  9085. this._worldMatrix = BABYLON.Matrix.Identity();
  9086. }
  9087. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9088. return this._worldMatrix;
  9089. };
  9090. DirectionalLight.prototype.serialize = function () {
  9091. var serializationObject = _super.prototype.serialize.call(this);
  9092. serializationObject.type = 1;
  9093. serializationObject.position = this.position.asArray();
  9094. serializationObject.direction = this.direction.asArray();
  9095. return serializationObject;
  9096. };
  9097. return DirectionalLight;
  9098. })(BABYLON.Light);
  9099. BABYLON.DirectionalLight = DirectionalLight;
  9100. })(BABYLON || (BABYLON = {}));
  9101. var BABYLON;
  9102. (function (BABYLON) {
  9103. var ShadowGenerator = (function () {
  9104. function ShadowGenerator(mapSize, light) {
  9105. var _this = this;
  9106. // Members
  9107. this._filter = ShadowGenerator.FILTER_NONE;
  9108. this.blurScale = 2;
  9109. this._blurBoxOffset = 0;
  9110. this._bias = 0.00005;
  9111. this._lightDirection = BABYLON.Vector3.Zero();
  9112. this.forceBackFacesOnly = false;
  9113. this._darkness = 0;
  9114. this._transparencyShadow = false;
  9115. this._viewMatrix = BABYLON.Matrix.Zero();
  9116. this._projectionMatrix = BABYLON.Matrix.Zero();
  9117. this._transformMatrix = BABYLON.Matrix.Zero();
  9118. this._worldViewProjection = BABYLON.Matrix.Zero();
  9119. this._currentFaceIndex = 0;
  9120. this._currentFaceIndexCache = 0;
  9121. this._light = light;
  9122. this._scene = light.getScene();
  9123. this._mapSize = mapSize;
  9124. light._shadowGenerator = this;
  9125. // Render target
  9126. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9127. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9128. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9129. this._shadowMap.anisotropicFilteringLevel = 1;
  9130. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9131. this._shadowMap.renderParticles = false;
  9132. this._shadowMap.onBeforeRender = function (faceIndex) {
  9133. _this._currentFaceIndex = faceIndex;
  9134. };
  9135. this._shadowMap.onAfterUnbind = function () {
  9136. if (!_this.useBlurVarianceShadowMap) {
  9137. return;
  9138. }
  9139. if (!_this._shadowMap2) {
  9140. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9141. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9142. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9143. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9144. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9145. _this._downSamplePostprocess.onApply = function (effect) {
  9146. effect.setTexture("textureSampler", _this._shadowMap);
  9147. };
  9148. _this.blurBoxOffset = 1;
  9149. }
  9150. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9151. };
  9152. // Custom render function
  9153. var renderSubMesh = function (subMesh) {
  9154. var mesh = subMesh.getRenderingMesh();
  9155. var scene = _this._scene;
  9156. var engine = scene.getEngine();
  9157. // Culling
  9158. engine.setState(subMesh.getMaterial().backFaceCulling);
  9159. // Managing instances
  9160. var batch = mesh._getInstancesRenderList(subMesh._id);
  9161. if (batch.mustReturn) {
  9162. return;
  9163. }
  9164. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9165. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9166. engine.enableEffect(_this._effect);
  9167. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9168. var material = subMesh.getMaterial();
  9169. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9170. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9171. if (_this.getLight().needCube()) {
  9172. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9173. }
  9174. // Alpha test
  9175. if (material && material.needAlphaTesting()) {
  9176. var alphaTexture = material.getAlphaTestTexture();
  9177. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9178. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9179. }
  9180. // Bones
  9181. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9182. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9183. }
  9184. if (_this.forceBackFacesOnly) {
  9185. engine.setState(true, 0, false, true);
  9186. }
  9187. // Draw
  9188. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9189. if (_this.forceBackFacesOnly) {
  9190. engine.setState(true, 0, false, false);
  9191. }
  9192. }
  9193. else {
  9194. // Need to reset refresh rate of the shadowMap
  9195. _this._shadowMap.resetRefreshCounter();
  9196. }
  9197. };
  9198. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9199. var index;
  9200. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9201. renderSubMesh(opaqueSubMeshes.data[index]);
  9202. }
  9203. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9204. renderSubMesh(alphaTestSubMeshes.data[index]);
  9205. }
  9206. if (_this._transparencyShadow) {
  9207. for (index = 0; index < transparentSubMeshes.length; index++) {
  9208. renderSubMesh(transparentSubMeshes.data[index]);
  9209. }
  9210. }
  9211. };
  9212. this._shadowMap.onClear = function (engine) {
  9213. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9214. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9215. }
  9216. else {
  9217. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9218. }
  9219. };
  9220. }
  9221. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9222. // Static
  9223. get: function () {
  9224. return ShadowGenerator._FILTER_NONE;
  9225. },
  9226. enumerable: true,
  9227. configurable: true
  9228. });
  9229. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9230. get: function () {
  9231. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9232. },
  9233. enumerable: true,
  9234. configurable: true
  9235. });
  9236. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9237. get: function () {
  9238. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9239. },
  9240. enumerable: true,
  9241. configurable: true
  9242. });
  9243. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9244. get: function () {
  9245. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9246. },
  9247. enumerable: true,
  9248. configurable: true
  9249. });
  9250. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9251. get: function () {
  9252. return this._bias;
  9253. },
  9254. set: function (bias) {
  9255. this._bias = bias;
  9256. },
  9257. enumerable: true,
  9258. configurable: true
  9259. });
  9260. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9261. get: function () {
  9262. return this._blurBoxOffset;
  9263. },
  9264. set: function (value) {
  9265. var _this = this;
  9266. if (this._blurBoxOffset === value) {
  9267. return;
  9268. }
  9269. this._blurBoxOffset = value;
  9270. if (this._boxBlurPostprocess) {
  9271. this._boxBlurPostprocess.dispose();
  9272. }
  9273. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9274. this._boxBlurPostprocess.onApply = function (effect) {
  9275. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9276. };
  9277. },
  9278. enumerable: true,
  9279. configurable: true
  9280. });
  9281. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9282. get: function () {
  9283. return this._filter;
  9284. },
  9285. set: function (value) {
  9286. if (this._filter === value) {
  9287. return;
  9288. }
  9289. this._filter = value;
  9290. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9291. this._shadowMap.anisotropicFilteringLevel = 16;
  9292. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9293. }
  9294. else {
  9295. this._shadowMap.anisotropicFilteringLevel = 1;
  9296. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9297. }
  9298. },
  9299. enumerable: true,
  9300. configurable: true
  9301. });
  9302. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9303. get: function () {
  9304. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9305. },
  9306. set: function (value) {
  9307. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9308. },
  9309. enumerable: true,
  9310. configurable: true
  9311. });
  9312. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9313. get: function () {
  9314. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9315. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9316. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9317. },
  9318. set: function (value) {
  9319. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9320. },
  9321. enumerable: true,
  9322. configurable: true
  9323. });
  9324. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9325. get: function () {
  9326. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9327. },
  9328. set: function (value) {
  9329. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9330. },
  9331. enumerable: true,
  9332. configurable: true
  9333. });
  9334. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9335. var defines = [];
  9336. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9337. defines.push("#define VSM");
  9338. }
  9339. if (this.getLight().needCube()) {
  9340. defines.push("#define CUBEMAP");
  9341. }
  9342. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9343. var mesh = subMesh.getMesh();
  9344. var material = subMesh.getMaterial();
  9345. // Alpha test
  9346. if (material && material.needAlphaTesting()) {
  9347. defines.push("#define ALPHATEST");
  9348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9349. attribs.push(BABYLON.VertexBuffer.UVKind);
  9350. defines.push("#define UV1");
  9351. }
  9352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9354. defines.push("#define UV2");
  9355. }
  9356. }
  9357. // Bones
  9358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9359. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9360. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9361. if (mesh.numBoneInfluencers > 4) {
  9362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9364. }
  9365. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9366. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9367. }
  9368. else {
  9369. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9370. }
  9371. // Instances
  9372. if (useInstances) {
  9373. defines.push("#define INSTANCES");
  9374. attribs.push("world0");
  9375. attribs.push("world1");
  9376. attribs.push("world2");
  9377. attribs.push("world3");
  9378. }
  9379. // Get correct effect
  9380. var join = defines.join("\n");
  9381. if (this._cachedDefines !== join) {
  9382. this._cachedDefines = join;
  9383. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9384. }
  9385. return this._effect.isReady();
  9386. };
  9387. ShadowGenerator.prototype.getShadowMap = function () {
  9388. return this._shadowMap;
  9389. };
  9390. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9391. if (this._shadowMap2) {
  9392. return this._shadowMap2;
  9393. }
  9394. return this._shadowMap;
  9395. };
  9396. ShadowGenerator.prototype.getLight = function () {
  9397. return this._light;
  9398. };
  9399. // Methods
  9400. ShadowGenerator.prototype.getTransformMatrix = function () {
  9401. var scene = this._scene;
  9402. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9403. return this._transformMatrix;
  9404. }
  9405. this._currentRenderID = scene.getRenderId();
  9406. this._currentFaceIndexCache = this._currentFaceIndex;
  9407. var lightPosition = this._light.position;
  9408. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9409. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9410. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9411. }
  9412. if (this._light.computeTransformedPosition()) {
  9413. lightPosition = this._light.transformedPosition;
  9414. }
  9415. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9416. this._cachedPosition = lightPosition.clone();
  9417. this._cachedDirection = this._lightDirection.clone();
  9418. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9419. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9420. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9421. }
  9422. return this._transformMatrix;
  9423. };
  9424. ShadowGenerator.prototype.getDarkness = function () {
  9425. return this._darkness;
  9426. };
  9427. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9428. if (darkness >= 1.0)
  9429. this._darkness = 1.0;
  9430. else if (darkness <= 0.0)
  9431. this._darkness = 0.0;
  9432. else
  9433. this._darkness = darkness;
  9434. };
  9435. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9436. this._transparencyShadow = hasShadow;
  9437. };
  9438. ShadowGenerator.prototype._packHalf = function (depth) {
  9439. var scale = depth * 255.0;
  9440. var fract = scale - Math.floor(scale);
  9441. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9442. };
  9443. ShadowGenerator.prototype.dispose = function () {
  9444. this._shadowMap.dispose();
  9445. if (this._shadowMap2) {
  9446. this._shadowMap2.dispose();
  9447. }
  9448. if (this._downSamplePostprocess) {
  9449. this._downSamplePostprocess.dispose();
  9450. }
  9451. if (this._boxBlurPostprocess) {
  9452. this._boxBlurPostprocess.dispose();
  9453. }
  9454. };
  9455. ShadowGenerator.prototype.serialize = function () {
  9456. var serializationObject = {};
  9457. serializationObject.lightId = this._light.id;
  9458. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9459. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9460. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9461. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9462. serializationObject.renderList = [];
  9463. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9464. var mesh = this.getShadowMap().renderList[meshIndex];
  9465. serializationObject.renderList.push(mesh.id);
  9466. }
  9467. return serializationObject;
  9468. };
  9469. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9470. //casting to point light, as light is missing the position attr and typescript complains.
  9471. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9472. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9473. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9474. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9475. shadowGenerator.getShadowMap().renderList.push(mesh);
  9476. }
  9477. if (parsedShadowGenerator.usePoissonSampling) {
  9478. shadowGenerator.usePoissonSampling = true;
  9479. }
  9480. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9481. shadowGenerator.useVarianceShadowMap = true;
  9482. }
  9483. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9484. shadowGenerator.useBlurVarianceShadowMap = true;
  9485. if (parsedShadowGenerator.blurScale) {
  9486. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9487. }
  9488. if (parsedShadowGenerator.blurBoxOffset) {
  9489. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9490. }
  9491. }
  9492. if (parsedShadowGenerator.bias !== undefined) {
  9493. shadowGenerator.bias = parsedShadowGenerator.bias;
  9494. }
  9495. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9496. return shadowGenerator;
  9497. };
  9498. ShadowGenerator._FILTER_NONE = 0;
  9499. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9500. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9501. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9502. return ShadowGenerator;
  9503. })();
  9504. BABYLON.ShadowGenerator = ShadowGenerator;
  9505. })(BABYLON || (BABYLON = {}));
  9506. var BABYLON;
  9507. (function (BABYLON) {
  9508. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9509. if (boxMin.x > sphereCenter.x + sphereRadius)
  9510. return false;
  9511. if (sphereCenter.x - sphereRadius > boxMax.x)
  9512. return false;
  9513. if (boxMin.y > sphereCenter.y + sphereRadius)
  9514. return false;
  9515. if (sphereCenter.y - sphereRadius > boxMax.y)
  9516. return false;
  9517. if (boxMin.z > sphereCenter.z + sphereRadius)
  9518. return false;
  9519. if (sphereCenter.z - sphereRadius > boxMax.z)
  9520. return false;
  9521. return true;
  9522. };
  9523. var getLowestRoot = function (a, b, c, maxR) {
  9524. var determinant = b * b - 4.0 * a * c;
  9525. var result = { root: 0, found: false };
  9526. if (determinant < 0)
  9527. return result;
  9528. var sqrtD = Math.sqrt(determinant);
  9529. var r1 = (-b - sqrtD) / (2.0 * a);
  9530. var r2 = (-b + sqrtD) / (2.0 * a);
  9531. if (r1 > r2) {
  9532. var temp = r2;
  9533. r2 = r1;
  9534. r1 = temp;
  9535. }
  9536. if (r1 > 0 && r1 < maxR) {
  9537. result.root = r1;
  9538. result.found = true;
  9539. return result;
  9540. }
  9541. if (r2 > 0 && r2 < maxR) {
  9542. result.root = r2;
  9543. result.found = true;
  9544. return result;
  9545. }
  9546. return result;
  9547. };
  9548. var Collider = (function () {
  9549. function Collider() {
  9550. this.radius = new BABYLON.Vector3(1, 1, 1);
  9551. this.retry = 0;
  9552. this.basePointWorld = BABYLON.Vector3.Zero();
  9553. this.velocityWorld = BABYLON.Vector3.Zero();
  9554. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9555. this._collisionPoint = BABYLON.Vector3.Zero();
  9556. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9557. this._tempVector = BABYLON.Vector3.Zero();
  9558. this._tempVector2 = BABYLON.Vector3.Zero();
  9559. this._tempVector3 = BABYLON.Vector3.Zero();
  9560. this._tempVector4 = BABYLON.Vector3.Zero();
  9561. this._edge = BABYLON.Vector3.Zero();
  9562. this._baseToVertex = BABYLON.Vector3.Zero();
  9563. this._destinationPoint = BABYLON.Vector3.Zero();
  9564. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9565. this._displacementVector = BABYLON.Vector3.Zero();
  9566. }
  9567. // Methods
  9568. Collider.prototype._initialize = function (source, dir, e) {
  9569. this.velocity = dir;
  9570. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9571. this.basePoint = source;
  9572. source.multiplyToRef(this.radius, this.basePointWorld);
  9573. dir.multiplyToRef(this.radius, this.velocityWorld);
  9574. this.velocityWorldLength = this.velocityWorld.length();
  9575. this.epsilon = e;
  9576. this.collisionFound = false;
  9577. };
  9578. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9579. pa.subtractToRef(point, this._tempVector);
  9580. pb.subtractToRef(point, this._tempVector2);
  9581. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9582. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9583. if (d < 0)
  9584. return false;
  9585. pc.subtractToRef(point, this._tempVector3);
  9586. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9587. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9588. if (d < 0)
  9589. return false;
  9590. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9591. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9592. return d >= 0;
  9593. };
  9594. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9595. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9596. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9597. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9598. return false;
  9599. }
  9600. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9601. return false;
  9602. return true;
  9603. };
  9604. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9605. var t0;
  9606. var embeddedInPlane = false;
  9607. //defensive programming, actually not needed.
  9608. if (!trianglePlaneArray) {
  9609. trianglePlaneArray = [];
  9610. }
  9611. if (!trianglePlaneArray[faceIndex]) {
  9612. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9613. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9614. }
  9615. var trianglePlane = trianglePlaneArray[faceIndex];
  9616. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9617. return;
  9618. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9619. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9620. if (normalDotVelocity == 0) {
  9621. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9622. return;
  9623. embeddedInPlane = true;
  9624. t0 = 0;
  9625. }
  9626. else {
  9627. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9628. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9629. if (t0 > t1) {
  9630. var temp = t1;
  9631. t1 = t0;
  9632. t0 = temp;
  9633. }
  9634. if (t0 > 1.0 || t1 < 0.0)
  9635. return;
  9636. if (t0 < 0)
  9637. t0 = 0;
  9638. if (t0 > 1.0)
  9639. t0 = 1.0;
  9640. }
  9641. this._collisionPoint.copyFromFloats(0, 0, 0);
  9642. var found = false;
  9643. var t = 1.0;
  9644. if (!embeddedInPlane) {
  9645. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9646. this.velocity.scaleToRef(t0, this._tempVector);
  9647. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9648. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9649. found = true;
  9650. t = t0;
  9651. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9652. }
  9653. }
  9654. if (!found) {
  9655. var velocitySquaredLength = this.velocity.lengthSquared();
  9656. var a = velocitySquaredLength;
  9657. this.basePoint.subtractToRef(p1, this._tempVector);
  9658. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9659. var c = this._tempVector.lengthSquared() - 1.0;
  9660. var lowestRoot = getLowestRoot(a, b, c, t);
  9661. if (lowestRoot.found) {
  9662. t = lowestRoot.root;
  9663. found = true;
  9664. this._collisionPoint.copyFrom(p1);
  9665. }
  9666. this.basePoint.subtractToRef(p2, this._tempVector);
  9667. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9668. c = this._tempVector.lengthSquared() - 1.0;
  9669. lowestRoot = getLowestRoot(a, b, c, t);
  9670. if (lowestRoot.found) {
  9671. t = lowestRoot.root;
  9672. found = true;
  9673. this._collisionPoint.copyFrom(p2);
  9674. }
  9675. this.basePoint.subtractToRef(p3, this._tempVector);
  9676. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9677. c = this._tempVector.lengthSquared() - 1.0;
  9678. lowestRoot = getLowestRoot(a, b, c, t);
  9679. if (lowestRoot.found) {
  9680. t = lowestRoot.root;
  9681. found = true;
  9682. this._collisionPoint.copyFrom(p3);
  9683. }
  9684. p2.subtractToRef(p1, this._edge);
  9685. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9686. var edgeSquaredLength = this._edge.lengthSquared();
  9687. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9688. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9689. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9690. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9691. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9692. lowestRoot = getLowestRoot(a, b, c, t);
  9693. if (lowestRoot.found) {
  9694. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9695. if (f >= 0.0 && f <= 1.0) {
  9696. t = lowestRoot.root;
  9697. found = true;
  9698. this._edge.scaleInPlace(f);
  9699. p1.addToRef(this._edge, this._collisionPoint);
  9700. }
  9701. }
  9702. p3.subtractToRef(p2, this._edge);
  9703. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9704. edgeSquaredLength = this._edge.lengthSquared();
  9705. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9706. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9707. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9708. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9709. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9710. lowestRoot = getLowestRoot(a, b, c, t);
  9711. if (lowestRoot.found) {
  9712. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9713. if (f >= 0.0 && f <= 1.0) {
  9714. t = lowestRoot.root;
  9715. found = true;
  9716. this._edge.scaleInPlace(f);
  9717. p2.addToRef(this._edge, this._collisionPoint);
  9718. }
  9719. }
  9720. p1.subtractToRef(p3, this._edge);
  9721. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9722. edgeSquaredLength = this._edge.lengthSquared();
  9723. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9724. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9725. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9726. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9727. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9728. lowestRoot = getLowestRoot(a, b, c, t);
  9729. if (lowestRoot.found) {
  9730. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9731. if (f >= 0.0 && f <= 1.0) {
  9732. t = lowestRoot.root;
  9733. found = true;
  9734. this._edge.scaleInPlace(f);
  9735. p3.addToRef(this._edge, this._collisionPoint);
  9736. }
  9737. }
  9738. }
  9739. if (found) {
  9740. var distToCollision = t * this.velocity.length();
  9741. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9742. if (!this.intersectionPoint) {
  9743. this.intersectionPoint = this._collisionPoint.clone();
  9744. }
  9745. else {
  9746. this.intersectionPoint.copyFrom(this._collisionPoint);
  9747. }
  9748. this.nearestDistance = distToCollision;
  9749. this.collisionFound = true;
  9750. }
  9751. }
  9752. };
  9753. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9754. for (var i = indexStart; i < indexEnd; i += 3) {
  9755. var p1 = pts[indices[i] - decal];
  9756. var p2 = pts[indices[i + 1] - decal];
  9757. var p3 = pts[indices[i + 2] - decal];
  9758. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9759. }
  9760. };
  9761. Collider.prototype._getResponse = function (pos, vel) {
  9762. pos.addToRef(vel, this._destinationPoint);
  9763. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9764. this.basePoint.addToRef(vel, pos);
  9765. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9766. this._slidePlaneNormal.normalize();
  9767. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9768. pos.addInPlace(this._displacementVector);
  9769. this.intersectionPoint.addInPlace(this._displacementVector);
  9770. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9771. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9772. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9773. };
  9774. return Collider;
  9775. })();
  9776. BABYLON.Collider = Collider;
  9777. })(BABYLON || (BABYLON = {}));
  9778. var BABYLON;
  9779. (function (BABYLON) {
  9780. //WebWorker code will be inserted to this variable.
  9781. BABYLON.CollisionWorker = "";
  9782. (function (WorkerTaskType) {
  9783. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9784. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9785. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9786. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9787. var WorkerTaskType = BABYLON.WorkerTaskType;
  9788. (function (WorkerReplyType) {
  9789. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9790. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9791. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9792. var WorkerReplyType = BABYLON.WorkerReplyType;
  9793. var CollisionCoordinatorWorker = (function () {
  9794. function CollisionCoordinatorWorker() {
  9795. var _this = this;
  9796. this._scaledPosition = BABYLON.Vector3.Zero();
  9797. this._scaledVelocity = BABYLON.Vector3.Zero();
  9798. this.onMeshUpdated = function (mesh) {
  9799. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9800. };
  9801. this.onGeometryUpdated = function (geometry) {
  9802. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9803. };
  9804. this._afterRender = function () {
  9805. if (!_this._init)
  9806. return;
  9807. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9808. return;
  9809. }
  9810. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9811. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9812. if (_this._runningUpdated > 4) {
  9813. return;
  9814. }
  9815. ++_this._runningUpdated;
  9816. var payload = {
  9817. updatedMeshes: _this._addUpdateMeshesList,
  9818. updatedGeometries: _this._addUpdateGeometriesList,
  9819. removedGeometries: _this._toRemoveGeometryArray,
  9820. removedMeshes: _this._toRemoveMeshesArray
  9821. };
  9822. var message = {
  9823. payload: payload,
  9824. taskType: WorkerTaskType.UPDATE
  9825. };
  9826. var serializable = [];
  9827. for (var id in payload.updatedGeometries) {
  9828. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9829. //prepare transferables
  9830. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9831. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9832. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9833. }
  9834. }
  9835. _this._worker.postMessage(message, serializable);
  9836. _this._addUpdateMeshesList = {};
  9837. _this._addUpdateGeometriesList = {};
  9838. _this._toRemoveGeometryArray = [];
  9839. _this._toRemoveMeshesArray = [];
  9840. };
  9841. this._onMessageFromWorker = function (e) {
  9842. var returnData = e.data;
  9843. if (returnData.error != WorkerReplyType.SUCCESS) {
  9844. //TODO what errors can be returned from the worker?
  9845. BABYLON.Tools.Warn("error returned from worker!");
  9846. return;
  9847. }
  9848. switch (returnData.taskType) {
  9849. case WorkerTaskType.INIT:
  9850. _this._init = true;
  9851. //Update the worked with ALL of the scene's current state
  9852. _this._scene.meshes.forEach(function (mesh) {
  9853. _this.onMeshAdded(mesh);
  9854. });
  9855. _this._scene.getGeometries().forEach(function (geometry) {
  9856. _this.onGeometryAdded(geometry);
  9857. });
  9858. break;
  9859. case WorkerTaskType.UPDATE:
  9860. _this._runningUpdated--;
  9861. break;
  9862. case WorkerTaskType.COLLIDE:
  9863. _this._runningCollisionTask = false;
  9864. var returnPayload = returnData.payload;
  9865. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9866. return;
  9867. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9868. //cleanup
  9869. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9870. break;
  9871. }
  9872. };
  9873. this._collisionsCallbackArray = [];
  9874. this._init = false;
  9875. this._runningUpdated = 0;
  9876. this._runningCollisionTask = false;
  9877. this._addUpdateMeshesList = {};
  9878. this._addUpdateGeometriesList = {};
  9879. this._toRemoveGeometryArray = [];
  9880. this._toRemoveMeshesArray = [];
  9881. }
  9882. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9883. if (!this._init)
  9884. return;
  9885. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9886. return;
  9887. position.divideToRef(collider.radius, this._scaledPosition);
  9888. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9889. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9890. var payload = {
  9891. collider: {
  9892. position: this._scaledPosition.asArray(),
  9893. velocity: this._scaledVelocity.asArray(),
  9894. radius: collider.radius.asArray()
  9895. },
  9896. collisionId: collisionIndex,
  9897. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9898. maximumRetry: maximumRetry
  9899. };
  9900. var message = {
  9901. payload: payload,
  9902. taskType: WorkerTaskType.COLLIDE
  9903. };
  9904. this._worker.postMessage(message);
  9905. };
  9906. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9907. this._scene = scene;
  9908. this._scene.registerAfterRender(this._afterRender);
  9909. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9910. this._worker = new Worker(workerUrl);
  9911. this._worker.onmessage = this._onMessageFromWorker;
  9912. var message = {
  9913. payload: {},
  9914. taskType: WorkerTaskType.INIT
  9915. };
  9916. this._worker.postMessage(message);
  9917. };
  9918. CollisionCoordinatorWorker.prototype.destroy = function () {
  9919. this._scene.unregisterAfterRender(this._afterRender);
  9920. this._worker.terminate();
  9921. };
  9922. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9923. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9924. this.onMeshUpdated(mesh);
  9925. };
  9926. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9927. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9928. };
  9929. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9930. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9931. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9932. this.onGeometryUpdated(geometry);
  9933. };
  9934. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9935. this._toRemoveGeometryArray.push(geometry.id);
  9936. };
  9937. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9938. var submeshes = [];
  9939. if (mesh.subMeshes) {
  9940. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9941. return {
  9942. position: idx,
  9943. verticesStart: sm.verticesStart,
  9944. verticesCount: sm.verticesCount,
  9945. indexStart: sm.indexStart,
  9946. indexCount: sm.indexCount,
  9947. hasMaterial: !!sm.getMaterial(),
  9948. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9949. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9950. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9951. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9952. };
  9953. });
  9954. }
  9955. var geometryId = null;
  9956. if (mesh instanceof BABYLON.Mesh) {
  9957. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9958. }
  9959. else if (mesh instanceof BABYLON.InstancedMesh) {
  9960. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9961. }
  9962. return {
  9963. uniqueId: mesh.uniqueId,
  9964. id: mesh.id,
  9965. name: mesh.name,
  9966. geometryId: geometryId,
  9967. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9968. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9969. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9970. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9971. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9972. subMeshes: submeshes,
  9973. checkCollisions: mesh.checkCollisions
  9974. };
  9975. };
  9976. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9977. return {
  9978. id: geometry.id,
  9979. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9980. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9981. indices: new Int32Array(geometry.getIndices() || []),
  9982. };
  9983. };
  9984. return CollisionCoordinatorWorker;
  9985. })();
  9986. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9987. var CollisionCoordinatorLegacy = (function () {
  9988. function CollisionCoordinatorLegacy() {
  9989. this._scaledPosition = BABYLON.Vector3.Zero();
  9990. this._scaledVelocity = BABYLON.Vector3.Zero();
  9991. this._finalPosition = BABYLON.Vector3.Zero();
  9992. }
  9993. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9994. position.divideToRef(collider.radius, this._scaledPosition);
  9995. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9996. collider.collidedMesh = null;
  9997. collider.retry = 0;
  9998. collider.initialVelocity = this._scaledVelocity;
  9999. collider.initialPosition = this._scaledPosition;
  10000. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10001. this._finalPosition.multiplyInPlace(collider.radius);
  10002. //run the callback
  10003. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10004. };
  10005. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10006. this._scene = scene;
  10007. };
  10008. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10009. //Legacy need no destruction method.
  10010. };
  10011. //No update in legacy mode
  10012. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10013. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10014. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10015. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10016. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10017. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10018. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10019. if (excludedMesh === void 0) { excludedMesh = null; }
  10020. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10021. if (collider.retry >= maximumRetry) {
  10022. finalPosition.copyFrom(position);
  10023. return;
  10024. }
  10025. collider._initialize(position, velocity, closeDistance);
  10026. // Check all meshes
  10027. for (var index = 0; index < this._scene.meshes.length; index++) {
  10028. var mesh = this._scene.meshes[index];
  10029. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10030. mesh._checkCollision(collider);
  10031. }
  10032. }
  10033. if (!collider.collisionFound) {
  10034. position.addToRef(velocity, finalPosition);
  10035. return;
  10036. }
  10037. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10038. collider._getResponse(position, velocity);
  10039. }
  10040. if (velocity.length() <= closeDistance) {
  10041. finalPosition.copyFrom(position);
  10042. return;
  10043. }
  10044. collider.retry++;
  10045. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10046. };
  10047. return CollisionCoordinatorLegacy;
  10048. })();
  10049. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10050. })(BABYLON || (BABYLON = {}));
  10051. var BABYLON;
  10052. (function (BABYLON) {
  10053. var VRCameraMetrics = (function () {
  10054. function VRCameraMetrics() {
  10055. this.compensateDistortion = true;
  10056. }
  10057. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  10058. get: function () {
  10059. return this.hResolution / (2 * this.vResolution);
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  10065. get: function () {
  10066. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  10072. get: function () {
  10073. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10074. var h = (4 * meters) / this.hScreenSize;
  10075. return BABYLON.Matrix.Translation(h, 0, 0);
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  10081. get: function () {
  10082. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10083. var h = (4 * meters) / this.hScreenSize;
  10084. return BABYLON.Matrix.Translation(-h, 0, 0);
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  10090. get: function () {
  10091. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  10092. },
  10093. enumerable: true,
  10094. configurable: true
  10095. });
  10096. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  10097. get: function () {
  10098. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  10099. },
  10100. enumerable: true,
  10101. configurable: true
  10102. });
  10103. VRCameraMetrics.GetDefault = function () {
  10104. var result = new VRCameraMetrics();
  10105. result.hResolution = 1280;
  10106. result.vResolution = 800;
  10107. result.hScreenSize = 0.149759993;
  10108. result.vScreenSize = 0.0935999975;
  10109. result.vScreenCenter = 0.0467999987,
  10110. result.eyeToScreenDistance = 0.0410000011;
  10111. result.lensSeparationDistance = 0.0635000020;
  10112. result.interpupillaryDistance = 0.0640000030;
  10113. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  10114. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  10115. result.postProcessScaleFactor = 1.714605507808412;
  10116. result.lensCenterOffset = 0.151976421;
  10117. return result;
  10118. };
  10119. return VRCameraMetrics;
  10120. })();
  10121. BABYLON.VRCameraMetrics = VRCameraMetrics;
  10122. var Camera = (function (_super) {
  10123. __extends(Camera, _super);
  10124. function Camera(name, position, scene) {
  10125. _super.call(this, name, scene);
  10126. this.position = position;
  10127. // Members
  10128. this.upVector = BABYLON.Vector3.Up();
  10129. this.orthoLeft = null;
  10130. this.orthoRight = null;
  10131. this.orthoBottom = null;
  10132. this.orthoTop = null;
  10133. this.fov = 0.8;
  10134. this.minZ = 1.0;
  10135. this.maxZ = 10000.0;
  10136. this.inertia = 0.9;
  10137. this.mode = Camera.PERSPECTIVE_CAMERA;
  10138. this.isIntermediate = false;
  10139. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10140. this.layerMask = 0x0FFFFFFF;
  10141. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10142. // Camera rig members
  10143. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10144. this._rigCameras = new Array();
  10145. // Cache
  10146. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10147. this._projectionMatrix = new BABYLON.Matrix();
  10148. this._postProcesses = new Array();
  10149. this._postProcessesTakenIndices = [];
  10150. this._activeMeshes = new BABYLON.SmartArray(256);
  10151. this._globalPosition = BABYLON.Vector3.Zero();
  10152. scene.addCamera(this);
  10153. if (!scene.activeCamera) {
  10154. scene.activeCamera = this;
  10155. }
  10156. }
  10157. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10158. get: function () {
  10159. return Camera._PERSPECTIVE_CAMERA;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10165. get: function () {
  10166. return Camera._ORTHOGRAPHIC_CAMERA;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10172. get: function () {
  10173. return Camera._FOVMODE_VERTICAL_FIXED;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10179. get: function () {
  10180. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10181. },
  10182. enumerable: true,
  10183. configurable: true
  10184. });
  10185. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10186. get: function () {
  10187. return Camera._RIG_MODE_NONE;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10193. get: function () {
  10194. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10195. },
  10196. enumerable: true,
  10197. configurable: true
  10198. });
  10199. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10200. get: function () {
  10201. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10207. get: function () {
  10208. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10209. },
  10210. enumerable: true,
  10211. configurable: true
  10212. });
  10213. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10214. get: function () {
  10215. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10221. get: function () {
  10222. return Camera._RIG_MODE_VR;
  10223. },
  10224. enumerable: true,
  10225. configurable: true
  10226. });
  10227. Object.defineProperty(Camera.prototype, "globalPosition", {
  10228. get: function () {
  10229. return this._globalPosition;
  10230. },
  10231. enumerable: true,
  10232. configurable: true
  10233. });
  10234. Camera.prototype.getActiveMeshes = function () {
  10235. return this._activeMeshes;
  10236. };
  10237. Camera.prototype.isActiveMesh = function (mesh) {
  10238. return (this._activeMeshes.indexOf(mesh) !== -1);
  10239. };
  10240. //Cache
  10241. Camera.prototype._initCache = function () {
  10242. _super.prototype._initCache.call(this);
  10243. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10244. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10245. this._cache.mode = undefined;
  10246. this._cache.minZ = undefined;
  10247. this._cache.maxZ = undefined;
  10248. this._cache.fov = undefined;
  10249. this._cache.aspectRatio = undefined;
  10250. this._cache.orthoLeft = undefined;
  10251. this._cache.orthoRight = undefined;
  10252. this._cache.orthoBottom = undefined;
  10253. this._cache.orthoTop = undefined;
  10254. this._cache.renderWidth = undefined;
  10255. this._cache.renderHeight = undefined;
  10256. };
  10257. Camera.prototype._updateCache = function (ignoreParentClass) {
  10258. if (!ignoreParentClass) {
  10259. _super.prototype._updateCache.call(this);
  10260. }
  10261. var engine = this.getEngine();
  10262. this._cache.position.copyFrom(this.position);
  10263. this._cache.upVector.copyFrom(this.upVector);
  10264. this._cache.mode = this.mode;
  10265. this._cache.minZ = this.minZ;
  10266. this._cache.maxZ = this.maxZ;
  10267. this._cache.fov = this.fov;
  10268. this._cache.aspectRatio = engine.getAspectRatio(this);
  10269. this._cache.orthoLeft = this.orthoLeft;
  10270. this._cache.orthoRight = this.orthoRight;
  10271. this._cache.orthoBottom = this.orthoBottom;
  10272. this._cache.orthoTop = this.orthoTop;
  10273. this._cache.renderWidth = engine.getRenderWidth();
  10274. this._cache.renderHeight = engine.getRenderHeight();
  10275. };
  10276. Camera.prototype._updateFromScene = function () {
  10277. this.updateCache();
  10278. this._update();
  10279. };
  10280. // Synchronized
  10281. Camera.prototype._isSynchronized = function () {
  10282. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10283. };
  10284. Camera.prototype._isSynchronizedViewMatrix = function () {
  10285. if (!_super.prototype._isSynchronized.call(this))
  10286. return false;
  10287. return this._cache.position.equals(this.position)
  10288. && this._cache.upVector.equals(this.upVector)
  10289. && this.isSynchronizedWithParent();
  10290. };
  10291. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10292. var check = this._cache.mode === this.mode
  10293. && this._cache.minZ === this.minZ
  10294. && this._cache.maxZ === this.maxZ;
  10295. if (!check) {
  10296. return false;
  10297. }
  10298. var engine = this.getEngine();
  10299. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10300. check = this._cache.fov === this.fov
  10301. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10302. }
  10303. else {
  10304. check = this._cache.orthoLeft === this.orthoLeft
  10305. && this._cache.orthoRight === this.orthoRight
  10306. && this._cache.orthoBottom === this.orthoBottom
  10307. && this._cache.orthoTop === this.orthoTop
  10308. && this._cache.renderWidth === engine.getRenderWidth()
  10309. && this._cache.renderHeight === engine.getRenderHeight();
  10310. }
  10311. return check;
  10312. };
  10313. // Controls
  10314. Camera.prototype.attachControl = function (element) {
  10315. };
  10316. Camera.prototype.detachControl = function (element) {
  10317. };
  10318. Camera.prototype._update = function () {
  10319. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10320. this._updateRigCameras();
  10321. }
  10322. this._checkInputs();
  10323. };
  10324. Camera.prototype._checkInputs = function () {
  10325. };
  10326. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10327. if (insertAt === void 0) { insertAt = null; }
  10328. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10329. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10330. return 0;
  10331. }
  10332. if (insertAt == null || insertAt < 0) {
  10333. this._postProcesses.push(postProcess);
  10334. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10335. return this._postProcesses.length - 1;
  10336. }
  10337. var add = 0;
  10338. var i;
  10339. var start;
  10340. if (this._postProcesses[insertAt]) {
  10341. start = this._postProcesses.length - 1;
  10342. for (i = start; i >= insertAt + 1; --i) {
  10343. this._postProcesses[i + 1] = this._postProcesses[i];
  10344. }
  10345. add = 1;
  10346. }
  10347. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10348. if (this._postProcessesTakenIndices[i] < insertAt) {
  10349. continue;
  10350. }
  10351. start = this._postProcessesTakenIndices.length - 1;
  10352. for (var j = start; j >= i; --j) {
  10353. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10354. }
  10355. this._postProcessesTakenIndices[i] = insertAt;
  10356. break;
  10357. }
  10358. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10359. this._postProcessesTakenIndices.push(insertAt);
  10360. }
  10361. var result = insertAt + add;
  10362. this._postProcesses[result] = postProcess;
  10363. return result;
  10364. };
  10365. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10366. if (atIndices === void 0) { atIndices = null; }
  10367. var result = [];
  10368. var i;
  10369. var index;
  10370. if (!atIndices) {
  10371. var length = this._postProcesses.length;
  10372. for (i = 0; i < length; i++) {
  10373. if (this._postProcesses[i] !== postProcess) {
  10374. continue;
  10375. }
  10376. delete this._postProcesses[i];
  10377. index = this._postProcessesTakenIndices.indexOf(i);
  10378. this._postProcessesTakenIndices.splice(index, 1);
  10379. }
  10380. }
  10381. else {
  10382. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10383. for (i = 0; i < atIndices.length; i++) {
  10384. var foundPostProcess = this._postProcesses[atIndices[i]];
  10385. if (foundPostProcess !== postProcess) {
  10386. result.push(i);
  10387. continue;
  10388. }
  10389. delete this._postProcesses[atIndices[i]];
  10390. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10391. this._postProcessesTakenIndices.splice(index, 1);
  10392. }
  10393. }
  10394. return result;
  10395. };
  10396. Camera.prototype.getWorldMatrix = function () {
  10397. if (!this._worldMatrix) {
  10398. this._worldMatrix = BABYLON.Matrix.Identity();
  10399. }
  10400. var viewMatrix = this.getViewMatrix();
  10401. viewMatrix.invertToRef(this._worldMatrix);
  10402. return this._worldMatrix;
  10403. };
  10404. Camera.prototype._getViewMatrix = function () {
  10405. return BABYLON.Matrix.Identity();
  10406. };
  10407. Camera.prototype.getViewMatrix = function (force) {
  10408. this._computedViewMatrix = this._computeViewMatrix(force);
  10409. if (!force && this._isSynchronizedViewMatrix()) {
  10410. return this._computedViewMatrix;
  10411. }
  10412. if (!this.parent || !this.parent.getWorldMatrix) {
  10413. this._globalPosition.copyFrom(this.position);
  10414. }
  10415. else {
  10416. if (!this._worldMatrix) {
  10417. this._worldMatrix = BABYLON.Matrix.Identity();
  10418. }
  10419. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10420. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10421. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10422. this._computedViewMatrix.invert();
  10423. this._markSyncedWithParent();
  10424. }
  10425. this._currentRenderId = this.getScene().getRenderId();
  10426. return this._computedViewMatrix;
  10427. };
  10428. Camera.prototype._computeViewMatrix = function (force) {
  10429. if (!force && this._isSynchronizedViewMatrix()) {
  10430. return this._computedViewMatrix;
  10431. }
  10432. this._computedViewMatrix = this._getViewMatrix();
  10433. this._currentRenderId = this.getScene().getRenderId();
  10434. return this._computedViewMatrix;
  10435. };
  10436. Camera.prototype.getProjectionMatrix = function (force) {
  10437. if (!force && this._isSynchronizedProjectionMatrix()) {
  10438. return this._projectionMatrix;
  10439. }
  10440. var engine = this.getEngine();
  10441. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10442. if (this.minZ <= 0) {
  10443. this.minZ = 0.1;
  10444. }
  10445. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10446. return this._projectionMatrix;
  10447. }
  10448. var halfWidth = engine.getRenderWidth() / 2.0;
  10449. var halfHeight = engine.getRenderHeight() / 2.0;
  10450. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10451. return this._projectionMatrix;
  10452. };
  10453. Camera.prototype.dispose = function () {
  10454. // Animations
  10455. this.getScene().stopAnimation(this);
  10456. // Remove from scene
  10457. this.getScene().removeCamera(this);
  10458. while (this._rigCameras.length > 0) {
  10459. this._rigCameras.pop().dispose();
  10460. }
  10461. // Postprocesses
  10462. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10463. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10464. }
  10465. };
  10466. // ---- Camera rigs section ----
  10467. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10468. while (this._rigCameras.length > 0) {
  10469. this._rigCameras.pop().dispose();
  10470. }
  10471. this.cameraRigMode = mode;
  10472. this._cameraRigParams = {};
  10473. switch (this.cameraRigMode) {
  10474. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10475. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10476. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10477. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10478. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10479. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10480. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10481. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10482. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10483. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10484. break;
  10485. }
  10486. var postProcesses = new Array();
  10487. switch (this.cameraRigMode) {
  10488. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10489. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10490. this._rigCameras[0].isIntermediate = true;
  10491. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10492. postProcesses[1].onApply = function (effect) {
  10493. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10494. };
  10495. break;
  10496. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10497. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10498. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10499. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10500. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10501. var secondCamIndex = 1 - firstCamIndex;
  10502. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10503. this._rigCameras[firstCamIndex].isIntermediate = true;
  10504. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10505. break;
  10506. case Camera.RIG_MODE_VR:
  10507. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10508. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10509. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10510. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10511. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10512. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10513. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10514. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10515. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10516. if (metrics.compensateDistortion) {
  10517. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10518. }
  10519. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10520. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10521. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10522. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10523. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10524. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10525. if (metrics.compensateDistortion) {
  10526. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10527. }
  10528. break;
  10529. }
  10530. this._update();
  10531. };
  10532. Camera.prototype._getVRProjectionMatrix = function () {
  10533. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10534. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10535. return this._projectionMatrix;
  10536. };
  10537. Camera.prototype.setCameraRigParameter = function (name, value) {
  10538. this._cameraRigParams[name] = value;
  10539. //provisionnally:
  10540. if (name === "interaxialDistance") {
  10541. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10542. }
  10543. };
  10544. /**
  10545. * May needs to be overridden by children so sub has required properties to be copied
  10546. */
  10547. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10548. return null;
  10549. };
  10550. /**
  10551. * May needs to be overridden by children
  10552. */
  10553. Camera.prototype._updateRigCameras = function () {
  10554. for (var i = 0; i < this._rigCameras.length; i++) {
  10555. this._rigCameras[i].minZ = this.minZ;
  10556. this._rigCameras[i].maxZ = this.maxZ;
  10557. this._rigCameras[i].fov = this.fov;
  10558. }
  10559. // only update viewport when ANAGLYPH
  10560. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10561. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10562. }
  10563. };
  10564. Camera.prototype.serialize = function () {
  10565. var serializationObject = {};
  10566. serializationObject.name = this.name;
  10567. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10568. serializationObject.id = this.id;
  10569. serializationObject.position = this.position.asArray();
  10570. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10571. // Parent
  10572. if (this.parent) {
  10573. serializationObject.parentId = this.parent.id;
  10574. }
  10575. serializationObject.fov = this.fov;
  10576. serializationObject.minZ = this.minZ;
  10577. serializationObject.maxZ = this.maxZ;
  10578. serializationObject.inertia = this.inertia;
  10579. // Animations
  10580. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10581. serializationObject.ranges = this.serializeAnimationRanges();
  10582. // Layer mask
  10583. serializationObject.layerMask = this.layerMask;
  10584. return serializationObject;
  10585. };
  10586. Camera.Parse = function (parsedCamera, scene) {
  10587. var camera;
  10588. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10589. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10590. var interaxial_distance;
  10591. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10592. var alpha = parsedCamera.alpha;
  10593. var beta = parsedCamera.beta;
  10594. var radius = parsedCamera.radius;
  10595. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10596. interaxial_distance = parsedCamera.interaxial_distance;
  10597. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10598. }
  10599. else {
  10600. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10601. }
  10602. }
  10603. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10604. interaxial_distance = parsedCamera.interaxial_distance;
  10605. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10606. }
  10607. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10608. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10609. }
  10610. else if (parsedCamera.type === "FollowCamera") {
  10611. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10612. camera.heightOffset = parsedCamera.heightOffset;
  10613. camera.radius = parsedCamera.radius;
  10614. camera.rotationOffset = parsedCamera.rotationOffset;
  10615. if (lockedTargetMesh)
  10616. camera.target = lockedTargetMesh;
  10617. }
  10618. else if (parsedCamera.type === "GamepadCamera") {
  10619. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10620. }
  10621. else if (parsedCamera.type === "TouchCamera") {
  10622. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10623. }
  10624. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10625. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10626. }
  10627. else if (parsedCamera.type === "WebVRFreeCamera") {
  10628. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10629. }
  10630. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10631. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10632. }
  10633. else if (parsedCamera.type === "FreeCamera") {
  10634. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
  10635. }
  10636. else {
  10637. // Universal Camera is the default value
  10638. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
  10639. }
  10640. // apply 3d rig, when found
  10641. if (parsedCamera.cameraRigMode) {
  10642. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10643. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10644. }
  10645. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10646. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10647. camera.lockedTarget = lockedTargetMesh;
  10648. }
  10649. camera.id = parsedCamera.id;
  10650. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10651. // Parent
  10652. if (parsedCamera.parentId) {
  10653. camera._waitingParentId = parsedCamera.parentId;
  10654. }
  10655. // Target
  10656. if (parsedCamera.target) {
  10657. if (camera.setTarget) {
  10658. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10659. }
  10660. else {
  10661. //For ArcRotate
  10662. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10663. }
  10664. }
  10665. else {
  10666. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10667. }
  10668. camera.fov = parsedCamera.fov;
  10669. camera.minZ = parsedCamera.minZ;
  10670. camera.maxZ = parsedCamera.maxZ;
  10671. camera.speed = parsedCamera.speed;
  10672. camera.inertia = parsedCamera.inertia;
  10673. camera.checkCollisions = parsedCamera.checkCollisions;
  10674. camera.applyGravity = parsedCamera.applyGravity;
  10675. if (parsedCamera.ellipsoid) {
  10676. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10677. }
  10678. // Animations
  10679. if (parsedCamera.animations) {
  10680. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10681. var parsedAnimation = parsedCamera.animations[animationIndex];
  10682. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10683. }
  10684. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10685. }
  10686. if (parsedCamera.autoAnimate) {
  10687. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10688. }
  10689. // Layer Mask
  10690. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10691. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10692. }
  10693. else {
  10694. camera.layerMask = 0x0FFFFFFF;
  10695. }
  10696. return camera;
  10697. };
  10698. // Statics
  10699. Camera._PERSPECTIVE_CAMERA = 0;
  10700. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10701. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10702. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10703. Camera._RIG_MODE_NONE = 0;
  10704. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10705. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10706. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10707. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10708. Camera._RIG_MODE_VR = 20;
  10709. return Camera;
  10710. })(BABYLON.Node);
  10711. BABYLON.Camera = Camera;
  10712. })(BABYLON || (BABYLON = {}));
  10713. var BABYLON;
  10714. (function (BABYLON) {
  10715. var TargetCamera = (function (_super) {
  10716. __extends(TargetCamera, _super);
  10717. function TargetCamera(name, position, scene) {
  10718. _super.call(this, name, position, scene);
  10719. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10720. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10721. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10722. this.speed = 2.0;
  10723. this.noRotationConstraint = false;
  10724. this.lockedTarget = null;
  10725. this._currentTarget = BABYLON.Vector3.Zero();
  10726. this._viewMatrix = BABYLON.Matrix.Zero();
  10727. this._camMatrix = BABYLON.Matrix.Zero();
  10728. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10729. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10730. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10731. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10732. this._lookAtTemp = BABYLON.Matrix.Zero();
  10733. this._tempMatrix = BABYLON.Matrix.Zero();
  10734. }
  10735. TargetCamera.prototype.getFrontPosition = function (distance) {
  10736. var direction = this.getTarget().subtract(this.position);
  10737. direction.normalize();
  10738. direction.scaleInPlace(distance);
  10739. return this.globalPosition.add(direction);
  10740. };
  10741. TargetCamera.prototype._getLockedTargetPosition = function () {
  10742. if (!this.lockedTarget) {
  10743. return null;
  10744. }
  10745. return this.lockedTarget.position || this.lockedTarget;
  10746. };
  10747. // Cache
  10748. TargetCamera.prototype._initCache = function () {
  10749. _super.prototype._initCache.call(this);
  10750. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10751. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10752. };
  10753. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10754. if (!ignoreParentClass) {
  10755. _super.prototype._updateCache.call(this);
  10756. }
  10757. var lockedTargetPosition = this._getLockedTargetPosition();
  10758. if (!lockedTargetPosition) {
  10759. this._cache.lockedTarget = null;
  10760. }
  10761. else {
  10762. if (!this._cache.lockedTarget) {
  10763. this._cache.lockedTarget = lockedTargetPosition.clone();
  10764. }
  10765. else {
  10766. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10767. }
  10768. }
  10769. this._cache.rotation.copyFrom(this.rotation);
  10770. };
  10771. // Synchronized
  10772. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10773. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10774. return false;
  10775. }
  10776. var lockedTargetPosition = this._getLockedTargetPosition();
  10777. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10778. && this._cache.rotation.equals(this.rotation);
  10779. };
  10780. // Methods
  10781. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10782. var engine = this.getEngine();
  10783. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10784. };
  10785. // Target
  10786. TargetCamera.prototype.setTarget = function (target) {
  10787. this.upVector.normalize();
  10788. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10789. this._camMatrix.invert();
  10790. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10791. var vDir = target.subtract(this.position);
  10792. if (vDir.x >= 0.0) {
  10793. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10794. }
  10795. else {
  10796. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10797. }
  10798. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10799. if (isNaN(this.rotation.x)) {
  10800. this.rotation.x = 0;
  10801. }
  10802. if (isNaN(this.rotation.y)) {
  10803. this.rotation.y = 0;
  10804. }
  10805. if (isNaN(this.rotation.z)) {
  10806. this.rotation.z = 0;
  10807. }
  10808. };
  10809. TargetCamera.prototype.getTarget = function () {
  10810. return this._currentTarget;
  10811. };
  10812. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10813. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10814. };
  10815. TargetCamera.prototype._updatePosition = function () {
  10816. this.position.addInPlace(this.cameraDirection);
  10817. };
  10818. TargetCamera.prototype._checkInputs = function () {
  10819. var needToMove = this._decideIfNeedsToMove();
  10820. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10821. // Move
  10822. if (needToMove) {
  10823. this._updatePosition();
  10824. }
  10825. // Rotate
  10826. if (needToRotate) {
  10827. this.rotation.x += this.cameraRotation.x;
  10828. this.rotation.y += this.cameraRotation.y;
  10829. if (!this.noRotationConstraint) {
  10830. var limit = (Math.PI / 2) * 0.95;
  10831. if (this.rotation.x > limit)
  10832. this.rotation.x = limit;
  10833. if (this.rotation.x < -limit)
  10834. this.rotation.x = -limit;
  10835. }
  10836. }
  10837. // Inertia
  10838. if (needToMove) {
  10839. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10840. this.cameraDirection.x = 0;
  10841. }
  10842. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10843. this.cameraDirection.y = 0;
  10844. }
  10845. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10846. this.cameraDirection.z = 0;
  10847. }
  10848. this.cameraDirection.scaleInPlace(this.inertia);
  10849. }
  10850. if (needToRotate) {
  10851. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10852. this.cameraRotation.x = 0;
  10853. }
  10854. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10855. this.cameraRotation.y = 0;
  10856. }
  10857. this.cameraRotation.scaleInPlace(this.inertia);
  10858. }
  10859. _super.prototype._checkInputs.call(this);
  10860. };
  10861. TargetCamera.prototype._getViewMatrix = function () {
  10862. if (!this.lockedTarget) {
  10863. // Compute
  10864. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10865. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10866. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10867. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10868. this._lookAtTemp.invert();
  10869. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10870. }
  10871. else {
  10872. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10873. }
  10874. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10875. // Computing target and final matrix
  10876. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10877. }
  10878. else {
  10879. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10880. }
  10881. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10882. return this._viewMatrix;
  10883. };
  10884. TargetCamera.prototype._getVRViewMatrix = function () {
  10885. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10886. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10887. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10888. // Computing target and final matrix
  10889. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10890. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10891. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10892. return this._viewMatrix;
  10893. };
  10894. /**
  10895. * @override
  10896. * Override Camera.createRigCamera
  10897. */
  10898. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10899. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10900. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10901. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10902. rigCamera._cameraRigParams = {};
  10903. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10904. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10905. }
  10906. return rigCamera;
  10907. }
  10908. return null;
  10909. };
  10910. /**
  10911. * @override
  10912. * Override Camera._updateRigCameras
  10913. */
  10914. TargetCamera.prototype._updateRigCameras = function () {
  10915. switch (this.cameraRigMode) {
  10916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10920. case BABYLON.Camera.RIG_MODE_VR:
  10921. var camLeft = this._rigCameras[0];
  10922. var camRight = this._rigCameras[1];
  10923. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10924. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10925. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10926. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10927. camLeft.position.copyFrom(this.position);
  10928. camRight.position.copyFrom(this.position);
  10929. }
  10930. else {
  10931. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10932. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10933. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10934. camLeft.setTarget(this.getTarget());
  10935. camRight.setTarget(this.getTarget());
  10936. }
  10937. break;
  10938. }
  10939. _super.prototype._updateRigCameras.call(this);
  10940. };
  10941. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10942. if (!this._rigCamTransformMatrix) {
  10943. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10944. }
  10945. var target = this.getTarget();
  10946. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10947. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10948. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10949. };
  10950. TargetCamera.prototype.serialize = function () {
  10951. var serializationObject = _super.prototype.serialize.call(this);
  10952. serializationObject.speed = this.speed;
  10953. if (this.rotation) {
  10954. serializationObject.rotation = this.rotation.asArray();
  10955. }
  10956. if (this.lockedTarget && this.lockedTarget.id) {
  10957. serializationObject.lockedTargetId = this.lockedTarget.id;
  10958. }
  10959. return serializationObject;
  10960. };
  10961. return TargetCamera;
  10962. })(BABYLON.Camera);
  10963. BABYLON.TargetCamera = TargetCamera;
  10964. })(BABYLON || (BABYLON = {}));
  10965. var BABYLON;
  10966. (function (BABYLON) {
  10967. var FreeCamera = (function (_super) {
  10968. __extends(FreeCamera, _super);
  10969. function FreeCamera(name, position, scene) {
  10970. var _this = this;
  10971. _super.call(this, name, position, scene);
  10972. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10973. this.keysUp = [38];
  10974. this.keysDown = [40];
  10975. this.keysLeft = [37];
  10976. this.keysRight = [39];
  10977. this.checkCollisions = false;
  10978. this.applyGravity = false;
  10979. this.angularSensibility = 2000.0;
  10980. this._keys = [];
  10981. this._collider = new BABYLON.Collider();
  10982. this._needMoveForGravity = false;
  10983. this._oldPosition = BABYLON.Vector3.Zero();
  10984. this._diffPosition = BABYLON.Vector3.Zero();
  10985. this._newPosition = BABYLON.Vector3.Zero();
  10986. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10987. if (collidedMesh === void 0) { collidedMesh = null; }
  10988. //TODO move this to the collision coordinator!
  10989. if (_this.getScene().workerCollisions)
  10990. newPosition.multiplyInPlace(_this._collider.radius);
  10991. var updatePosition = function (newPos) {
  10992. _this._newPosition.copyFrom(newPos);
  10993. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10994. var oldPosition = _this.position.clone();
  10995. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10996. _this.position.addInPlace(_this._diffPosition);
  10997. if (_this.onCollide && collidedMesh) {
  10998. _this.onCollide(collidedMesh);
  10999. }
  11000. }
  11001. };
  11002. updatePosition(newPosition);
  11003. };
  11004. }
  11005. FreeCamera.prototype._onLostFocus = function (e) {
  11006. this._keys = [];
  11007. };
  11008. // Controls
  11009. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11010. var _this = this;
  11011. var previousPosition;
  11012. var engine = this.getEngine();
  11013. if (this._attachedElement) {
  11014. return;
  11015. }
  11016. this._attachedElement = element;
  11017. if (this._onMouseDown === undefined) {
  11018. this._onMouseDown = function (evt) {
  11019. previousPosition = {
  11020. x: evt.clientX,
  11021. y: evt.clientY
  11022. };
  11023. if (!noPreventDefault) {
  11024. evt.preventDefault();
  11025. }
  11026. };
  11027. this._onMouseUp = function (evt) {
  11028. previousPosition = null;
  11029. if (!noPreventDefault) {
  11030. evt.preventDefault();
  11031. }
  11032. };
  11033. this._onMouseOut = function (evt) {
  11034. previousPosition = null;
  11035. _this._keys = [];
  11036. if (!noPreventDefault) {
  11037. evt.preventDefault();
  11038. }
  11039. };
  11040. this._onMouseMove = function (evt) {
  11041. if (!previousPosition && !engine.isPointerLock) {
  11042. return;
  11043. }
  11044. var offsetX;
  11045. var offsetY;
  11046. if (!engine.isPointerLock) {
  11047. offsetX = evt.clientX - previousPosition.x;
  11048. offsetY = evt.clientY - previousPosition.y;
  11049. }
  11050. else {
  11051. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11052. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11053. }
  11054. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11055. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11056. previousPosition = {
  11057. x: evt.clientX,
  11058. y: evt.clientY
  11059. };
  11060. if (!noPreventDefault) {
  11061. evt.preventDefault();
  11062. }
  11063. };
  11064. this._onKeyDown = function (evt) {
  11065. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11066. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11067. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11068. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11069. var index = _this._keys.indexOf(evt.keyCode);
  11070. if (index === -1) {
  11071. _this._keys.push(evt.keyCode);
  11072. }
  11073. if (!noPreventDefault) {
  11074. evt.preventDefault();
  11075. }
  11076. }
  11077. };
  11078. this._onKeyUp = function (evt) {
  11079. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11080. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11081. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11082. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11083. var index = _this._keys.indexOf(evt.keyCode);
  11084. if (index >= 0) {
  11085. _this._keys.splice(index, 1);
  11086. }
  11087. if (!noPreventDefault) {
  11088. evt.preventDefault();
  11089. }
  11090. }
  11091. };
  11092. this._reset = function () {
  11093. _this._keys = [];
  11094. previousPosition = null;
  11095. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11096. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11097. };
  11098. }
  11099. element.addEventListener("mousedown", this._onMouseDown, false);
  11100. element.addEventListener("mouseup", this._onMouseUp, false);
  11101. element.addEventListener("mouseout", this._onMouseOut, false);
  11102. element.addEventListener("mousemove", this._onMouseMove, false);
  11103. BABYLON.Tools.RegisterTopRootEvents([
  11104. { name: "keydown", handler: this._onKeyDown },
  11105. { name: "keyup", handler: this._onKeyUp },
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. };
  11109. FreeCamera.prototype.detachControl = function (element) {
  11110. if (this._attachedElement !== element) {
  11111. return;
  11112. }
  11113. element.removeEventListener("mousedown", this._onMouseDown);
  11114. element.removeEventListener("mouseup", this._onMouseUp);
  11115. element.removeEventListener("mouseout", this._onMouseOut);
  11116. element.removeEventListener("mousemove", this._onMouseMove);
  11117. BABYLON.Tools.UnregisterTopRootEvents([
  11118. { name: "keydown", handler: this._onKeyDown },
  11119. { name: "keyup", handler: this._onKeyUp },
  11120. { name: "blur", handler: this._onLostFocus }
  11121. ]);
  11122. this._attachedElement = null;
  11123. if (this._reset) {
  11124. this._reset();
  11125. }
  11126. };
  11127. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11128. var globalPosition;
  11129. if (this.parent) {
  11130. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11131. }
  11132. else {
  11133. globalPosition = this.position;
  11134. }
  11135. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11136. this._collider.radius = this.ellipsoid;
  11137. //no need for clone, as long as gravity is not on.
  11138. var actualVelocity = velocity;
  11139. //add gravity to the velocity to prevent the dual-collision checking
  11140. if (this.applyGravity) {
  11141. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11142. actualVelocity = velocity.add(this.getScene().gravity);
  11143. }
  11144. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11145. };
  11146. FreeCamera.prototype._checkInputs = function () {
  11147. if (!this._localDirection) {
  11148. this._localDirection = BABYLON.Vector3.Zero();
  11149. this._transformedDirection = BABYLON.Vector3.Zero();
  11150. }
  11151. // Keyboard
  11152. for (var index = 0; index < this._keys.length; index++) {
  11153. var keyCode = this._keys[index];
  11154. var speed = this._computeLocalCameraSpeed();
  11155. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11156. this._localDirection.copyFromFloats(-speed, 0, 0);
  11157. }
  11158. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11159. this._localDirection.copyFromFloats(0, 0, speed);
  11160. }
  11161. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11162. this._localDirection.copyFromFloats(speed, 0, 0);
  11163. }
  11164. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11165. this._localDirection.copyFromFloats(0, 0, -speed);
  11166. }
  11167. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11168. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11169. this.cameraDirection.addInPlace(this._transformedDirection);
  11170. }
  11171. _super.prototype._checkInputs.call(this);
  11172. };
  11173. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11174. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11175. };
  11176. FreeCamera.prototype._updatePosition = function () {
  11177. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11178. this._collideWithWorld(this.cameraDirection);
  11179. }
  11180. else {
  11181. this.position.addInPlace(this.cameraDirection);
  11182. }
  11183. };
  11184. FreeCamera.prototype.serialize = function () {
  11185. var serializationObject = _super.prototype.serialize.call(this);
  11186. serializationObject.checkCollisions = this.checkCollisions;
  11187. serializationObject.applyGravity = this.applyGravity;
  11188. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11189. return serializationObject;
  11190. };
  11191. return FreeCamera;
  11192. })(BABYLON.TargetCamera);
  11193. BABYLON.FreeCamera = FreeCamera;
  11194. })(BABYLON || (BABYLON = {}));
  11195. var BABYLON;
  11196. (function (BABYLON) {
  11197. var FollowCamera = (function (_super) {
  11198. __extends(FollowCamera, _super);
  11199. function FollowCamera(name, position, scene) {
  11200. _super.call(this, name, position, scene);
  11201. this.radius = 12;
  11202. this.rotationOffset = 0;
  11203. this.heightOffset = 4;
  11204. this.cameraAcceleration = 0.05;
  11205. this.maxCameraSpeed = 20;
  11206. }
  11207. FollowCamera.prototype.getRadians = function (degrees) {
  11208. return degrees * Math.PI / 180;
  11209. };
  11210. FollowCamera.prototype.follow = function (cameraTarget) {
  11211. if (!cameraTarget)
  11212. return;
  11213. var yRotation;
  11214. if (cameraTarget.rotationQuaternion) {
  11215. var rotMatrix = new BABYLON.Matrix();
  11216. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11217. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11218. }
  11219. else {
  11220. yRotation = cameraTarget.rotation.y;
  11221. }
  11222. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11223. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11224. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11225. var dx = targetX - this.position.x;
  11226. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11227. var dz = (targetZ) - this.position.z;
  11228. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11229. var vy = dy * this.cameraAcceleration;
  11230. var vz = dz * this.cameraAcceleration * 2;
  11231. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11232. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11233. }
  11234. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11235. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11236. }
  11237. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11238. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11239. }
  11240. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11241. this.setTarget(cameraTarget.position);
  11242. };
  11243. FollowCamera.prototype._checkInputs = function () {
  11244. _super.prototype._checkInputs.call(this);
  11245. this.follow(this.target);
  11246. };
  11247. FollowCamera.prototype.serialize = function () {
  11248. var serializationObject = _super.prototype.serialize.call(this);
  11249. serializationObject.radius = this.radius;
  11250. serializationObject.heightOffset = this.heightOffset;
  11251. serializationObject.rotationOffset = this.rotationOffset;
  11252. return serializationObject;
  11253. };
  11254. return FollowCamera;
  11255. })(BABYLON.TargetCamera);
  11256. BABYLON.FollowCamera = FollowCamera;
  11257. var ArcFollowCamera = (function (_super) {
  11258. __extends(ArcFollowCamera, _super);
  11259. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11260. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11261. this.alpha = alpha;
  11262. this.beta = beta;
  11263. this.radius = radius;
  11264. this.target = target;
  11265. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11266. this.follow();
  11267. }
  11268. ArcFollowCamera.prototype.follow = function () {
  11269. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11270. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11271. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11272. this.position = this.target.position.add(this._cartesianCoordinates);
  11273. this.setTarget(this.target.position);
  11274. };
  11275. ArcFollowCamera.prototype._checkInputs = function () {
  11276. _super.prototype._checkInputs.call(this);
  11277. this.follow();
  11278. };
  11279. ArcFollowCamera.prototype.serialize = function () {
  11280. var serializationObject = _super.prototype.serialize.call(this);
  11281. serializationObject.radius = this.radius;
  11282. return serializationObject;
  11283. };
  11284. return ArcFollowCamera;
  11285. })(BABYLON.TargetCamera);
  11286. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11287. })(BABYLON || (BABYLON = {}));
  11288. var BABYLON;
  11289. (function (BABYLON) {
  11290. // We're mainly based on the logic defined into the FreeCamera code
  11291. var TouchCamera = (function (_super) {
  11292. __extends(TouchCamera, _super);
  11293. function TouchCamera(name, position, scene) {
  11294. _super.call(this, name, position, scene);
  11295. this._offsetX = null;
  11296. this._offsetY = null;
  11297. this._pointerCount = 0;
  11298. this._pointerPressed = [];
  11299. this.touchAngularSensibility = 200000.0;
  11300. this.touchMoveSensibility = 250.0;
  11301. }
  11302. TouchCamera.prototype._onLostFocus = function (e) {
  11303. this._offsetX = null;
  11304. this._offsetY = null;
  11305. _super.prototype._onLostFocus.call(this, e);
  11306. };
  11307. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11308. var _this = this;
  11309. var previousPosition;
  11310. if (this._attachedCanvas) {
  11311. return;
  11312. }
  11313. if (this._onPointerDown === undefined) {
  11314. this._onPointerDown = function (evt) {
  11315. if (evt.pointerType === "mouse") {
  11316. return;
  11317. }
  11318. if (!noPreventDefault) {
  11319. evt.preventDefault();
  11320. }
  11321. _this._pointerPressed.push(evt.pointerId);
  11322. if (_this._pointerPressed.length !== 1) {
  11323. return;
  11324. }
  11325. previousPosition = {
  11326. x: evt.clientX,
  11327. y: evt.clientY
  11328. };
  11329. };
  11330. this._onPointerUp = function (evt) {
  11331. if (evt.pointerType === "mouse") {
  11332. return;
  11333. }
  11334. if (!noPreventDefault) {
  11335. evt.preventDefault();
  11336. }
  11337. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11338. if (index === -1) {
  11339. return;
  11340. }
  11341. _this._pointerPressed.splice(index, 1);
  11342. if (index != 0) {
  11343. return;
  11344. }
  11345. previousPosition = null;
  11346. _this._offsetX = null;
  11347. _this._offsetY = null;
  11348. };
  11349. this._onPointerMove = function (evt) {
  11350. if (evt.pointerType === "mouse") {
  11351. return;
  11352. }
  11353. if (!noPreventDefault) {
  11354. evt.preventDefault();
  11355. }
  11356. if (!previousPosition) {
  11357. return;
  11358. }
  11359. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11360. if (index != 0) {
  11361. return;
  11362. }
  11363. _this._offsetX = evt.clientX - previousPosition.x;
  11364. _this._offsetY = -(evt.clientY - previousPosition.y);
  11365. };
  11366. }
  11367. canvas.addEventListener("pointerdown", this._onPointerDown);
  11368. canvas.addEventListener("pointerup", this._onPointerUp);
  11369. canvas.addEventListener("pointerout", this._onPointerUp);
  11370. canvas.addEventListener("pointermove", this._onPointerMove);
  11371. _super.prototype.attachControl.call(this, canvas);
  11372. };
  11373. TouchCamera.prototype.detachControl = function (canvas) {
  11374. if (this._attachedCanvas !== canvas) {
  11375. return;
  11376. }
  11377. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11378. canvas.removeEventListener("pointerup", this._onPointerUp);
  11379. canvas.removeEventListener("pointerout", this._onPointerUp);
  11380. canvas.removeEventListener("pointermove", this._onPointerMove);
  11381. _super.prototype.detachControl.call(this, canvas);
  11382. };
  11383. TouchCamera.prototype._checkInputs = function () {
  11384. if (this._offsetX) {
  11385. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11386. if (this._pointerPressed.length > 1) {
  11387. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11388. }
  11389. else {
  11390. var speed = this._computeLocalCameraSpeed();
  11391. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11392. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11393. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11394. }
  11395. }
  11396. _super.prototype._checkInputs.call(this);
  11397. };
  11398. return TouchCamera;
  11399. })(BABYLON.FreeCamera);
  11400. BABYLON.TouchCamera = TouchCamera;
  11401. })(BABYLON || (BABYLON = {}));
  11402. var BABYLON;
  11403. (function (BABYLON) {
  11404. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11405. var ArcRotateCamera = (function (_super) {
  11406. __extends(ArcRotateCamera, _super);
  11407. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11408. var _this = this;
  11409. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11410. this.alpha = alpha;
  11411. this.beta = beta;
  11412. this.radius = radius;
  11413. this.target = target;
  11414. this.inertialAlphaOffset = 0;
  11415. this.inertialBetaOffset = 0;
  11416. this.inertialRadiusOffset = 0;
  11417. this.lowerAlphaLimit = null;
  11418. this.upperAlphaLimit = null;
  11419. this.lowerBetaLimit = 0.01;
  11420. this.upperBetaLimit = Math.PI;
  11421. this.lowerRadiusLimit = null;
  11422. this.upperRadiusLimit = null;
  11423. this.angularSensibilityX = 1000.0;
  11424. this.angularSensibilityY = 1000.0;
  11425. this.wheelPrecision = 3.0;
  11426. this.pinchPrecision = 2.0;
  11427. this.panningSensibility = 50.0;
  11428. this.inertialPanningX = 0;
  11429. this.inertialPanningY = 0;
  11430. this.keysUp = [38];
  11431. this.keysDown = [40];
  11432. this.keysLeft = [37];
  11433. this.keysRight = [39];
  11434. this.zoomOnFactor = 1;
  11435. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11436. this.pinchInwards = true;
  11437. this.allowUpsideDown = true;
  11438. this._keys = [];
  11439. this._viewMatrix = new BABYLON.Matrix();
  11440. // Panning
  11441. this.panningAxis = new BABYLON.Vector3(1, 0, 1);
  11442. this._isRightClick = false;
  11443. this._isCtrlPushed = false;
  11444. this.checkCollisions = false;
  11445. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11446. this._collider = new BABYLON.Collider();
  11447. this._previousPosition = BABYLON.Vector3.Zero();
  11448. this._collisionVelocity = BABYLON.Vector3.Zero();
  11449. this._newPosition = BABYLON.Vector3.Zero();
  11450. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11451. if (collidedMesh === void 0) { collidedMesh = null; }
  11452. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11453. newPosition.multiplyInPlace(_this._collider.radius);
  11454. }
  11455. if (!collidedMesh) {
  11456. _this._previousPosition.copyFrom(_this.position);
  11457. }
  11458. else {
  11459. _this.setPosition(newPosition);
  11460. if (_this.onCollide) {
  11461. _this.onCollide(collidedMesh);
  11462. }
  11463. }
  11464. // Recompute because of constraints
  11465. var cosa = Math.cos(_this.alpha);
  11466. var sina = Math.sin(_this.alpha);
  11467. var cosb = Math.cos(_this.beta);
  11468. var sinb = Math.sin(_this.beta);
  11469. var target = _this._getTargetPosition();
  11470. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11471. _this.position.copyFrom(_this._newPosition);
  11472. var up = _this.upVector;
  11473. if (_this.allowUpsideDown && _this.beta < 0) {
  11474. up = up.clone();
  11475. up = up.negate();
  11476. }
  11477. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11478. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11479. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11480. _this._collisionTriggered = false;
  11481. };
  11482. if (!this.target) {
  11483. this.target = BABYLON.Vector3.Zero();
  11484. }
  11485. this.getViewMatrix();
  11486. }
  11487. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11488. //deprecated angularSensibility support
  11489. get: function () {
  11490. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11491. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11492. },
  11493. //deprecated angularSensibility support
  11494. set: function (value) {
  11495. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11496. this.angularSensibilityX = value;
  11497. this.angularSensibilityY = value;
  11498. },
  11499. enumerable: true,
  11500. configurable: true
  11501. });
  11502. ArcRotateCamera.prototype._getTargetPosition = function () {
  11503. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11504. };
  11505. // Cache
  11506. ArcRotateCamera.prototype._initCache = function () {
  11507. _super.prototype._initCache.call(this);
  11508. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11509. this._cache.alpha = undefined;
  11510. this._cache.beta = undefined;
  11511. this._cache.radius = undefined;
  11512. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11513. };
  11514. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11515. if (!ignoreParentClass) {
  11516. _super.prototype._updateCache.call(this);
  11517. }
  11518. this._cache.target.copyFrom(this._getTargetPosition());
  11519. this._cache.alpha = this.alpha;
  11520. this._cache.beta = this.beta;
  11521. this._cache.radius = this.radius;
  11522. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11523. };
  11524. // Synchronized
  11525. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11526. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11527. return false;
  11528. return this._cache.target.equals(this._getTargetPosition())
  11529. && this._cache.alpha === this.alpha
  11530. && this._cache.beta === this.beta
  11531. && this._cache.radius === this.radius
  11532. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11533. };
  11534. // Methods
  11535. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11536. var _this = this;
  11537. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11538. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11539. var previousPinchDistance = 0;
  11540. var pointers = new BABYLON.SmartCollection();
  11541. if (this._attachedElement) {
  11542. return;
  11543. }
  11544. this._attachedElement = element;
  11545. var engine = this.getEngine();
  11546. if (this._onPointerDown === undefined) {
  11547. this._onPointerDown = function (evt) {
  11548. // Manage panning with right click
  11549. _this._isRightClick = evt.button === 2;
  11550. // manage pointers
  11551. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11552. cacheSoloPointer = pointers.item(evt.pointerId);
  11553. if (!noPreventDefault) {
  11554. evt.preventDefault();
  11555. }
  11556. };
  11557. this._onPointerUp = function (evt) {
  11558. cacheSoloPointer = null;
  11559. previousPinchDistance = 0;
  11560. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11561. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11562. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11563. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11564. pointers.empty();
  11565. if (!noPreventDefault) {
  11566. evt.preventDefault();
  11567. }
  11568. };
  11569. this._onContextMenu = function (evt) {
  11570. evt.preventDefault();
  11571. };
  11572. this._onPointerMove = function (evt) {
  11573. if (!noPreventDefault) {
  11574. evt.preventDefault();
  11575. }
  11576. switch (pointers.count) {
  11577. case 1:
  11578. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11579. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11580. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11581. }
  11582. else {
  11583. var offsetX = evt.clientX - cacheSoloPointer.x;
  11584. var offsetY = evt.clientY - cacheSoloPointer.y;
  11585. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11586. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11587. }
  11588. cacheSoloPointer.x = evt.clientX;
  11589. cacheSoloPointer.y = evt.clientY;
  11590. break;
  11591. case 2:
  11592. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11593. pointers.item(evt.pointerId).x = evt.clientX;
  11594. pointers.item(evt.pointerId).y = evt.clientY;
  11595. var direction = _this.pinchInwards ? 1 : -1;
  11596. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11597. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11598. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11599. if (previousPinchDistance === 0) {
  11600. previousPinchDistance = pinchSquaredDistance;
  11601. return;
  11602. }
  11603. if (pinchSquaredDistance !== previousPinchDistance) {
  11604. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11605. previousPinchDistance = pinchSquaredDistance;
  11606. }
  11607. break;
  11608. default:
  11609. if (pointers.item(evt.pointerId)) {
  11610. pointers.item(evt.pointerId).x = evt.clientX;
  11611. pointers.item(evt.pointerId).y = evt.clientY;
  11612. }
  11613. }
  11614. };
  11615. this._onMouseMove = function (evt) {
  11616. if (!engine.isPointerLock) {
  11617. return;
  11618. }
  11619. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11620. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11621. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11622. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11623. if (!noPreventDefault) {
  11624. evt.preventDefault();
  11625. }
  11626. };
  11627. this._wheel = function (event) {
  11628. var delta = 0;
  11629. if (event.wheelDelta) {
  11630. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11631. }
  11632. else if (event.detail) {
  11633. delta = -event.detail / _this.wheelPrecision;
  11634. }
  11635. if (delta)
  11636. _this.inertialRadiusOffset += delta;
  11637. if (event.preventDefault) {
  11638. if (!noPreventDefault) {
  11639. event.preventDefault();
  11640. }
  11641. }
  11642. };
  11643. this._onKeyDown = function (evt) {
  11644. _this._isCtrlPushed = evt.ctrlKey;
  11645. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11646. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11647. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11648. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11649. var index = _this._keys.indexOf(evt.keyCode);
  11650. if (index === -1) {
  11651. _this._keys.push(evt.keyCode);
  11652. }
  11653. if (evt.preventDefault) {
  11654. if (!noPreventDefault) {
  11655. evt.preventDefault();
  11656. }
  11657. }
  11658. }
  11659. };
  11660. this._onKeyUp = function (evt) {
  11661. _this._isCtrlPushed = evt.ctrlKey;
  11662. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11663. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11664. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11665. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11666. var index = _this._keys.indexOf(evt.keyCode);
  11667. if (index >= 0) {
  11668. _this._keys.splice(index, 1);
  11669. }
  11670. if (evt.preventDefault) {
  11671. if (!noPreventDefault) {
  11672. evt.preventDefault();
  11673. }
  11674. }
  11675. }
  11676. };
  11677. this._onLostFocus = function () {
  11678. _this._keys = [];
  11679. pointers.empty();
  11680. previousPinchDistance = 0;
  11681. cacheSoloPointer = null;
  11682. };
  11683. this._onGestureStart = function (e) {
  11684. if (window.MSGesture === undefined) {
  11685. return;
  11686. }
  11687. if (!_this._MSGestureHandler) {
  11688. _this._MSGestureHandler = new MSGesture();
  11689. _this._MSGestureHandler.target = element;
  11690. }
  11691. _this._MSGestureHandler.addPointer(e.pointerId);
  11692. };
  11693. this._onGesture = function (e) {
  11694. _this.radius *= e.scale;
  11695. if (e.preventDefault) {
  11696. if (!noPreventDefault) {
  11697. e.stopPropagation();
  11698. e.preventDefault();
  11699. }
  11700. }
  11701. };
  11702. this._reset = function () {
  11703. _this._keys = [];
  11704. _this.inertialAlphaOffset = 0;
  11705. _this.inertialBetaOffset = 0;
  11706. _this.inertialRadiusOffset = 0;
  11707. pointers.empty();
  11708. previousPinchDistance = 0;
  11709. cacheSoloPointer = null;
  11710. };
  11711. }
  11712. if (!useCtrlForPanning) {
  11713. element.addEventListener("contextmenu", this._onContextMenu, false);
  11714. }
  11715. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11716. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11717. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11718. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11719. element.addEventListener("mousemove", this._onMouseMove, false);
  11720. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11721. element.addEventListener("MSGestureChange", this._onGesture, false);
  11722. element.addEventListener('mousewheel', this._wheel, false);
  11723. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11724. BABYLON.Tools.RegisterTopRootEvents([
  11725. { name: "keydown", handler: this._onKeyDown },
  11726. { name: "keyup", handler: this._onKeyUp },
  11727. { name: "blur", handler: this._onLostFocus }
  11728. ]);
  11729. };
  11730. ArcRotateCamera.prototype.detachControl = function (element) {
  11731. if (this._attachedElement !== element) {
  11732. return;
  11733. }
  11734. element.removeEventListener("contextmenu", this._onContextMenu);
  11735. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11736. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11737. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11738. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11739. element.removeEventListener("mousemove", this._onMouseMove);
  11740. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11741. element.removeEventListener("MSGestureChange", this._onGesture);
  11742. element.removeEventListener('mousewheel', this._wheel);
  11743. element.removeEventListener('DOMMouseScroll', this._wheel);
  11744. BABYLON.Tools.UnregisterTopRootEvents([
  11745. { name: "keydown", handler: this._onKeyDown },
  11746. { name: "keyup", handler: this._onKeyUp },
  11747. { name: "blur", handler: this._onLostFocus }
  11748. ]);
  11749. this._MSGestureHandler = null;
  11750. this._attachedElement = null;
  11751. if (this._reset) {
  11752. this._reset();
  11753. }
  11754. };
  11755. ArcRotateCamera.prototype._checkInputs = function () {
  11756. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11757. if (this._collisionTriggered) {
  11758. return;
  11759. }
  11760. // Keyboard
  11761. for (var index = 0; index < this._keys.length; index++) {
  11762. var keyCode = this._keys[index];
  11763. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11764. this.inertialAlphaOffset -= 0.01;
  11765. }
  11766. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11767. this.inertialBetaOffset -= 0.01;
  11768. }
  11769. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11770. this.inertialAlphaOffset += 0.01;
  11771. }
  11772. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11773. this.inertialBetaOffset += 0.01;
  11774. }
  11775. }
  11776. // Inertia
  11777. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11778. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11779. this.beta += this.inertialBetaOffset;
  11780. this.radius -= this.inertialRadiusOffset;
  11781. this.inertialAlphaOffset *= this.inertia;
  11782. this.inertialBetaOffset *= this.inertia;
  11783. this.inertialRadiusOffset *= this.inertia;
  11784. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11785. this.inertialAlphaOffset = 0;
  11786. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11787. this.inertialBetaOffset = 0;
  11788. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11789. this.inertialRadiusOffset = 0;
  11790. }
  11791. // Panning inertia
  11792. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11793. if (!this._localDirection) {
  11794. this._localDirection = BABYLON.Vector3.Zero();
  11795. this._transformedDirection = BABYLON.Vector3.Zero();
  11796. }
  11797. this.inertialPanningX *= this.inertia;
  11798. this.inertialPanningY *= this.inertia;
  11799. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11800. this.inertialPanningX = 0;
  11801. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11802. this.inertialPanningY = 0;
  11803. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11804. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11805. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11806. this._transformedDirection.multiplyInPlace(this.panningAxis);
  11807. this.target.addInPlace(this._transformedDirection);
  11808. }
  11809. // Limits
  11810. this._checkLimits();
  11811. _super.prototype._checkInputs.call(this);
  11812. };
  11813. ArcRotateCamera.prototype._checkLimits = function () {
  11814. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11815. if (this.allowUpsideDown && this.beta > Math.PI) {
  11816. this.beta = this.beta - (2 * Math.PI);
  11817. }
  11818. }
  11819. else {
  11820. if (this.beta < this.lowerBetaLimit) {
  11821. this.beta = this.lowerBetaLimit;
  11822. }
  11823. }
  11824. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11825. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11826. this.beta = this.beta + (2 * Math.PI);
  11827. }
  11828. }
  11829. else {
  11830. if (this.beta > this.upperBetaLimit) {
  11831. this.beta = this.upperBetaLimit;
  11832. }
  11833. }
  11834. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11835. this.alpha = this.lowerAlphaLimit;
  11836. }
  11837. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11838. this.alpha = this.upperAlphaLimit;
  11839. }
  11840. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11841. this.radius = this.lowerRadiusLimit;
  11842. }
  11843. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11844. this.radius = this.upperRadiusLimit;
  11845. }
  11846. };
  11847. ArcRotateCamera.prototype.setPosition = function (position) {
  11848. if (this.position.equals(position)) {
  11849. return;
  11850. }
  11851. var radiusv3 = position.subtract(this._getTargetPosition());
  11852. this.radius = radiusv3.length();
  11853. // Alpha
  11854. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11855. if (radiusv3.z < 0) {
  11856. this.alpha = 2 * Math.PI - this.alpha;
  11857. }
  11858. // Beta
  11859. this.beta = Math.acos(radiusv3.y / this.radius);
  11860. this._checkLimits();
  11861. };
  11862. ArcRotateCamera.prototype.setTarget = function (target) {
  11863. this.target = target;
  11864. };
  11865. ArcRotateCamera.prototype._getViewMatrix = function () {
  11866. // Compute
  11867. var cosa = Math.cos(this.alpha);
  11868. var sina = Math.sin(this.alpha);
  11869. var cosb = Math.cos(this.beta);
  11870. var sinb = Math.sin(this.beta);
  11871. var target = this._getTargetPosition();
  11872. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11873. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11874. this._collider.radius = this.collisionRadius;
  11875. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11876. this._collisionTriggered = true;
  11877. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11878. }
  11879. else {
  11880. this.position.copyFrom(this._newPosition);
  11881. var up = this.upVector;
  11882. if (this.allowUpsideDown && this.beta < 0) {
  11883. up = up.clone();
  11884. up = up.negate();
  11885. }
  11886. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11887. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11888. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11889. }
  11890. return this._viewMatrix;
  11891. };
  11892. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11893. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11894. meshes = meshes || this.getScene().meshes;
  11895. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11896. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11897. this.radius = distance * this.zoomOnFactor;
  11898. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11899. };
  11900. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11901. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11902. var meshesOrMinMaxVector;
  11903. var distance;
  11904. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11905. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11906. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11907. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11908. }
  11909. else {
  11910. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11911. distance = meshesOrMinMaxVectorAndDistance.distance;
  11912. }
  11913. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11914. if (!doNotUpdateMaxZ) {
  11915. this.maxZ = distance * 2;
  11916. }
  11917. };
  11918. /**
  11919. * @override
  11920. * Override Camera.createRigCamera
  11921. */
  11922. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11923. switch (this.cameraRigMode) {
  11924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11926. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11928. case BABYLON.Camera.RIG_MODE_VR:
  11929. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11930. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11931. }
  11932. return null;
  11933. };
  11934. /**
  11935. * @override
  11936. * Override Camera._updateRigCameras
  11937. */
  11938. ArcRotateCamera.prototype._updateRigCameras = function () {
  11939. switch (this.cameraRigMode) {
  11940. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11941. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11942. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11943. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11944. case BABYLON.Camera.RIG_MODE_VR:
  11945. var camLeft = this._rigCameras[0];
  11946. var camRight = this._rigCameras[1];
  11947. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11948. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11949. camLeft.beta = camRight.beta = this.beta;
  11950. camLeft.radius = camRight.radius = this.radius;
  11951. break;
  11952. }
  11953. _super.prototype._updateRigCameras.call(this);
  11954. };
  11955. ArcRotateCamera.prototype.serialize = function () {
  11956. var serializationObject = _super.prototype.serialize.call(this);
  11957. if (this.target instanceof BABYLON.Vector3) {
  11958. serializationObject.target = this.target.asArray();
  11959. }
  11960. if (this.target && this.target.id) {
  11961. serializationObject.lockedTargetId = this.target.id;
  11962. }
  11963. serializationObject.checkCollisions = this.checkCollisions;
  11964. serializationObject.alpha = this.alpha;
  11965. serializationObject.beta = this.beta;
  11966. serializationObject.radius = this.radius;
  11967. return serializationObject;
  11968. };
  11969. return ArcRotateCamera;
  11970. })(BABYLON.TargetCamera);
  11971. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11972. })(BABYLON || (BABYLON = {}));
  11973. var BABYLON;
  11974. (function (BABYLON) {
  11975. var RenderingManager = (function () {
  11976. function RenderingManager(scene) {
  11977. this._renderingGroups = new Array();
  11978. this._scene = scene;
  11979. }
  11980. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11981. if (this._scene._activeParticleSystems.length === 0) {
  11982. return;
  11983. }
  11984. // Particles
  11985. var activeCamera = this._scene.activeCamera;
  11986. var beforeParticlesDate = BABYLON.Tools.Now;
  11987. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11988. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11989. if (particleSystem.renderingGroupId !== index) {
  11990. continue;
  11991. }
  11992. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11993. continue;
  11994. }
  11995. this._clearDepthBuffer();
  11996. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11997. this._scene._activeParticles += particleSystem.render();
  11998. }
  11999. }
  12000. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12001. };
  12002. RenderingManager.prototype._renderSprites = function (index) {
  12003. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12004. return;
  12005. }
  12006. // Sprites
  12007. var activeCamera = this._scene.activeCamera;
  12008. var beforeSpritessDate = BABYLON.Tools.Now;
  12009. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12010. var spriteManager = this._scene.spriteManagers[id];
  12011. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12012. this._clearDepthBuffer();
  12013. spriteManager.render();
  12014. }
  12015. }
  12016. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12017. };
  12018. RenderingManager.prototype._clearDepthBuffer = function () {
  12019. if (this._depthBufferAlreadyCleaned) {
  12020. return;
  12021. }
  12022. this._scene.getEngine().clear(0, false, true);
  12023. this._depthBufferAlreadyCleaned = true;
  12024. };
  12025. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12026. if (this._currentRenderSprites) {
  12027. this._renderSprites(this._currentIndex);
  12028. }
  12029. if (this._currentRenderParticles) {
  12030. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12031. }
  12032. };
  12033. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12034. this._currentActiveMeshes = activeMeshes;
  12035. this._currentRenderParticles = renderParticles;
  12036. this._currentRenderSprites = renderSprites;
  12037. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12038. this._depthBufferAlreadyCleaned = index == 0;
  12039. var renderingGroup = this._renderingGroups[index];
  12040. var needToStepBack = false;
  12041. this._currentIndex = index;
  12042. if (renderingGroup) {
  12043. this._clearDepthBuffer();
  12044. if (!renderingGroup.onBeforeTransparentRendering) {
  12045. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12046. }
  12047. if (!renderingGroup.render(customRenderFunction)) {
  12048. this._renderingGroups.splice(index, 1);
  12049. needToStepBack = true;
  12050. this._renderSpritesAndParticles();
  12051. }
  12052. }
  12053. else {
  12054. this._renderSpritesAndParticles();
  12055. }
  12056. if (needToStepBack) {
  12057. index--;
  12058. }
  12059. }
  12060. };
  12061. RenderingManager.prototype.reset = function () {
  12062. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12063. if (renderingGroup) {
  12064. renderingGroup.prepare();
  12065. }
  12066. });
  12067. };
  12068. RenderingManager.prototype.dispatch = function (subMesh) {
  12069. var mesh = subMesh.getMesh();
  12070. var renderingGroupId = mesh.renderingGroupId || 0;
  12071. if (!this._renderingGroups[renderingGroupId]) {
  12072. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12073. }
  12074. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12075. };
  12076. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12077. return RenderingManager;
  12078. })();
  12079. BABYLON.RenderingManager = RenderingManager;
  12080. })(BABYLON || (BABYLON = {}));
  12081. var BABYLON;
  12082. (function (BABYLON) {
  12083. var RenderingGroup = (function () {
  12084. function RenderingGroup(index, scene) {
  12085. this.index = index;
  12086. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12087. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12088. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12089. this._scene = scene;
  12090. }
  12091. RenderingGroup.prototype.render = function (customRenderFunction) {
  12092. if (customRenderFunction) {
  12093. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12094. return true;
  12095. }
  12096. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12097. if (this.onBeforeTransparentRendering) {
  12098. this.onBeforeTransparentRendering();
  12099. }
  12100. return false;
  12101. }
  12102. var engine = this._scene.getEngine();
  12103. // Opaque
  12104. var subIndex;
  12105. var submesh;
  12106. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12107. submesh = this._opaqueSubMeshes.data[subIndex];
  12108. submesh.render(false);
  12109. }
  12110. // Alpha test
  12111. engine.setAlphaTesting(true);
  12112. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12113. submesh = this._alphaTestSubMeshes.data[subIndex];
  12114. submesh.render(false);
  12115. }
  12116. engine.setAlphaTesting(false);
  12117. if (this.onBeforeTransparentRendering) {
  12118. this.onBeforeTransparentRendering();
  12119. }
  12120. // Transparent
  12121. if (this._transparentSubMeshes.length) {
  12122. // Sorting
  12123. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12124. submesh = this._transparentSubMeshes.data[subIndex];
  12125. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12126. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12127. }
  12128. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12129. sortedArray.sort(function (a, b) {
  12130. // Alpha index first
  12131. if (a._alphaIndex > b._alphaIndex) {
  12132. return 1;
  12133. }
  12134. if (a._alphaIndex < b._alphaIndex) {
  12135. return -1;
  12136. }
  12137. // Then distance to camera
  12138. if (a._distanceToCamera < b._distanceToCamera) {
  12139. return 1;
  12140. }
  12141. if (a._distanceToCamera > b._distanceToCamera) {
  12142. return -1;
  12143. }
  12144. return 0;
  12145. });
  12146. // Rendering
  12147. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12148. submesh = sortedArray[subIndex];
  12149. submesh.render(true);
  12150. }
  12151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12152. }
  12153. return true;
  12154. };
  12155. RenderingGroup.prototype.prepare = function () {
  12156. this._opaqueSubMeshes.reset();
  12157. this._transparentSubMeshes.reset();
  12158. this._alphaTestSubMeshes.reset();
  12159. };
  12160. RenderingGroup.prototype.dispatch = function (subMesh) {
  12161. var material = subMesh.getMaterial();
  12162. var mesh = subMesh.getMesh();
  12163. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12164. this._transparentSubMeshes.push(subMesh);
  12165. }
  12166. else if (material.needAlphaTesting()) {
  12167. this._alphaTestSubMeshes.push(subMesh);
  12168. }
  12169. else {
  12170. this._opaqueSubMeshes.push(subMesh); // Opaque
  12171. }
  12172. };
  12173. return RenderingGroup;
  12174. })();
  12175. BABYLON.RenderingGroup = RenderingGroup;
  12176. })(BABYLON || (BABYLON = {}));
  12177. var BABYLON;
  12178. (function (BABYLON) {
  12179. /**
  12180. * Represents a scene to be rendered by the engine.
  12181. * @see http://doc.babylonjs.com/page.php?p=21911
  12182. */
  12183. var Scene = (function () {
  12184. /**
  12185. * @constructor
  12186. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12187. */
  12188. function Scene(engine) {
  12189. // Members
  12190. this.autoClear = true;
  12191. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12192. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12193. this.forceWireframe = false;
  12194. this.forcePointsCloud = false;
  12195. this.forceShowBoundingBoxes = false;
  12196. this.animationsEnabled = true;
  12197. this.constantlyUpdateMeshUnderPointer = false;
  12198. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12199. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12200. this._startingPointerTime = 0;
  12201. // Fog
  12202. /**
  12203. * is fog enabled on this scene.
  12204. * @type {boolean}
  12205. */
  12206. this.fogEnabled = true;
  12207. this.fogMode = Scene.FOGMODE_NONE;
  12208. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12209. this.fogDensity = 0.1;
  12210. this.fogStart = 0;
  12211. this.fogEnd = 1000.0;
  12212. // Lights
  12213. /**
  12214. * is shadow enabled on this scene.
  12215. * @type {boolean}
  12216. */
  12217. this.shadowsEnabled = true;
  12218. /**
  12219. * is light enabled on this scene.
  12220. * @type {boolean}
  12221. */
  12222. this.lightsEnabled = true;
  12223. /**
  12224. * All of the lights added to this scene.
  12225. * @see BABYLON.Light
  12226. * @type {BABYLON.Light[]}
  12227. */
  12228. this.lights = new Array();
  12229. // Cameras
  12230. /**
  12231. * All of the cameras added to this scene.
  12232. * @see BABYLON.Camera
  12233. * @type {BABYLON.Camera[]}
  12234. */
  12235. this.cameras = new Array();
  12236. this.activeCameras = new Array();
  12237. // Meshes
  12238. /**
  12239. * All of the (abstract) meshes added to this scene.
  12240. * @see BABYLON.AbstractMesh
  12241. * @type {BABYLON.AbstractMesh[]}
  12242. */
  12243. this.meshes = new Array();
  12244. // Geometries
  12245. this._geometries = new Array();
  12246. this.materials = new Array();
  12247. this.multiMaterials = new Array();
  12248. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12249. // Textures
  12250. this.texturesEnabled = true;
  12251. this.textures = new Array();
  12252. // Particles
  12253. this.particlesEnabled = true;
  12254. this.particleSystems = new Array();
  12255. // Sprites
  12256. this.spritesEnabled = true;
  12257. this.spriteManagers = new Array();
  12258. // Layers
  12259. this.layers = new Array();
  12260. // Skeletons
  12261. this.skeletonsEnabled = true;
  12262. this.skeletons = new Array();
  12263. // Lens flares
  12264. this.lensFlaresEnabled = true;
  12265. this.lensFlareSystems = new Array();
  12266. // Collisions
  12267. this.collisionsEnabled = true;
  12268. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12269. // Postprocesses
  12270. this.postProcessesEnabled = true;
  12271. // Customs render targets
  12272. this.renderTargetsEnabled = true;
  12273. this.dumpNextRenderTargets = false;
  12274. this.customRenderTargets = new Array();
  12275. // Imported meshes
  12276. this.importedMeshesFiles = new Array();
  12277. // Probes
  12278. this.probesEnabled = true;
  12279. this.reflectionProbes = new Array();
  12280. this._actionManagers = new Array();
  12281. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12282. // Procedural textures
  12283. this.proceduralTexturesEnabled = true;
  12284. this._proceduralTextures = new Array();
  12285. this.soundTracks = new Array();
  12286. this._audioEnabled = true;
  12287. this._headphone = false;
  12288. this._totalVertices = 0;
  12289. this._activeIndices = 0;
  12290. this._activeParticles = 0;
  12291. this._lastFrameDuration = 0;
  12292. this._evaluateActiveMeshesDuration = 0;
  12293. this._renderTargetsDuration = 0;
  12294. this._particlesDuration = 0;
  12295. this._renderDuration = 0;
  12296. this._spritesDuration = 0;
  12297. this._animationRatio = 0;
  12298. this._renderId = 0;
  12299. this._executeWhenReadyTimeoutId = -1;
  12300. this._toBeDisposed = new BABYLON.SmartArray(256);
  12301. this._onReadyCallbacks = new Array();
  12302. this._pendingData = []; //ANY
  12303. this._onBeforeRenderCallbacks = new Array();
  12304. this._onAfterRenderCallbacks = new Array();
  12305. this._activeMeshes = new BABYLON.SmartArray(256);
  12306. this._processedMaterials = new BABYLON.SmartArray(256);
  12307. this._renderTargets = new BABYLON.SmartArray(256);
  12308. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12309. this._activeSkeletons = new BABYLON.SmartArray(32);
  12310. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12311. this._activeBones = 0;
  12312. this._activeAnimatables = new Array();
  12313. this._transformMatrix = BABYLON.Matrix.Zero();
  12314. this._edgesRenderers = new BABYLON.SmartArray(16);
  12315. this._uniqueIdCounter = 0;
  12316. this._engine = engine;
  12317. engine.scenes.push(this);
  12318. this._renderingManager = new BABYLON.RenderingManager(this);
  12319. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12320. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12321. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12322. if (BABYLON.OutlineRenderer) {
  12323. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12324. }
  12325. this.attachControl();
  12326. this._debugLayer = new BABYLON.DebugLayer(this);
  12327. if (BABYLON.SoundTrack) {
  12328. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12329. }
  12330. //simplification queue
  12331. if (BABYLON.SimplificationQueue) {
  12332. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12333. }
  12334. //collision coordinator initialization. For now legacy per default.
  12335. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12336. }
  12337. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12338. get: function () {
  12339. return Scene._FOGMODE_NONE;
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12345. get: function () {
  12346. return Scene._FOGMODE_EXP;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12352. get: function () {
  12353. return Scene._FOGMODE_EXP2;
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12359. get: function () {
  12360. return Scene._FOGMODE_LINEAR;
  12361. },
  12362. enumerable: true,
  12363. configurable: true
  12364. });
  12365. Object.defineProperty(Scene.prototype, "debugLayer", {
  12366. // Properties
  12367. get: function () {
  12368. return this._debugLayer;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12374. get: function () {
  12375. return this._workerCollisions;
  12376. },
  12377. set: function (enabled) {
  12378. enabled = (enabled && !!Worker);
  12379. this._workerCollisions = enabled;
  12380. if (this.collisionCoordinator) {
  12381. this.collisionCoordinator.destroy();
  12382. }
  12383. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12384. this.collisionCoordinator.init(this);
  12385. },
  12386. enumerable: true,
  12387. configurable: true
  12388. });
  12389. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12390. get: function () {
  12391. return this._selectionOctree;
  12392. },
  12393. enumerable: true,
  12394. configurable: true
  12395. });
  12396. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12397. /**
  12398. * The mesh that is currently under the pointer.
  12399. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12400. */
  12401. get: function () {
  12402. return this._pointerOverMesh;
  12403. },
  12404. enumerable: true,
  12405. configurable: true
  12406. });
  12407. Object.defineProperty(Scene.prototype, "pointerX", {
  12408. /**
  12409. * Current on-screen X position of the pointer
  12410. * @return {number} X position of the pointer
  12411. */
  12412. get: function () {
  12413. return this._pointerX;
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(Scene.prototype, "pointerY", {
  12419. /**
  12420. * Current on-screen Y position of the pointer
  12421. * @return {number} Y position of the pointer
  12422. */
  12423. get: function () {
  12424. return this._pointerY;
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Scene.prototype.getCachedMaterial = function () {
  12430. return this._cachedMaterial;
  12431. };
  12432. Scene.prototype.getBoundingBoxRenderer = function () {
  12433. return this._boundingBoxRenderer;
  12434. };
  12435. Scene.prototype.getOutlineRenderer = function () {
  12436. return this._outlineRenderer;
  12437. };
  12438. Scene.prototype.getEngine = function () {
  12439. return this._engine;
  12440. };
  12441. Scene.prototype.getTotalVertices = function () {
  12442. return this._totalVertices;
  12443. };
  12444. Scene.prototype.getActiveIndices = function () {
  12445. return this._activeIndices;
  12446. };
  12447. Scene.prototype.getActiveParticles = function () {
  12448. return this._activeParticles;
  12449. };
  12450. Scene.prototype.getActiveBones = function () {
  12451. return this._activeBones;
  12452. };
  12453. // Stats
  12454. Scene.prototype.getLastFrameDuration = function () {
  12455. return this._lastFrameDuration;
  12456. };
  12457. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12458. return this._evaluateActiveMeshesDuration;
  12459. };
  12460. Scene.prototype.getActiveMeshes = function () {
  12461. return this._activeMeshes;
  12462. };
  12463. Scene.prototype.getRenderTargetsDuration = function () {
  12464. return this._renderTargetsDuration;
  12465. };
  12466. Scene.prototype.getRenderDuration = function () {
  12467. return this._renderDuration;
  12468. };
  12469. Scene.prototype.getParticlesDuration = function () {
  12470. return this._particlesDuration;
  12471. };
  12472. Scene.prototype.getSpritesDuration = function () {
  12473. return this._spritesDuration;
  12474. };
  12475. Scene.prototype.getAnimationRatio = function () {
  12476. return this._animationRatio;
  12477. };
  12478. Scene.prototype.getRenderId = function () {
  12479. return this._renderId;
  12480. };
  12481. Scene.prototype.incrementRenderId = function () {
  12482. this._renderId++;
  12483. };
  12484. Scene.prototype._updatePointerPosition = function (evt) {
  12485. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12486. this._pointerX = evt.clientX - canvasRect.left;
  12487. this._pointerY = evt.clientY - canvasRect.top;
  12488. if (this.cameraToUseForPointers) {
  12489. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12490. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12491. }
  12492. };
  12493. // Pointers handling
  12494. Scene.prototype.attachControl = function () {
  12495. var _this = this;
  12496. var spritePredicate = function (sprite) {
  12497. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12498. };
  12499. this._onPointerMove = function (evt) {
  12500. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12501. return;
  12502. }
  12503. var canvas = _this._engine.getRenderingCanvas();
  12504. _this._updatePointerPosition(evt);
  12505. // Meshes
  12506. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  12507. if (pickResult.hit && pickResult.pickedMesh) {
  12508. _this.setPointerOverSprite(null);
  12509. _this.setPointerOverMesh(pickResult.pickedMesh);
  12510. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12511. canvas.style.cursor = "pointer";
  12512. }
  12513. else {
  12514. canvas.style.cursor = "";
  12515. }
  12516. }
  12517. else {
  12518. _this.setPointerOverMesh(null);
  12519. // Sprites
  12520. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12521. if (pickResult.hit && pickResult.pickedSprite) {
  12522. canvas.style.cursor = "pointer";
  12523. _this.setPointerOverSprite(pickResult.pickedSprite);
  12524. }
  12525. else {
  12526. _this.setPointerOverSprite(null);
  12527. // Restore pointer
  12528. canvas.style.cursor = "";
  12529. }
  12530. }
  12531. if (_this.onPointerMove) {
  12532. _this.onPointerMove(evt, pickResult);
  12533. }
  12534. };
  12535. this._onPointerDown = function (evt) {
  12536. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12537. return;
  12538. }
  12539. _this._updatePointerPosition(evt);
  12540. _this._startingPointerPosition.x = _this._pointerX;
  12541. _this._startingPointerPosition.y = _this._pointerY;
  12542. _this._startingPointerTime = new Date().getTime();
  12543. var predicate = null;
  12544. // Meshes
  12545. _this._pickedDownMesh = null;
  12546. if (!_this.onPointerDown && !_this.onPointerPick) {
  12547. predicate = function (mesh) {
  12548. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12549. };
  12550. }
  12551. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12552. if (pickResult.hit && pickResult.pickedMesh) {
  12553. if (pickResult.pickedMesh.actionManager) {
  12554. _this._pickedDownMesh = pickResult.pickedMesh;
  12555. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12556. switch (evt.button) {
  12557. case 0:
  12558. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12559. break;
  12560. case 1:
  12561. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12562. break;
  12563. case 2:
  12564. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12565. break;
  12566. }
  12567. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12568. }
  12569. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12570. var that = _this;
  12571. window.setTimeout(function () {
  12572. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12573. if (pickResult.hit && pickResult.pickedMesh) {
  12574. if (pickResult.pickedMesh.actionManager) {
  12575. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12576. that._startingPointerTime = 0;
  12577. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12578. }
  12579. }
  12580. }
  12581. }, BABYLON.ActionManager.LongPressDelay);
  12582. }
  12583. }
  12584. }
  12585. if (_this.onPointerDown) {
  12586. _this.onPointerDown(evt, pickResult);
  12587. }
  12588. // Sprites
  12589. _this._pickedDownSprite = null;
  12590. if (_this.spriteManagers.length > 0) {
  12591. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12592. if (pickResult.hit && pickResult.pickedSprite) {
  12593. if (pickResult.pickedSprite.actionManager) {
  12594. _this._pickedDownSprite = pickResult.pickedSprite;
  12595. switch (evt.button) {
  12596. case 0:
  12597. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12598. break;
  12599. case 1:
  12600. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12601. break;
  12602. case 2:
  12603. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12604. break;
  12605. }
  12606. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12607. }
  12608. }
  12609. }
  12610. };
  12611. this._onPointerUp = function (evt) {
  12612. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12613. return;
  12614. }
  12615. var predicate = null;
  12616. _this._updatePointerPosition(evt);
  12617. if (!_this.onPointerUp && !_this.onPointerPick) {
  12618. predicate = function (mesh) {
  12619. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12620. };
  12621. }
  12622. // Meshes
  12623. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12624. if (pickResult.hit && pickResult.pickedMesh) {
  12625. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12626. _this.onPointerPick(evt, pickResult);
  12627. }
  12628. if (pickResult.pickedMesh.actionManager) {
  12629. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12630. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12631. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12632. }
  12633. }
  12634. }
  12635. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12636. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12637. }
  12638. if (_this.onPointerUp) {
  12639. _this.onPointerUp(evt, pickResult);
  12640. }
  12641. _this._startingPointerTime = 0;
  12642. // Sprites
  12643. if (_this.spriteManagers.length > 0) {
  12644. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12645. if (pickResult.hit && pickResult.pickedSprite) {
  12646. if (pickResult.pickedSprite.actionManager) {
  12647. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12648. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12649. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12650. }
  12651. }
  12652. }
  12653. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12654. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12655. }
  12656. }
  12657. };
  12658. this._onKeyDown = function (evt) {
  12659. if (_this.actionManager) {
  12660. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12661. }
  12662. };
  12663. this._onKeyUp = function (evt) {
  12664. if (_this.actionManager) {
  12665. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12666. }
  12667. };
  12668. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12669. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12670. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12671. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12672. // Wheel
  12673. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12674. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12675. BABYLON.Tools.RegisterTopRootEvents([
  12676. { name: "keydown", handler: this._onKeyDown },
  12677. { name: "keyup", handler: this._onKeyUp }
  12678. ]);
  12679. };
  12680. Scene.prototype.detachControl = function () {
  12681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12682. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12683. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12684. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12685. // Wheel
  12686. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12687. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12688. BABYLON.Tools.UnregisterTopRootEvents([
  12689. { name: "keydown", handler: this._onKeyDown },
  12690. { name: "keyup", handler: this._onKeyUp }
  12691. ]);
  12692. };
  12693. // Ready
  12694. Scene.prototype.isReady = function () {
  12695. if (this._pendingData.length > 0) {
  12696. return false;
  12697. }
  12698. var index;
  12699. for (index = 0; index < this._geometries.length; index++) {
  12700. var geometry = this._geometries[index];
  12701. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12702. return false;
  12703. }
  12704. }
  12705. for (index = 0; index < this.meshes.length; index++) {
  12706. var mesh = this.meshes[index];
  12707. if (!mesh.isReady()) {
  12708. return false;
  12709. }
  12710. var mat = mesh.material;
  12711. if (mat) {
  12712. if (!mat.isReady(mesh)) {
  12713. return false;
  12714. }
  12715. }
  12716. }
  12717. return true;
  12718. };
  12719. Scene.prototype.resetCachedMaterial = function () {
  12720. this._cachedMaterial = null;
  12721. };
  12722. Scene.prototype.registerBeforeRender = function (func) {
  12723. this._onBeforeRenderCallbacks.push(func);
  12724. };
  12725. Scene.prototype.unregisterBeforeRender = function (func) {
  12726. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12727. if (index > -1) {
  12728. this._onBeforeRenderCallbacks.splice(index, 1);
  12729. }
  12730. };
  12731. Scene.prototype.registerAfterRender = function (func) {
  12732. this._onAfterRenderCallbacks.push(func);
  12733. };
  12734. Scene.prototype.unregisterAfterRender = function (func) {
  12735. var index = this._onAfterRenderCallbacks.indexOf(func);
  12736. if (index > -1) {
  12737. this._onAfterRenderCallbacks.splice(index, 1);
  12738. }
  12739. };
  12740. Scene.prototype._addPendingData = function (data) {
  12741. this._pendingData.push(data);
  12742. };
  12743. Scene.prototype._removePendingData = function (data) {
  12744. var index = this._pendingData.indexOf(data);
  12745. if (index !== -1) {
  12746. this._pendingData.splice(index, 1);
  12747. }
  12748. };
  12749. Scene.prototype.getWaitingItemsCount = function () {
  12750. return this._pendingData.length;
  12751. };
  12752. /**
  12753. * Registers a function to be executed when the scene is ready.
  12754. * @param {Function} func - the function to be executed.
  12755. */
  12756. Scene.prototype.executeWhenReady = function (func) {
  12757. var _this = this;
  12758. this._onReadyCallbacks.push(func);
  12759. if (this._executeWhenReadyTimeoutId !== -1) {
  12760. return;
  12761. }
  12762. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12763. _this._checkIsReady();
  12764. }, 150);
  12765. };
  12766. Scene.prototype._checkIsReady = function () {
  12767. var _this = this;
  12768. if (this.isReady()) {
  12769. this._onReadyCallbacks.forEach(function (func) {
  12770. func();
  12771. });
  12772. this._onReadyCallbacks = [];
  12773. this._executeWhenReadyTimeoutId = -1;
  12774. return;
  12775. }
  12776. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12777. _this._checkIsReady();
  12778. }, 150);
  12779. };
  12780. // Animations
  12781. /**
  12782. * Will start the animation sequence of a given target
  12783. * @param target - the target
  12784. * @param {number} from - from which frame should animation start
  12785. * @param {number} to - till which frame should animation run.
  12786. * @param {boolean} [loop] - should the animation loop
  12787. * @param {number} [speedRatio] - the speed in which to run the animation
  12788. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12789. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12790. * @return {BABYLON.Animatable} the animatable object created for this animation
  12791. * @see BABYLON.Animatable
  12792. * @see http://doc.babylonjs.com/page.php?p=22081
  12793. */
  12794. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12795. if (speedRatio === void 0) { speedRatio = 1.0; }
  12796. this.stopAnimation(target);
  12797. if (!animatable) {
  12798. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12799. }
  12800. // Local animations
  12801. if (target.animations) {
  12802. animatable.appendAnimations(target, target.animations);
  12803. }
  12804. // Children animations
  12805. if (target.getAnimatables) {
  12806. var animatables = target.getAnimatables();
  12807. for (var index = 0; index < animatables.length; index++) {
  12808. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12809. }
  12810. }
  12811. return animatable;
  12812. };
  12813. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12814. if (speedRatio === undefined) {
  12815. speedRatio = 1.0;
  12816. }
  12817. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12818. return animatable;
  12819. };
  12820. Scene.prototype.getAnimatableByTarget = function (target) {
  12821. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12822. if (this._activeAnimatables[index].target === target) {
  12823. return this._activeAnimatables[index];
  12824. }
  12825. }
  12826. return null;
  12827. };
  12828. Object.defineProperty(Scene.prototype, "Animatables", {
  12829. get: function () {
  12830. return this._activeAnimatables;
  12831. },
  12832. enumerable: true,
  12833. configurable: true
  12834. });
  12835. /**
  12836. * Will stop the animation of the given target
  12837. * @param target - the target
  12838. * @see beginAnimation
  12839. */
  12840. Scene.prototype.stopAnimation = function (target) {
  12841. var animatable = this.getAnimatableByTarget(target);
  12842. if (animatable) {
  12843. animatable.stop();
  12844. }
  12845. };
  12846. Scene.prototype._animate = function () {
  12847. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12848. return;
  12849. }
  12850. if (!this._animationStartDate) {
  12851. if (this._pendingData.length > 0) {
  12852. return;
  12853. }
  12854. this._animationStartDate = BABYLON.Tools.Now;
  12855. }
  12856. // Getting time
  12857. var now = BABYLON.Tools.Now;
  12858. var delay = now - this._animationStartDate;
  12859. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12860. this._activeAnimatables[index]._animate(delay);
  12861. }
  12862. };
  12863. // Matrix
  12864. Scene.prototype.getViewMatrix = function () {
  12865. return this._viewMatrix;
  12866. };
  12867. Scene.prototype.getProjectionMatrix = function () {
  12868. return this._projectionMatrix;
  12869. };
  12870. Scene.prototype.getTransformMatrix = function () {
  12871. return this._transformMatrix;
  12872. };
  12873. Scene.prototype.setTransformMatrix = function (view, projection) {
  12874. this._viewMatrix = view;
  12875. this._projectionMatrix = projection;
  12876. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12877. };
  12878. // Methods
  12879. Scene.prototype.addMesh = function (newMesh) {
  12880. newMesh.uniqueId = this._uniqueIdCounter++;
  12881. var position = this.meshes.push(newMesh);
  12882. //notify the collision coordinator
  12883. this.collisionCoordinator.onMeshAdded(newMesh);
  12884. if (this.onNewMeshAdded) {
  12885. this.onNewMeshAdded(newMesh, position, this);
  12886. }
  12887. };
  12888. Scene.prototype.removeMesh = function (toRemove) {
  12889. var index = this.meshes.indexOf(toRemove);
  12890. if (index !== -1) {
  12891. // Remove from the scene if mesh found
  12892. this.meshes.splice(index, 1);
  12893. }
  12894. //notify the collision coordinator
  12895. this.collisionCoordinator.onMeshRemoved(toRemove);
  12896. if (this.onMeshRemoved) {
  12897. this.onMeshRemoved(toRemove);
  12898. }
  12899. return index;
  12900. };
  12901. Scene.prototype.removeSkeleton = function (toRemove) {
  12902. var index = this.skeletons.indexOf(toRemove);
  12903. if (index !== -1) {
  12904. // Remove from the scene if mesh found
  12905. this.skeletons.splice(index, 1);
  12906. }
  12907. return index;
  12908. };
  12909. Scene.prototype.removeLight = function (toRemove) {
  12910. var index = this.lights.indexOf(toRemove);
  12911. if (index !== -1) {
  12912. // Remove from the scene if mesh found
  12913. this.lights.splice(index, 1);
  12914. }
  12915. if (this.onLightRemoved) {
  12916. this.onLightRemoved(toRemove);
  12917. }
  12918. return index;
  12919. };
  12920. Scene.prototype.removeCamera = function (toRemove) {
  12921. var index = this.cameras.indexOf(toRemove);
  12922. if (index !== -1) {
  12923. // Remove from the scene if mesh found
  12924. this.cameras.splice(index, 1);
  12925. }
  12926. // Remove from activeCameras
  12927. var index2 = this.activeCameras.indexOf(toRemove);
  12928. if (index2 !== -1) {
  12929. // Remove from the scene if mesh found
  12930. this.activeCameras.splice(index2, 1);
  12931. }
  12932. // Reset the activeCamera
  12933. if (this.activeCamera === toRemove) {
  12934. if (this.cameras.length > 0) {
  12935. this.activeCamera = this.cameras[0];
  12936. }
  12937. else {
  12938. this.activeCamera = null;
  12939. }
  12940. }
  12941. if (this.onCameraRemoved) {
  12942. this.onCameraRemoved(toRemove);
  12943. }
  12944. return index;
  12945. };
  12946. Scene.prototype.addLight = function (newLight) {
  12947. newLight.uniqueId = this._uniqueIdCounter++;
  12948. var position = this.lights.push(newLight);
  12949. if (this.onNewLightAdded) {
  12950. this.onNewLightAdded(newLight, position, this);
  12951. }
  12952. };
  12953. Scene.prototype.addCamera = function (newCamera) {
  12954. newCamera.uniqueId = this._uniqueIdCounter++;
  12955. var position = this.cameras.push(newCamera);
  12956. if (this.onNewCameraAdded) {
  12957. this.onNewCameraAdded(newCamera, position, this);
  12958. }
  12959. };
  12960. /**
  12961. * Switch active camera
  12962. * @param {Camera} newCamera - new active camera
  12963. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  12964. */
  12965. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  12966. if (attachControl === void 0) { attachControl = true; }
  12967. var canvas = this._engine.getRenderingCanvas();
  12968. this.activeCamera.detachControl(canvas);
  12969. this.activeCamera = newCamera;
  12970. if (attachControl) {
  12971. newCamera.attachControl(canvas);
  12972. }
  12973. };
  12974. /**
  12975. * sets the active camera of the scene using its ID
  12976. * @param {string} id - the camera's ID
  12977. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12978. * @see activeCamera
  12979. */
  12980. Scene.prototype.setActiveCameraByID = function (id) {
  12981. var camera = this.getCameraByID(id);
  12982. if (camera) {
  12983. this.activeCamera = camera;
  12984. return camera;
  12985. }
  12986. return null;
  12987. };
  12988. /**
  12989. * sets the active camera of the scene using its name
  12990. * @param {string} name - the camera's name
  12991. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12992. * @see activeCamera
  12993. */
  12994. Scene.prototype.setActiveCameraByName = function (name) {
  12995. var camera = this.getCameraByName(name);
  12996. if (camera) {
  12997. this.activeCamera = camera;
  12998. return camera;
  12999. }
  13000. return null;
  13001. };
  13002. /**
  13003. * get a material using its id
  13004. * @param {string} the material's ID
  13005. * @return {BABYLON.Material|null} the material or null if none found.
  13006. */
  13007. Scene.prototype.getMaterialByID = function (id) {
  13008. for (var index = 0; index < this.materials.length; index++) {
  13009. if (this.materials[index].id === id) {
  13010. return this.materials[index];
  13011. }
  13012. }
  13013. return null;
  13014. };
  13015. /**
  13016. * get a material using its name
  13017. * @param {string} the material's name
  13018. * @return {BABYLON.Material|null} the material or null if none found.
  13019. */
  13020. Scene.prototype.getMaterialByName = function (name) {
  13021. for (var index = 0; index < this.materials.length; index++) {
  13022. if (this.materials[index].name === name) {
  13023. return this.materials[index];
  13024. }
  13025. }
  13026. return null;
  13027. };
  13028. Scene.prototype.getLensFlareSystemByName = function (name) {
  13029. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13030. if (this.lensFlareSystems[index].name === name) {
  13031. return this.lensFlareSystems[index];
  13032. }
  13033. }
  13034. return null;
  13035. };
  13036. Scene.prototype.getCameraByID = function (id) {
  13037. for (var index = 0; index < this.cameras.length; index++) {
  13038. if (this.cameras[index].id === id) {
  13039. return this.cameras[index];
  13040. }
  13041. }
  13042. return null;
  13043. };
  13044. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13045. for (var index = 0; index < this.cameras.length; index++) {
  13046. if (this.cameras[index].uniqueId === uniqueId) {
  13047. return this.cameras[index];
  13048. }
  13049. }
  13050. return null;
  13051. };
  13052. /**
  13053. * get a camera using its name
  13054. * @param {string} the camera's name
  13055. * @return {BABYLON.Camera|null} the camera or null if none found.
  13056. */
  13057. Scene.prototype.getCameraByName = function (name) {
  13058. for (var index = 0; index < this.cameras.length; index++) {
  13059. if (this.cameras[index].name === name) {
  13060. return this.cameras[index];
  13061. }
  13062. }
  13063. return null;
  13064. };
  13065. /**
  13066. * get a bone using its id
  13067. * @param {string} the bone's id
  13068. * @return {BABYLON.Bone|null} the bone or null if not found
  13069. */
  13070. Scene.prototype.getBoneByID = function (id) {
  13071. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13072. var skeleton = this.skeletons[skeletonIndex];
  13073. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13074. if (skeleton.bones[boneIndex].id === id) {
  13075. return skeleton.bones[boneIndex];
  13076. }
  13077. }
  13078. }
  13079. return null;
  13080. };
  13081. /**
  13082. * get a bone using its id
  13083. * @param {string} the bone's name
  13084. * @return {BABYLON.Bone|null} the bone or null if not found
  13085. */
  13086. Scene.prototype.getBoneByName = function (name) {
  13087. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13088. var skeleton = this.skeletons[skeletonIndex];
  13089. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13090. if (skeleton.bones[boneIndex].name === name) {
  13091. return skeleton.bones[boneIndex];
  13092. }
  13093. }
  13094. }
  13095. return null;
  13096. };
  13097. /**
  13098. * get a light node using its name
  13099. * @param {string} the light's name
  13100. * @return {BABYLON.Light|null} the light or null if none found.
  13101. */
  13102. Scene.prototype.getLightByName = function (name) {
  13103. for (var index = 0; index < this.lights.length; index++) {
  13104. if (this.lights[index].name === name) {
  13105. return this.lights[index];
  13106. }
  13107. }
  13108. return null;
  13109. };
  13110. /**
  13111. * get a light node using its ID
  13112. * @param {string} the light's id
  13113. * @return {BABYLON.Light|null} the light or null if none found.
  13114. */
  13115. Scene.prototype.getLightByID = function (id) {
  13116. for (var index = 0; index < this.lights.length; index++) {
  13117. if (this.lights[index].id === id) {
  13118. return this.lights[index];
  13119. }
  13120. }
  13121. return null;
  13122. };
  13123. /**
  13124. * get a light node using its scene-generated unique ID
  13125. * @param {number} the light's unique id
  13126. * @return {BABYLON.Light|null} the light or null if none found.
  13127. */
  13128. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13129. for (var index = 0; index < this.lights.length; index++) {
  13130. if (this.lights[index].uniqueId === uniqueId) {
  13131. return this.lights[index];
  13132. }
  13133. }
  13134. return null;
  13135. };
  13136. /**
  13137. * get a particle system by id
  13138. * @param id {number} the particle system id
  13139. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13140. */
  13141. Scene.prototype.getParticleSystemByID = function (id) {
  13142. for (var index = 0; index < this.particleSystems.length; index++) {
  13143. if (this.particleSystems[index].id === id) {
  13144. return this.particleSystems[index];
  13145. }
  13146. }
  13147. return null;
  13148. };
  13149. /**
  13150. * get a geometry using its ID
  13151. * @param {string} the geometry's id
  13152. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13153. */
  13154. Scene.prototype.getGeometryByID = function (id) {
  13155. for (var index = 0; index < this._geometries.length; index++) {
  13156. if (this._geometries[index].id === id) {
  13157. return this._geometries[index];
  13158. }
  13159. }
  13160. return null;
  13161. };
  13162. /**
  13163. * add a new geometry to this scene.
  13164. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13165. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13166. * @return {boolean} was the geometry added or not
  13167. */
  13168. Scene.prototype.pushGeometry = function (geometry, force) {
  13169. if (!force && this.getGeometryByID(geometry.id)) {
  13170. return false;
  13171. }
  13172. this._geometries.push(geometry);
  13173. //notify the collision coordinator
  13174. this.collisionCoordinator.onGeometryAdded(geometry);
  13175. if (this.onGeometryAdded) {
  13176. this.onGeometryAdded(geometry);
  13177. }
  13178. return true;
  13179. };
  13180. /**
  13181. * Removes an existing geometry
  13182. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13183. * @return {boolean} was the geometry removed or not
  13184. */
  13185. Scene.prototype.removeGeometry = function (geometry) {
  13186. var index = this._geometries.indexOf(geometry);
  13187. if (index > -1) {
  13188. this._geometries.splice(index, 1);
  13189. //notify the collision coordinator
  13190. this.collisionCoordinator.onGeometryDeleted(geometry);
  13191. if (this.onGeometryRemoved) {
  13192. this.onGeometryRemoved(geometry);
  13193. }
  13194. return true;
  13195. }
  13196. return false;
  13197. };
  13198. Scene.prototype.getGeometries = function () {
  13199. return this._geometries;
  13200. };
  13201. /**
  13202. * Get the first added mesh found of a given ID
  13203. * @param {string} id - the id to search for
  13204. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13205. */
  13206. Scene.prototype.getMeshByID = function (id) {
  13207. for (var index = 0; index < this.meshes.length; index++) {
  13208. if (this.meshes[index].id === id) {
  13209. return this.meshes[index];
  13210. }
  13211. }
  13212. return null;
  13213. };
  13214. /**
  13215. * Get a mesh with its auto-generated unique id
  13216. * @param {number} uniqueId - the unique id to search for
  13217. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13218. */
  13219. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13220. for (var index = 0; index < this.meshes.length; index++) {
  13221. if (this.meshes[index].uniqueId === uniqueId) {
  13222. return this.meshes[index];
  13223. }
  13224. }
  13225. return null;
  13226. };
  13227. /**
  13228. * Get a the last added mesh found of a given ID
  13229. * @param {string} id - the id to search for
  13230. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13231. */
  13232. Scene.prototype.getLastMeshByID = function (id) {
  13233. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13234. if (this.meshes[index].id === id) {
  13235. return this.meshes[index];
  13236. }
  13237. }
  13238. return null;
  13239. };
  13240. /**
  13241. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13242. * @param {string} id - the id to search for
  13243. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13244. */
  13245. Scene.prototype.getLastEntryByID = function (id) {
  13246. var index;
  13247. for (index = this.meshes.length - 1; index >= 0; index--) {
  13248. if (this.meshes[index].id === id) {
  13249. return this.meshes[index];
  13250. }
  13251. }
  13252. for (index = this.cameras.length - 1; index >= 0; index--) {
  13253. if (this.cameras[index].id === id) {
  13254. return this.cameras[index];
  13255. }
  13256. }
  13257. for (index = this.lights.length - 1; index >= 0; index--) {
  13258. if (this.lights[index].id === id) {
  13259. return this.lights[index];
  13260. }
  13261. }
  13262. return null;
  13263. };
  13264. Scene.prototype.getNodeByID = function (id) {
  13265. var mesh = this.getMeshByID(id);
  13266. if (mesh) {
  13267. return mesh;
  13268. }
  13269. var light = this.getLightByID(id);
  13270. if (light) {
  13271. return light;
  13272. }
  13273. var camera = this.getCameraByID(id);
  13274. if (camera) {
  13275. return camera;
  13276. }
  13277. var bone = this.getBoneByID(id);
  13278. return bone;
  13279. };
  13280. Scene.prototype.getNodeByName = function (name) {
  13281. var mesh = this.getMeshByName(name);
  13282. if (mesh) {
  13283. return mesh;
  13284. }
  13285. var light = this.getLightByName(name);
  13286. if (light) {
  13287. return light;
  13288. }
  13289. var camera = this.getCameraByName(name);
  13290. if (camera) {
  13291. return camera;
  13292. }
  13293. var bone = this.getBoneByName(name);
  13294. return bone;
  13295. };
  13296. Scene.prototype.getMeshByName = function (name) {
  13297. for (var index = 0; index < this.meshes.length; index++) {
  13298. if (this.meshes[index].name === name) {
  13299. return this.meshes[index];
  13300. }
  13301. }
  13302. return null;
  13303. };
  13304. Scene.prototype.getSoundByName = function (name) {
  13305. var index;
  13306. if (BABYLON.AudioEngine) {
  13307. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13308. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13309. return this.mainSoundTrack.soundCollection[index];
  13310. }
  13311. }
  13312. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13313. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13314. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13315. return this.soundTracks[sdIndex].soundCollection[index];
  13316. }
  13317. }
  13318. }
  13319. }
  13320. return null;
  13321. };
  13322. Scene.prototype.getLastSkeletonByID = function (id) {
  13323. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13324. if (this.skeletons[index].id === id) {
  13325. return this.skeletons[index];
  13326. }
  13327. }
  13328. return null;
  13329. };
  13330. Scene.prototype.getSkeletonById = function (id) {
  13331. for (var index = 0; index < this.skeletons.length; index++) {
  13332. if (this.skeletons[index].id === id) {
  13333. return this.skeletons[index];
  13334. }
  13335. }
  13336. return null;
  13337. };
  13338. Scene.prototype.getSkeletonByName = function (name) {
  13339. for (var index = 0; index < this.skeletons.length; index++) {
  13340. if (this.skeletons[index].name === name) {
  13341. return this.skeletons[index];
  13342. }
  13343. }
  13344. return null;
  13345. };
  13346. Scene.prototype.isActiveMesh = function (mesh) {
  13347. return (this._activeMeshes.indexOf(mesh) !== -1);
  13348. };
  13349. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13350. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13351. var material = subMesh.getMaterial();
  13352. if (mesh.showSubMeshesBoundingBox) {
  13353. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13354. }
  13355. if (material) {
  13356. // Render targets
  13357. if (material.getRenderTargetTextures) {
  13358. if (this._processedMaterials.indexOf(material) === -1) {
  13359. this._processedMaterials.push(material);
  13360. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13361. }
  13362. }
  13363. // Dispatch
  13364. this._activeIndices += subMesh.indexCount;
  13365. this._renderingManager.dispatch(subMesh);
  13366. }
  13367. }
  13368. };
  13369. Scene.prototype._evaluateActiveMeshes = function () {
  13370. this.activeCamera._activeMeshes.reset();
  13371. this._activeMeshes.reset();
  13372. this._renderingManager.reset();
  13373. this._processedMaterials.reset();
  13374. this._activeParticleSystems.reset();
  13375. this._activeSkeletons.reset();
  13376. this._softwareSkinnedMeshes.reset();
  13377. this._boundingBoxRenderer.reset();
  13378. this._edgesRenderers.reset();
  13379. if (!this._frustumPlanes) {
  13380. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13381. }
  13382. else {
  13383. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13384. }
  13385. // Meshes
  13386. var meshes;
  13387. var len;
  13388. if (this._selectionOctree) {
  13389. var selection = this._selectionOctree.select(this._frustumPlanes);
  13390. meshes = selection.data;
  13391. len = selection.length;
  13392. }
  13393. else {
  13394. len = this.meshes.length;
  13395. meshes = this.meshes;
  13396. }
  13397. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13398. var mesh = meshes[meshIndex];
  13399. if (mesh.isBlocked) {
  13400. continue;
  13401. }
  13402. this._totalVertices += mesh.getTotalVertices();
  13403. if (!mesh.isReady() || !mesh.isEnabled()) {
  13404. continue;
  13405. }
  13406. mesh.computeWorldMatrix();
  13407. // Intersections
  13408. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13409. this._meshesForIntersections.pushNoDuplicate(mesh);
  13410. }
  13411. // Switch to current LOD
  13412. var meshLOD = mesh.getLOD(this.activeCamera);
  13413. if (!meshLOD) {
  13414. continue;
  13415. }
  13416. mesh._preActivate();
  13417. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13418. this._activeMeshes.push(mesh);
  13419. this.activeCamera._activeMeshes.push(mesh);
  13420. mesh._activate(this._renderId);
  13421. this._activeMesh(meshLOD);
  13422. }
  13423. }
  13424. // Particle systems
  13425. var beforeParticlesDate = BABYLON.Tools.Now;
  13426. if (this.particlesEnabled) {
  13427. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13428. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13429. var particleSystem = this.particleSystems[particleIndex];
  13430. if (!particleSystem.isStarted()) {
  13431. continue;
  13432. }
  13433. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13434. this._activeParticleSystems.push(particleSystem);
  13435. particleSystem.animate();
  13436. }
  13437. }
  13438. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13439. }
  13440. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13441. };
  13442. Scene.prototype._activeMesh = function (mesh) {
  13443. if (mesh.skeleton && this.skeletonsEnabled) {
  13444. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13445. if (!mesh.computeBonesUsingShaders) {
  13446. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13447. }
  13448. }
  13449. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13450. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13451. }
  13452. if (mesh._edgesRenderer) {
  13453. this._edgesRenderers.push(mesh._edgesRenderer);
  13454. }
  13455. if (mesh && mesh.subMeshes) {
  13456. // Submeshes Octrees
  13457. var len;
  13458. var subMeshes;
  13459. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13460. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13461. len = intersections.length;
  13462. subMeshes = intersections.data;
  13463. }
  13464. else {
  13465. subMeshes = mesh.subMeshes;
  13466. len = subMeshes.length;
  13467. }
  13468. for (var subIndex = 0; subIndex < len; subIndex++) {
  13469. var subMesh = subMeshes[subIndex];
  13470. this._evaluateSubMesh(subMesh, mesh);
  13471. }
  13472. }
  13473. };
  13474. Scene.prototype.updateTransformMatrix = function (force) {
  13475. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13476. };
  13477. Scene.prototype._renderForCamera = function (camera) {
  13478. var engine = this._engine;
  13479. this.activeCamera = camera;
  13480. if (!this.activeCamera)
  13481. throw new Error("Active camera not set");
  13482. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13483. // Viewport
  13484. engine.setViewport(this.activeCamera.viewport);
  13485. // Camera
  13486. this.resetCachedMaterial();
  13487. this._renderId++;
  13488. this.updateTransformMatrix();
  13489. if (this.beforeCameraRender) {
  13490. this.beforeCameraRender(this.activeCamera);
  13491. }
  13492. // Meshes
  13493. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13494. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13495. this._evaluateActiveMeshes();
  13496. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13497. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13498. // Skeletons
  13499. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13500. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13501. skeleton.prepare();
  13502. }
  13503. // Software skinning
  13504. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13505. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13506. mesh.applySkeleton(mesh.skeleton);
  13507. }
  13508. // Render targets
  13509. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13510. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13511. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13512. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13513. var renderTarget = this._renderTargets.data[renderIndex];
  13514. if (renderTarget._shouldRender()) {
  13515. this._renderId++;
  13516. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13517. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13518. }
  13519. }
  13520. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13521. this._renderId++;
  13522. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13523. }
  13524. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13525. // Prepare Frame
  13526. this.postProcessManager._prepareFrame();
  13527. var beforeRenderDate = BABYLON.Tools.Now;
  13528. // Backgrounds
  13529. var layerIndex;
  13530. var layer;
  13531. if (this.layers.length) {
  13532. engine.setDepthBuffer(false);
  13533. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13534. layer = this.layers[layerIndex];
  13535. if (layer.isBackground) {
  13536. layer.render();
  13537. }
  13538. }
  13539. engine.setDepthBuffer(true);
  13540. }
  13541. // Render
  13542. BABYLON.Tools.StartPerformanceCounter("Main render");
  13543. this._renderingManager.render(null, null, true, true);
  13544. BABYLON.Tools.EndPerformanceCounter("Main render");
  13545. // Bounding boxes
  13546. this._boundingBoxRenderer.render();
  13547. // Edges
  13548. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13549. this._edgesRenderers.data[edgesRendererIndex].render();
  13550. }
  13551. // Lens flares
  13552. if (this.lensFlaresEnabled) {
  13553. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13554. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13555. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13556. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13557. lensFlareSystem.render();
  13558. }
  13559. }
  13560. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13561. }
  13562. // Foregrounds
  13563. if (this.layers.length) {
  13564. engine.setDepthBuffer(false);
  13565. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13566. layer = this.layers[layerIndex];
  13567. if (!layer.isBackground) {
  13568. layer.render();
  13569. }
  13570. }
  13571. engine.setDepthBuffer(true);
  13572. }
  13573. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13574. // Finalize frame
  13575. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13576. // Update camera
  13577. this.activeCamera._updateFromScene();
  13578. // Reset some special arrays
  13579. this._renderTargets.reset();
  13580. if (this.afterCameraRender) {
  13581. this.afterCameraRender(this.activeCamera);
  13582. }
  13583. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13584. };
  13585. Scene.prototype._processSubCameras = function (camera) {
  13586. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13587. this._renderForCamera(camera);
  13588. return;
  13589. }
  13590. // rig cameras
  13591. for (var index = 0; index < camera._rigCameras.length; index++) {
  13592. this._renderForCamera(camera._rigCameras[index]);
  13593. }
  13594. this.activeCamera = camera;
  13595. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13596. // Update camera
  13597. this.activeCamera._updateFromScene();
  13598. };
  13599. Scene.prototype._checkIntersections = function () {
  13600. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13601. var sourceMesh = this._meshesForIntersections.data[index];
  13602. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13603. var action = sourceMesh.actionManager.actions[actionIndex];
  13604. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13605. var parameters = action.getTriggerParameter();
  13606. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13607. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13608. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13609. if (areIntersecting && currentIntersectionInProgress === -1) {
  13610. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13611. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13612. sourceMesh._intersectionsInProgress.push(otherMesh);
  13613. }
  13614. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13615. sourceMesh._intersectionsInProgress.push(otherMesh);
  13616. }
  13617. }
  13618. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13619. //They intersected, and now they don't.
  13620. //is this trigger an exit trigger? execute an event.
  13621. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13622. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13623. }
  13624. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13625. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13626. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13627. }
  13628. }
  13629. }
  13630. }
  13631. }
  13632. };
  13633. Scene.prototype.render = function () {
  13634. var startDate = BABYLON.Tools.Now;
  13635. this._particlesDuration = 0;
  13636. this._spritesDuration = 0;
  13637. this._activeParticles = 0;
  13638. this._renderDuration = 0;
  13639. this._renderTargetsDuration = 0;
  13640. this._evaluateActiveMeshesDuration = 0;
  13641. this._totalVertices = 0;
  13642. this._activeIndices = 0;
  13643. this._activeBones = 0;
  13644. this.getEngine().resetDrawCalls();
  13645. this._meshesForIntersections.reset();
  13646. this.resetCachedMaterial();
  13647. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13648. // Actions
  13649. if (this.actionManager) {
  13650. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13651. }
  13652. //Simplification Queue
  13653. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13654. this.simplificationQueue.executeNext();
  13655. }
  13656. // Animations
  13657. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13658. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13659. this._animate();
  13660. // Physics
  13661. if (this._physicsEngine) {
  13662. BABYLON.Tools.StartPerformanceCounter("Physics");
  13663. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13664. BABYLON.Tools.EndPerformanceCounter("Physics");
  13665. }
  13666. // Before render
  13667. if (this.beforeRender) {
  13668. this.beforeRender();
  13669. }
  13670. var callbackIndex;
  13671. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13672. this._onBeforeRenderCallbacks[callbackIndex]();
  13673. }
  13674. // Customs render targets
  13675. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13676. var engine = this.getEngine();
  13677. var currentActiveCamera = this.activeCamera;
  13678. if (this.renderTargetsEnabled) {
  13679. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13680. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13681. var renderTarget = this.customRenderTargets[customIndex];
  13682. if (renderTarget._shouldRender()) {
  13683. this._renderId++;
  13684. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13685. if (!this.activeCamera)
  13686. throw new Error("Active camera not set");
  13687. // Viewport
  13688. engine.setViewport(this.activeCamera.viewport);
  13689. // Camera
  13690. this.updateTransformMatrix();
  13691. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13692. }
  13693. }
  13694. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13695. this._renderId++;
  13696. }
  13697. if (this.customRenderTargets.length > 0) {
  13698. engine.restoreDefaultFramebuffer();
  13699. }
  13700. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13701. this.activeCamera = currentActiveCamera;
  13702. // Procedural textures
  13703. if (this.proceduralTexturesEnabled) {
  13704. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13705. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13706. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13707. if (proceduralTexture._shouldRender()) {
  13708. proceduralTexture.render();
  13709. }
  13710. }
  13711. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13712. }
  13713. // Clear
  13714. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13715. // Shadows
  13716. if (this.shadowsEnabled) {
  13717. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13718. var light = this.lights[lightIndex];
  13719. var shadowGenerator = light.getShadowGenerator();
  13720. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13721. this._renderTargets.push(shadowGenerator.getShadowMap());
  13722. }
  13723. }
  13724. }
  13725. // Depth renderer
  13726. if (this._depthRenderer) {
  13727. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13728. }
  13729. // RenderPipeline
  13730. this.postProcessRenderPipelineManager.update();
  13731. // Multi-cameras?
  13732. if (this.activeCameras.length > 0) {
  13733. var currentRenderId = this._renderId;
  13734. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13735. this._renderId = currentRenderId;
  13736. if (cameraIndex > 0) {
  13737. this._engine.clear(0, false, true);
  13738. }
  13739. this._processSubCameras(this.activeCameras[cameraIndex]);
  13740. }
  13741. }
  13742. else {
  13743. if (!this.activeCamera) {
  13744. throw new Error("No camera defined");
  13745. }
  13746. this._processSubCameras(this.activeCamera);
  13747. }
  13748. // Intersection checks
  13749. this._checkIntersections();
  13750. // Update the audio listener attached to the camera
  13751. if (BABYLON.AudioEngine) {
  13752. this._updateAudioParameters();
  13753. }
  13754. // After render
  13755. if (this.afterRender) {
  13756. this.afterRender();
  13757. }
  13758. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13759. this._onAfterRenderCallbacks[callbackIndex]();
  13760. }
  13761. // Cleaning
  13762. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13763. this._toBeDisposed.data[index].dispose();
  13764. this._toBeDisposed[index] = null;
  13765. }
  13766. this._toBeDisposed.reset();
  13767. if (this.dumpNextRenderTargets) {
  13768. this.dumpNextRenderTargets = false;
  13769. }
  13770. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13771. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13772. };
  13773. Scene.prototype._updateAudioParameters = function () {
  13774. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13775. return;
  13776. }
  13777. var listeningCamera;
  13778. var audioEngine = BABYLON.Engine.audioEngine;
  13779. if (this.activeCameras.length > 0) {
  13780. listeningCamera = this.activeCameras[0];
  13781. }
  13782. else {
  13783. listeningCamera = this.activeCamera;
  13784. }
  13785. if (listeningCamera && audioEngine.canUseWebAudio) {
  13786. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13787. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13788. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13789. cameraDirection.normalize();
  13790. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13791. var i;
  13792. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13793. var sound = this.mainSoundTrack.soundCollection[i];
  13794. if (sound.useCustomAttenuation) {
  13795. sound.updateDistanceFromListener();
  13796. }
  13797. }
  13798. for (i = 0; i < this.soundTracks.length; i++) {
  13799. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13800. sound = this.soundTracks[i].soundCollection[j];
  13801. if (sound.useCustomAttenuation) {
  13802. sound.updateDistanceFromListener();
  13803. }
  13804. }
  13805. }
  13806. }
  13807. };
  13808. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13809. // Audio
  13810. get: function () {
  13811. return this._audioEnabled;
  13812. },
  13813. set: function (value) {
  13814. this._audioEnabled = value;
  13815. if (BABYLON.AudioEngine) {
  13816. if (this._audioEnabled) {
  13817. this._enableAudio();
  13818. }
  13819. else {
  13820. this._disableAudio();
  13821. }
  13822. }
  13823. },
  13824. enumerable: true,
  13825. configurable: true
  13826. });
  13827. Scene.prototype._disableAudio = function () {
  13828. var i;
  13829. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13830. this.mainSoundTrack.soundCollection[i].pause();
  13831. }
  13832. for (i = 0; i < this.soundTracks.length; i++) {
  13833. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13834. this.soundTracks[i].soundCollection[j].pause();
  13835. }
  13836. }
  13837. };
  13838. Scene.prototype._enableAudio = function () {
  13839. var i;
  13840. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13841. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13842. this.mainSoundTrack.soundCollection[i].play();
  13843. }
  13844. }
  13845. for (i = 0; i < this.soundTracks.length; i++) {
  13846. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13847. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13848. this.soundTracks[i].soundCollection[j].play();
  13849. }
  13850. }
  13851. }
  13852. };
  13853. Object.defineProperty(Scene.prototype, "headphone", {
  13854. get: function () {
  13855. return this._headphone;
  13856. },
  13857. set: function (value) {
  13858. this._headphone = value;
  13859. if (BABYLON.AudioEngine) {
  13860. if (this._headphone) {
  13861. this._switchAudioModeForHeadphones();
  13862. }
  13863. else {
  13864. this._switchAudioModeForNormalSpeakers();
  13865. }
  13866. }
  13867. },
  13868. enumerable: true,
  13869. configurable: true
  13870. });
  13871. Scene.prototype._switchAudioModeForHeadphones = function () {
  13872. this.mainSoundTrack.switchPanningModelToHRTF();
  13873. for (var i = 0; i < this.soundTracks.length; i++) {
  13874. this.soundTracks[i].switchPanningModelToHRTF();
  13875. }
  13876. };
  13877. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13878. this.mainSoundTrack.switchPanningModelToEqualPower();
  13879. for (var i = 0; i < this.soundTracks.length; i++) {
  13880. this.soundTracks[i].switchPanningModelToEqualPower();
  13881. }
  13882. };
  13883. Scene.prototype.enableDepthRenderer = function () {
  13884. if (this._depthRenderer) {
  13885. return this._depthRenderer;
  13886. }
  13887. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13888. return this._depthRenderer;
  13889. };
  13890. Scene.prototype.disableDepthRenderer = function () {
  13891. if (!this._depthRenderer) {
  13892. return;
  13893. }
  13894. this._depthRenderer.dispose();
  13895. this._depthRenderer = null;
  13896. };
  13897. Scene.prototype.freezeMaterials = function () {
  13898. for (var i = 0; i < this.materials.length; i++) {
  13899. this.materials[i].freeze();
  13900. }
  13901. };
  13902. Scene.prototype.unfreezeMaterials = function () {
  13903. for (var i = 0; i < this.materials.length; i++) {
  13904. this.materials[i].unfreeze();
  13905. }
  13906. };
  13907. Scene.prototype.dispose = function () {
  13908. this.beforeRender = null;
  13909. this.afterRender = null;
  13910. this.skeletons = [];
  13911. this._boundingBoxRenderer.dispose();
  13912. if (this._depthRenderer) {
  13913. this._depthRenderer.dispose();
  13914. }
  13915. // Debug layer
  13916. this.debugLayer.hide();
  13917. // Events
  13918. if (this.onDispose) {
  13919. this.onDispose();
  13920. }
  13921. this._onBeforeRenderCallbacks = [];
  13922. this._onAfterRenderCallbacks = [];
  13923. this.detachControl();
  13924. // Release sounds & sounds tracks
  13925. if (BABYLON.AudioEngine) {
  13926. this.disposeSounds();
  13927. }
  13928. // Detach cameras
  13929. var canvas = this._engine.getRenderingCanvas();
  13930. var index;
  13931. for (index = 0; index < this.cameras.length; index++) {
  13932. this.cameras[index].detachControl(canvas);
  13933. }
  13934. // Release lights
  13935. while (this.lights.length) {
  13936. this.lights[0].dispose();
  13937. }
  13938. // Release meshes
  13939. while (this.meshes.length) {
  13940. this.meshes[0].dispose(true);
  13941. }
  13942. // Release cameras
  13943. while (this.cameras.length) {
  13944. this.cameras[0].dispose();
  13945. }
  13946. // Release materials
  13947. while (this.materials.length) {
  13948. this.materials[0].dispose();
  13949. }
  13950. // Release particles
  13951. while (this.particleSystems.length) {
  13952. this.particleSystems[0].dispose();
  13953. }
  13954. // Release sprites
  13955. while (this.spriteManagers.length) {
  13956. this.spriteManagers[0].dispose();
  13957. }
  13958. // Release layers
  13959. while (this.layers.length) {
  13960. this.layers[0].dispose();
  13961. }
  13962. // Release textures
  13963. while (this.textures.length) {
  13964. this.textures[0].dispose();
  13965. }
  13966. // Post-processes
  13967. this.postProcessManager.dispose();
  13968. // Physics
  13969. if (this._physicsEngine) {
  13970. this.disablePhysicsEngine();
  13971. }
  13972. // Remove from engine
  13973. index = this._engine.scenes.indexOf(this);
  13974. if (index > -1) {
  13975. this._engine.scenes.splice(index, 1);
  13976. }
  13977. this._engine.wipeCaches();
  13978. };
  13979. // Release sounds & sounds tracks
  13980. Scene.prototype.disposeSounds = function () {
  13981. this.mainSoundTrack.dispose();
  13982. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13983. this.soundTracks[scIndex].dispose();
  13984. }
  13985. };
  13986. // Octrees
  13987. Scene.prototype.getWorldExtends = function () {
  13988. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13989. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13990. for (var index = 0; index < this.meshes.length; index++) {
  13991. var mesh = this.meshes[index];
  13992. mesh.computeWorldMatrix(true);
  13993. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13994. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13995. BABYLON.Tools.CheckExtends(minBox, min, max);
  13996. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13997. }
  13998. return {
  13999. min: min,
  14000. max: max
  14001. };
  14002. };
  14003. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14004. if (maxCapacity === void 0) { maxCapacity = 64; }
  14005. if (maxDepth === void 0) { maxDepth = 2; }
  14006. if (!this._selectionOctree) {
  14007. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14008. }
  14009. var worldExtends = this.getWorldExtends();
  14010. // Update octree
  14011. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14012. return this._selectionOctree;
  14013. };
  14014. // Picking
  14015. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14016. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14017. var engine = this._engine;
  14018. if (!camera) {
  14019. if (!this.activeCamera)
  14020. throw new Error("Active camera not set");
  14021. camera = this.activeCamera;
  14022. }
  14023. var cameraViewport = camera.viewport;
  14024. var viewport = cameraViewport.toGlobal(engine);
  14025. // Moving coordinates to local viewport world
  14026. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14027. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14028. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14029. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14030. };
  14031. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14032. var engine = this._engine;
  14033. if (!camera) {
  14034. if (!this.activeCamera)
  14035. throw new Error("Active camera not set");
  14036. camera = this.activeCamera;
  14037. }
  14038. var cameraViewport = camera.viewport;
  14039. var viewport = cameraViewport.toGlobal(engine);
  14040. var identity = BABYLON.Matrix.Identity();
  14041. // Moving coordinates to local viewport world
  14042. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14043. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14044. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14045. };
  14046. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14047. var pickingInfo = null;
  14048. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14049. var mesh = this.meshes[meshIndex];
  14050. if (predicate) {
  14051. if (!predicate(mesh)) {
  14052. continue;
  14053. }
  14054. }
  14055. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14056. continue;
  14057. }
  14058. var world = mesh.getWorldMatrix();
  14059. var ray = rayFunction(world);
  14060. var result = mesh.intersects(ray, fastCheck);
  14061. if (!result || !result.hit)
  14062. continue;
  14063. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14064. continue;
  14065. pickingInfo = result;
  14066. if (fastCheck) {
  14067. break;
  14068. }
  14069. }
  14070. return pickingInfo || new BABYLON.PickingInfo();
  14071. };
  14072. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14073. var pickingInfo = null;
  14074. camera = camera || this.activeCamera;
  14075. if (this.spriteManagers.length > 0) {
  14076. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14077. var spriteManager = this.spriteManagers[spriteIndex];
  14078. if (!spriteManager.isPickable) {
  14079. continue;
  14080. }
  14081. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14082. if (!result || !result.hit)
  14083. continue;
  14084. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14085. continue;
  14086. pickingInfo = result;
  14087. if (fastCheck) {
  14088. break;
  14089. }
  14090. }
  14091. }
  14092. return pickingInfo || new BABYLON.PickingInfo();
  14093. };
  14094. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14095. var _this = this;
  14096. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14097. /// <param name="x">X position on screen</param>
  14098. /// <param name="y">Y position on screen</param>
  14099. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14100. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14101. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14102. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14103. };
  14104. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14105. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14106. /// <param name="x">X position on screen</param>
  14107. /// <param name="y">Y position on screen</param>
  14108. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  14109. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14110. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14111. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14112. };
  14113. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14114. var _this = this;
  14115. return this._internalPick(function (world) {
  14116. if (!_this._pickWithRayInverseMatrix) {
  14117. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14118. }
  14119. world.invertToRef(_this._pickWithRayInverseMatrix);
  14120. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14121. }, predicate, fastCheck);
  14122. };
  14123. Scene.prototype.setPointerOverMesh = function (mesh) {
  14124. if (this._pointerOverMesh === mesh) {
  14125. return;
  14126. }
  14127. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14128. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14129. }
  14130. this._pointerOverMesh = mesh;
  14131. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14132. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14133. }
  14134. };
  14135. Scene.prototype.getPointerOverMesh = function () {
  14136. return this._pointerOverMesh;
  14137. };
  14138. Scene.prototype.setPointerOverSprite = function (sprite) {
  14139. if (this._pointerOverSprite === sprite) {
  14140. return;
  14141. }
  14142. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14143. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14144. }
  14145. this._pointerOverSprite = sprite;
  14146. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14147. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14148. }
  14149. };
  14150. Scene.prototype.getPointerOverSprite = function () {
  14151. return this._pointerOverSprite;
  14152. };
  14153. // Physics
  14154. Scene.prototype.getPhysicsEngine = function () {
  14155. return this._physicsEngine;
  14156. };
  14157. /**
  14158. * Enables physics to the current scene
  14159. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14160. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14161. * @return {boolean} was the physics engine initialized
  14162. */
  14163. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14164. if (this._physicsEngine) {
  14165. return true;
  14166. }
  14167. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14168. if (!this._physicsEngine.isSupported()) {
  14169. this._physicsEngine = null;
  14170. return false;
  14171. }
  14172. this._physicsEngine._initialize(gravity);
  14173. return true;
  14174. };
  14175. Scene.prototype.disablePhysicsEngine = function () {
  14176. if (!this._physicsEngine) {
  14177. return;
  14178. }
  14179. this._physicsEngine.dispose();
  14180. this._physicsEngine = undefined;
  14181. };
  14182. Scene.prototype.isPhysicsEnabled = function () {
  14183. return this._physicsEngine !== undefined;
  14184. };
  14185. /**
  14186. * Sets the gravity of the physics engine (and NOT of the scene)
  14187. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14188. */
  14189. Scene.prototype.setGravity = function (gravity) {
  14190. if (!this._physicsEngine) {
  14191. return;
  14192. }
  14193. this._physicsEngine._setGravity(gravity);
  14194. };
  14195. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14196. if (parts.parts) {
  14197. options = parts;
  14198. parts = parts.parts;
  14199. }
  14200. if (!this._physicsEngine) {
  14201. return null;
  14202. }
  14203. for (var index = 0; index < parts.length; index++) {
  14204. var mesh = parts[index].mesh;
  14205. mesh._physicImpostor = parts[index].impostor;
  14206. mesh._physicsMass = options.mass / parts.length;
  14207. mesh._physicsFriction = options.friction;
  14208. mesh._physicRestitution = options.restitution;
  14209. }
  14210. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14211. };
  14212. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14213. for (var index = 0; index < compound.parts.length; index++) {
  14214. var mesh = compound.parts[index].mesh;
  14215. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14216. this._physicsEngine._unregisterMesh(mesh);
  14217. }
  14218. };
  14219. // Misc.
  14220. Scene.prototype.createDefaultCameraOrLight = function () {
  14221. // Light
  14222. if (this.lights.length === 0) {
  14223. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14224. }
  14225. // Camera
  14226. if (!this.activeCamera) {
  14227. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14228. // Compute position
  14229. var worldExtends = this.getWorldExtends();
  14230. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14231. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14232. camera.setTarget(worldCenter);
  14233. this.activeCamera = camera;
  14234. }
  14235. };
  14236. // Tags
  14237. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14238. if (tagsQuery === undefined) {
  14239. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14240. return list;
  14241. }
  14242. var listByTags = [];
  14243. forEach = forEach || (function (item) { return; });
  14244. for (var i in list) {
  14245. var item = list[i];
  14246. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14247. listByTags.push(item);
  14248. forEach(item);
  14249. }
  14250. }
  14251. return listByTags;
  14252. };
  14253. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14254. return this._getByTags(this.meshes, tagsQuery, forEach);
  14255. };
  14256. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14257. return this._getByTags(this.cameras, tagsQuery, forEach);
  14258. };
  14259. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14260. return this._getByTags(this.lights, tagsQuery, forEach);
  14261. };
  14262. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14263. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14264. };
  14265. // Statics
  14266. Scene._FOGMODE_NONE = 0;
  14267. Scene._FOGMODE_EXP = 1;
  14268. Scene._FOGMODE_EXP2 = 2;
  14269. Scene._FOGMODE_LINEAR = 3;
  14270. Scene.MinDeltaTime = 1.0;
  14271. Scene.MaxDeltaTime = 1000.0;
  14272. return Scene;
  14273. })();
  14274. BABYLON.Scene = Scene;
  14275. })(BABYLON || (BABYLON = {}));
  14276. var BABYLON;
  14277. (function (BABYLON) {
  14278. var VertexBuffer = (function () {
  14279. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14280. if (engine instanceof BABYLON.Mesh) {
  14281. this._engine = engine.getScene().getEngine();
  14282. }
  14283. else {
  14284. this._engine = engine;
  14285. }
  14286. this._updatable = updatable;
  14287. this._data = data;
  14288. if (!postponeInternalCreation) {
  14289. this.create();
  14290. }
  14291. this._kind = kind;
  14292. if (stride) {
  14293. this._strideSize = stride;
  14294. return;
  14295. }
  14296. // Deduce stride from kind
  14297. switch (kind) {
  14298. case VertexBuffer.PositionKind:
  14299. this._strideSize = 3;
  14300. break;
  14301. case VertexBuffer.NormalKind:
  14302. this._strideSize = 3;
  14303. break;
  14304. case VertexBuffer.UVKind:
  14305. case VertexBuffer.UV2Kind:
  14306. case VertexBuffer.UV3Kind:
  14307. case VertexBuffer.UV4Kind:
  14308. case VertexBuffer.UV5Kind:
  14309. case VertexBuffer.UV6Kind:
  14310. this._strideSize = 2;
  14311. break;
  14312. case VertexBuffer.ColorKind:
  14313. this._strideSize = 4;
  14314. break;
  14315. case VertexBuffer.MatricesIndicesKind:
  14316. case VertexBuffer.MatricesIndicesExtraKind:
  14317. this._strideSize = 4;
  14318. break;
  14319. case VertexBuffer.MatricesWeightsKind:
  14320. case VertexBuffer.MatricesWeightsExtraKind:
  14321. this._strideSize = 4;
  14322. break;
  14323. }
  14324. }
  14325. // Properties
  14326. VertexBuffer.prototype.isUpdatable = function () {
  14327. return this._updatable;
  14328. };
  14329. VertexBuffer.prototype.getData = function () {
  14330. return this._data;
  14331. };
  14332. VertexBuffer.prototype.getBuffer = function () {
  14333. return this._buffer;
  14334. };
  14335. VertexBuffer.prototype.getStrideSize = function () {
  14336. return this._strideSize;
  14337. };
  14338. // Methods
  14339. VertexBuffer.prototype.create = function (data) {
  14340. if (!data && this._buffer) {
  14341. return; // nothing to do
  14342. }
  14343. data = data || this._data;
  14344. if (!this._buffer) {
  14345. if (this._updatable) {
  14346. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14347. }
  14348. else {
  14349. this._buffer = this._engine.createVertexBuffer(data);
  14350. }
  14351. }
  14352. if (this._updatable) {
  14353. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14354. this._data = data;
  14355. }
  14356. };
  14357. VertexBuffer.prototype.update = function (data) {
  14358. this.create(data);
  14359. };
  14360. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14361. if (!this._buffer) {
  14362. return;
  14363. }
  14364. if (this._updatable) {
  14365. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14366. this._data = null;
  14367. }
  14368. };
  14369. VertexBuffer.prototype.dispose = function () {
  14370. if (!this._buffer) {
  14371. return;
  14372. }
  14373. if (this._engine._releaseBuffer(this._buffer)) {
  14374. this._buffer = null;
  14375. }
  14376. };
  14377. Object.defineProperty(VertexBuffer, "PositionKind", {
  14378. get: function () {
  14379. return VertexBuffer._PositionKind;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(VertexBuffer, "NormalKind", {
  14385. get: function () {
  14386. return VertexBuffer._NormalKind;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. Object.defineProperty(VertexBuffer, "UVKind", {
  14392. get: function () {
  14393. return VertexBuffer._UVKind;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14399. get: function () {
  14400. return VertexBuffer._UV2Kind;
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14406. get: function () {
  14407. return VertexBuffer._UV3Kind;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14413. get: function () {
  14414. return VertexBuffer._UV4Kind;
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14420. get: function () {
  14421. return VertexBuffer._UV5Kind;
  14422. },
  14423. enumerable: true,
  14424. configurable: true
  14425. });
  14426. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14427. get: function () {
  14428. return VertexBuffer._UV6Kind;
  14429. },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. Object.defineProperty(VertexBuffer, "ColorKind", {
  14434. get: function () {
  14435. return VertexBuffer._ColorKind;
  14436. },
  14437. enumerable: true,
  14438. configurable: true
  14439. });
  14440. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14441. get: function () {
  14442. return VertexBuffer._MatricesIndicesKind;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14448. get: function () {
  14449. return VertexBuffer._MatricesWeightsKind;
  14450. },
  14451. enumerable: true,
  14452. configurable: true
  14453. });
  14454. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14455. get: function () {
  14456. return VertexBuffer._MatricesIndicesExtraKind;
  14457. },
  14458. enumerable: true,
  14459. configurable: true
  14460. });
  14461. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14462. get: function () {
  14463. return VertexBuffer._MatricesWeightsExtraKind;
  14464. },
  14465. enumerable: true,
  14466. configurable: true
  14467. });
  14468. // Enums
  14469. VertexBuffer._PositionKind = "position";
  14470. VertexBuffer._NormalKind = "normal";
  14471. VertexBuffer._UVKind = "uv";
  14472. VertexBuffer._UV2Kind = "uv2";
  14473. VertexBuffer._UV3Kind = "uv3";
  14474. VertexBuffer._UV4Kind = "uv4";
  14475. VertexBuffer._UV5Kind = "uv5";
  14476. VertexBuffer._UV6Kind = "uv6";
  14477. VertexBuffer._ColorKind = "color";
  14478. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14479. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14480. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14481. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14482. return VertexBuffer;
  14483. })();
  14484. BABYLON.VertexBuffer = VertexBuffer;
  14485. })(BABYLON || (BABYLON = {}));
  14486. var BABYLON;
  14487. (function (BABYLON) {
  14488. /**
  14489. * Creates an instance based on a source mesh.
  14490. */
  14491. var InstancedMesh = (function (_super) {
  14492. __extends(InstancedMesh, _super);
  14493. function InstancedMesh(name, source) {
  14494. _super.call(this, name, source.getScene());
  14495. source.instances.push(this);
  14496. this._sourceMesh = source;
  14497. this.position.copyFrom(source.position);
  14498. this.rotation.copyFrom(source.rotation);
  14499. this.scaling.copyFrom(source.scaling);
  14500. if (source.rotationQuaternion) {
  14501. this.rotationQuaternion = source.rotationQuaternion.clone();
  14502. }
  14503. this.infiniteDistance = source.infiniteDistance;
  14504. this.setPivotMatrix(source.getPivotMatrix());
  14505. this.refreshBoundingInfo();
  14506. this._syncSubMeshes();
  14507. }
  14508. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14509. // Methods
  14510. get: function () {
  14511. return this._sourceMesh.receiveShadows;
  14512. },
  14513. enumerable: true,
  14514. configurable: true
  14515. });
  14516. Object.defineProperty(InstancedMesh.prototype, "material", {
  14517. get: function () {
  14518. return this._sourceMesh.material;
  14519. },
  14520. enumerable: true,
  14521. configurable: true
  14522. });
  14523. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14524. get: function () {
  14525. return this._sourceMesh.visibility;
  14526. },
  14527. enumerable: true,
  14528. configurable: true
  14529. });
  14530. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14531. get: function () {
  14532. return this._sourceMesh.skeleton;
  14533. },
  14534. enumerable: true,
  14535. configurable: true
  14536. });
  14537. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14538. get: function () {
  14539. return this._sourceMesh.renderingGroupId;
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. InstancedMesh.prototype.getTotalVertices = function () {
  14545. return this._sourceMesh.getTotalVertices();
  14546. };
  14547. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14548. get: function () {
  14549. return this._sourceMesh;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14555. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14556. };
  14557. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14558. return this._sourceMesh.isVerticesDataPresent(kind);
  14559. };
  14560. InstancedMesh.prototype.getIndices = function () {
  14561. return this._sourceMesh.getIndices();
  14562. };
  14563. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14564. get: function () {
  14565. return this._sourceMesh._positions;
  14566. },
  14567. enumerable: true,
  14568. configurable: true
  14569. });
  14570. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14571. var meshBB = this._sourceMesh.getBoundingInfo();
  14572. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14573. this._updateBoundingInfo();
  14574. };
  14575. InstancedMesh.prototype._preActivate = function () {
  14576. if (this._currentLOD) {
  14577. this._currentLOD._preActivate();
  14578. }
  14579. };
  14580. InstancedMesh.prototype._activate = function (renderId) {
  14581. if (this._currentLOD) {
  14582. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14583. }
  14584. };
  14585. InstancedMesh.prototype.getLOD = function (camera) {
  14586. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14587. if (this._currentLOD === this.sourceMesh) {
  14588. return this;
  14589. }
  14590. return this._currentLOD;
  14591. };
  14592. InstancedMesh.prototype._syncSubMeshes = function () {
  14593. this.releaseSubMeshes();
  14594. if (this._sourceMesh.subMeshes) {
  14595. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14596. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14597. }
  14598. }
  14599. };
  14600. InstancedMesh.prototype._generatePointsArray = function () {
  14601. return this._sourceMesh._generatePointsArray();
  14602. };
  14603. // Clone
  14604. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14605. var result = this._sourceMesh.createInstance(name);
  14606. // Deep copy
  14607. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14608. // Bounding info
  14609. this.refreshBoundingInfo();
  14610. // Parent
  14611. if (newParent) {
  14612. result.parent = newParent;
  14613. }
  14614. if (!doNotCloneChildren) {
  14615. // Children
  14616. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14617. var mesh = this.getScene().meshes[index];
  14618. if (mesh.parent === this) {
  14619. mesh.clone(mesh.name, result);
  14620. }
  14621. }
  14622. }
  14623. result.computeWorldMatrix(true);
  14624. return result;
  14625. };
  14626. // Dispoe
  14627. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14628. // Remove from mesh
  14629. var index = this._sourceMesh.instances.indexOf(this);
  14630. this._sourceMesh.instances.splice(index, 1);
  14631. _super.prototype.dispose.call(this, doNotRecurse);
  14632. };
  14633. return InstancedMesh;
  14634. })(BABYLON.AbstractMesh);
  14635. BABYLON.InstancedMesh = InstancedMesh;
  14636. })(BABYLON || (BABYLON = {}));
  14637. var BABYLON;
  14638. (function (BABYLON) {
  14639. var _InstancesBatch = (function () {
  14640. function _InstancesBatch() {
  14641. this.mustReturn = false;
  14642. this.visibleInstances = new Array();
  14643. this.renderSelf = new Array();
  14644. }
  14645. return _InstancesBatch;
  14646. })();
  14647. BABYLON._InstancesBatch = _InstancesBatch;
  14648. var Mesh = (function (_super) {
  14649. __extends(Mesh, _super);
  14650. /**
  14651. * @constructor
  14652. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14653. * @param {Scene} scene - The scene to add this mesh to.
  14654. * @param {Node} parent - The parent of this mesh, if it has one
  14655. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14656. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14657. * When false, achieved by calling a clone(), also passing False.
  14658. * This will make creation of children, recursive.
  14659. */
  14660. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14661. if (parent === void 0) { parent = null; }
  14662. _super.call(this, name, scene);
  14663. // Members
  14664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14665. this.instances = new Array();
  14666. this._LODLevels = new Array();
  14667. this._onBeforeRenderCallbacks = new Array();
  14668. this._onAfterRenderCallbacks = new Array();
  14669. this._visibleInstances = {};
  14670. this._renderIdForInstances = new Array();
  14671. this._batchCache = new _InstancesBatch();
  14672. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14673. this._sideOrientation = Mesh._DEFAULTSIDE;
  14674. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14675. if (source) {
  14676. // Geometry
  14677. if (source._geometry) {
  14678. source._geometry.applyToMesh(this);
  14679. }
  14680. // Deep copy
  14681. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14682. this.id = name + "." + source.id;
  14683. // Material
  14684. this.material = source.material;
  14685. var index;
  14686. if (!doNotCloneChildren) {
  14687. // Children
  14688. for (index = 0; index < scene.meshes.length; index++) {
  14689. var mesh = scene.meshes[index];
  14690. if (mesh.parent === source) {
  14691. // doNotCloneChildren is always going to be False
  14692. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14693. }
  14694. }
  14695. }
  14696. // Particles
  14697. for (index = 0; index < scene.particleSystems.length; index++) {
  14698. var system = scene.particleSystems[index];
  14699. if (system.emitter === source) {
  14700. system.clone(system.name, this);
  14701. }
  14702. }
  14703. this.computeWorldMatrix(true);
  14704. }
  14705. // Parent
  14706. if (parent !== null) {
  14707. this.parent = parent;
  14708. }
  14709. }
  14710. Object.defineProperty(Mesh, "FRONTSIDE", {
  14711. get: function () {
  14712. return Mesh._FRONTSIDE;
  14713. },
  14714. enumerable: true,
  14715. configurable: true
  14716. });
  14717. Object.defineProperty(Mesh, "BACKSIDE", {
  14718. get: function () {
  14719. return Mesh._BACKSIDE;
  14720. },
  14721. enumerable: true,
  14722. configurable: true
  14723. });
  14724. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14725. get: function () {
  14726. return Mesh._DOUBLESIDE;
  14727. },
  14728. enumerable: true,
  14729. configurable: true
  14730. });
  14731. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14732. get: function () {
  14733. return Mesh._DEFAULTSIDE;
  14734. },
  14735. enumerable: true,
  14736. configurable: true
  14737. });
  14738. Object.defineProperty(Mesh, "NO_CAP", {
  14739. get: function () {
  14740. return Mesh._NO_CAP;
  14741. },
  14742. enumerable: true,
  14743. configurable: true
  14744. });
  14745. Object.defineProperty(Mesh, "CAP_START", {
  14746. get: function () {
  14747. return Mesh._CAP_START;
  14748. },
  14749. enumerable: true,
  14750. configurable: true
  14751. });
  14752. Object.defineProperty(Mesh, "CAP_END", {
  14753. get: function () {
  14754. return Mesh._CAP_END;
  14755. },
  14756. enumerable: true,
  14757. configurable: true
  14758. });
  14759. Object.defineProperty(Mesh, "CAP_ALL", {
  14760. get: function () {
  14761. return Mesh._CAP_ALL;
  14762. },
  14763. enumerable: true,
  14764. configurable: true
  14765. });
  14766. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14767. // Methods
  14768. get: function () {
  14769. return this._LODLevels.length > 0;
  14770. },
  14771. enumerable: true,
  14772. configurable: true
  14773. });
  14774. Mesh.prototype._sortLODLevels = function () {
  14775. this._LODLevels.sort(function (a, b) {
  14776. if (a.distance < b.distance) {
  14777. return 1;
  14778. }
  14779. if (a.distance > b.distance) {
  14780. return -1;
  14781. }
  14782. return 0;
  14783. });
  14784. };
  14785. /**
  14786. * Add a mesh as LOD level triggered at the given distance.
  14787. * @param {number} distance - the distance from the center of the object to show this level
  14788. * @param {Mesh} mesh - the mesh to be added as LOD level
  14789. * @return {Mesh} this mesh (for chaining)
  14790. */
  14791. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14792. if (mesh && mesh._masterMesh) {
  14793. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14794. return this;
  14795. }
  14796. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14797. this._LODLevels.push(level);
  14798. if (mesh) {
  14799. mesh._masterMesh = this;
  14800. }
  14801. this._sortLODLevels();
  14802. return this;
  14803. };
  14804. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14805. for (var index = 0; index < this._LODLevels.length; index++) {
  14806. var level = this._LODLevels[index];
  14807. if (level.distance === distance) {
  14808. return level.mesh;
  14809. }
  14810. }
  14811. return null;
  14812. };
  14813. /**
  14814. * Remove a mesh from the LOD array
  14815. * @param {Mesh} mesh - the mesh to be removed.
  14816. * @return {Mesh} this mesh (for chaining)
  14817. */
  14818. Mesh.prototype.removeLODLevel = function (mesh) {
  14819. for (var index = 0; index < this._LODLevels.length; index++) {
  14820. if (this._LODLevels[index].mesh === mesh) {
  14821. this._LODLevels.splice(index, 1);
  14822. if (mesh) {
  14823. mesh._masterMesh = null;
  14824. }
  14825. }
  14826. }
  14827. this._sortLODLevels();
  14828. return this;
  14829. };
  14830. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14831. if (!this._LODLevels || this._LODLevels.length === 0) {
  14832. return this;
  14833. }
  14834. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14835. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14836. if (this.onLODLevelSelection) {
  14837. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14838. }
  14839. return this;
  14840. }
  14841. for (var index = 0; index < this._LODLevels.length; index++) {
  14842. var level = this._LODLevels[index];
  14843. if (level.distance < distanceToCamera) {
  14844. if (level.mesh) {
  14845. level.mesh._preActivate();
  14846. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14847. }
  14848. if (this.onLODLevelSelection) {
  14849. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14850. }
  14851. return level.mesh;
  14852. }
  14853. }
  14854. if (this.onLODLevelSelection) {
  14855. this.onLODLevelSelection(distanceToCamera, this, this);
  14856. }
  14857. return this;
  14858. };
  14859. Object.defineProperty(Mesh.prototype, "geometry", {
  14860. get: function () {
  14861. return this._geometry;
  14862. },
  14863. enumerable: true,
  14864. configurable: true
  14865. });
  14866. Mesh.prototype.getTotalVertices = function () {
  14867. if (!this._geometry) {
  14868. return 0;
  14869. }
  14870. return this._geometry.getTotalVertices();
  14871. };
  14872. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14873. if (!this._geometry) {
  14874. return null;
  14875. }
  14876. return this._geometry.getVerticesData(kind, copyWhenShared);
  14877. };
  14878. Mesh.prototype.getVertexBuffer = function (kind) {
  14879. if (!this._geometry) {
  14880. return undefined;
  14881. }
  14882. return this._geometry.getVertexBuffer(kind);
  14883. };
  14884. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14885. if (!this._geometry) {
  14886. if (this._delayInfo) {
  14887. return this._delayInfo.indexOf(kind) !== -1;
  14888. }
  14889. return false;
  14890. }
  14891. return this._geometry.isVerticesDataPresent(kind);
  14892. };
  14893. Mesh.prototype.getVerticesDataKinds = function () {
  14894. if (!this._geometry) {
  14895. var result = [];
  14896. if (this._delayInfo) {
  14897. for (var kind in this._delayInfo) {
  14898. result.push(kind);
  14899. }
  14900. }
  14901. return result;
  14902. }
  14903. return this._geometry.getVerticesDataKinds();
  14904. };
  14905. Mesh.prototype.getTotalIndices = function () {
  14906. if (!this._geometry) {
  14907. return 0;
  14908. }
  14909. return this._geometry.getTotalIndices();
  14910. };
  14911. Mesh.prototype.getIndices = function (copyWhenShared) {
  14912. if (!this._geometry) {
  14913. return [];
  14914. }
  14915. return this._geometry.getIndices(copyWhenShared);
  14916. };
  14917. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14918. get: function () {
  14919. return this._masterMesh !== null && this._masterMesh !== undefined;
  14920. },
  14921. enumerable: true,
  14922. configurable: true
  14923. });
  14924. Mesh.prototype.isReady = function () {
  14925. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14926. return false;
  14927. }
  14928. return _super.prototype.isReady.call(this);
  14929. };
  14930. Mesh.prototype.isDisposed = function () {
  14931. return this._isDisposed;
  14932. };
  14933. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14934. get: function () {
  14935. return this._sideOrientation;
  14936. },
  14937. set: function (sideO) {
  14938. this._sideOrientation = sideO;
  14939. },
  14940. enumerable: true,
  14941. configurable: true
  14942. });
  14943. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14944. get: function () {
  14945. return this._areNormalsFrozen;
  14946. },
  14947. enumerable: true,
  14948. configurable: true
  14949. });
  14950. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14951. Mesh.prototype.freezeNormals = function () {
  14952. this._areNormalsFrozen = true;
  14953. };
  14954. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14955. Mesh.prototype.unfreezeNormals = function () {
  14956. this._areNormalsFrozen = false;
  14957. };
  14958. // Methods
  14959. Mesh.prototype._preActivate = function () {
  14960. var sceneRenderId = this.getScene().getRenderId();
  14961. if (this._preActivateId === sceneRenderId) {
  14962. return;
  14963. }
  14964. this._preActivateId = sceneRenderId;
  14965. this._visibleInstances = null;
  14966. };
  14967. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14968. if (!this._visibleInstances) {
  14969. this._visibleInstances = {};
  14970. this._visibleInstances.defaultRenderId = renderId;
  14971. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14972. }
  14973. if (!this._visibleInstances[renderId]) {
  14974. this._visibleInstances[renderId] = new Array();
  14975. }
  14976. this._visibleInstances[renderId].push(instance);
  14977. };
  14978. Mesh.prototype.refreshBoundingInfo = function () {
  14979. if (this._boundingInfo.isLocked) {
  14980. return;
  14981. }
  14982. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14983. if (data) {
  14984. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14985. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14986. }
  14987. if (this.subMeshes) {
  14988. for (var index = 0; index < this.subMeshes.length; index++) {
  14989. this.subMeshes[index].refreshBoundingInfo();
  14990. }
  14991. }
  14992. this._updateBoundingInfo();
  14993. };
  14994. Mesh.prototype._createGlobalSubMesh = function () {
  14995. var totalVertices = this.getTotalVertices();
  14996. if (!totalVertices || !this.getIndices()) {
  14997. return null;
  14998. }
  14999. this.releaseSubMeshes();
  15000. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15001. };
  15002. Mesh.prototype.subdivide = function (count) {
  15003. if (count < 1) {
  15004. return;
  15005. }
  15006. var totalIndices = this.getTotalIndices();
  15007. var subdivisionSize = (totalIndices / count) | 0;
  15008. var offset = 0;
  15009. // Ensure that subdivisionSize is a multiple of 3
  15010. while (subdivisionSize % 3 !== 0) {
  15011. subdivisionSize++;
  15012. }
  15013. this.releaseSubMeshes();
  15014. for (var index = 0; index < count; index++) {
  15015. if (offset >= totalIndices) {
  15016. break;
  15017. }
  15018. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15019. offset += subdivisionSize;
  15020. }
  15021. this.synchronizeInstances();
  15022. };
  15023. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15024. if (!this._geometry) {
  15025. var vertexData = new BABYLON.VertexData();
  15026. vertexData.set(data, kind);
  15027. var scene = this.getScene();
  15028. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15029. }
  15030. else {
  15031. this._geometry.setVerticesData(kind, data, updatable, stride);
  15032. }
  15033. };
  15034. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15035. if (!this._geometry) {
  15036. return;
  15037. }
  15038. if (!makeItUnique) {
  15039. this._geometry.updateVerticesData(kind, data, updateExtends);
  15040. }
  15041. else {
  15042. this.makeGeometryUnique();
  15043. this.updateVerticesData(kind, data, updateExtends, false);
  15044. }
  15045. };
  15046. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15047. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15048. if (!this._geometry) {
  15049. return;
  15050. }
  15051. if (!makeItUnique) {
  15052. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15053. }
  15054. else {
  15055. this.makeGeometryUnique();
  15056. this.updateVerticesDataDirectly(kind, data, offset, false);
  15057. }
  15058. };
  15059. // Mesh positions update function :
  15060. // updates the mesh positions according to the positionFunction returned values.
  15061. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15062. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15063. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15064. if (computeNormals === void 0) { computeNormals = true; }
  15065. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15066. positionFunction(positions);
  15067. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15068. if (computeNormals) {
  15069. var indices = this.getIndices();
  15070. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15071. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15072. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15073. }
  15074. };
  15075. Mesh.prototype.makeGeometryUnique = function () {
  15076. if (!this._geometry) {
  15077. return;
  15078. }
  15079. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15080. geometry.applyToMesh(this);
  15081. };
  15082. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15083. if (!this._geometry) {
  15084. var vertexData = new BABYLON.VertexData();
  15085. vertexData.indices = indices;
  15086. var scene = this.getScene();
  15087. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15088. }
  15089. else {
  15090. this._geometry.setIndices(indices, totalVertices);
  15091. }
  15092. };
  15093. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15094. var engine = this.getScene().getEngine();
  15095. // Wireframe
  15096. var indexToBind;
  15097. if (this._unIndexed) {
  15098. indexToBind = null;
  15099. }
  15100. else {
  15101. switch (fillMode) {
  15102. case BABYLON.Material.PointFillMode:
  15103. indexToBind = null;
  15104. break;
  15105. case BABYLON.Material.WireFrameFillMode:
  15106. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15107. break;
  15108. default:
  15109. case BABYLON.Material.TriangleFillMode:
  15110. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15111. break;
  15112. }
  15113. }
  15114. // VBOs
  15115. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15116. };
  15117. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15118. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15119. return;
  15120. }
  15121. if (this.onBeforeDraw) {
  15122. this.onBeforeDraw();
  15123. }
  15124. var engine = this.getScene().getEngine();
  15125. // Draw order
  15126. switch (fillMode) {
  15127. case BABYLON.Material.PointFillMode:
  15128. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15129. break;
  15130. case BABYLON.Material.WireFrameFillMode:
  15131. if (this._unIndexed) {
  15132. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15133. }
  15134. else {
  15135. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15136. }
  15137. break;
  15138. default:
  15139. if (this._unIndexed) {
  15140. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15141. }
  15142. else {
  15143. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15144. }
  15145. }
  15146. };
  15147. Mesh.prototype.registerBeforeRender = function (func) {
  15148. this._onBeforeRenderCallbacks.push(func);
  15149. };
  15150. Mesh.prototype.unregisterBeforeRender = function (func) {
  15151. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15152. if (index > -1) {
  15153. this._onBeforeRenderCallbacks.splice(index, 1);
  15154. }
  15155. };
  15156. Mesh.prototype.registerAfterRender = function (func) {
  15157. this._onAfterRenderCallbacks.push(func);
  15158. };
  15159. Mesh.prototype.unregisterAfterRender = function (func) {
  15160. var index = this._onAfterRenderCallbacks.indexOf(func);
  15161. if (index > -1) {
  15162. this._onAfterRenderCallbacks.splice(index, 1);
  15163. }
  15164. };
  15165. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15166. var scene = this.getScene();
  15167. this._batchCache.mustReturn = false;
  15168. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15169. this._batchCache.visibleInstances[subMeshId] = null;
  15170. if (this._visibleInstances) {
  15171. var currentRenderId = scene.getRenderId();
  15172. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15173. var selfRenderId = this._renderId;
  15174. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15175. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15176. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15177. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15178. }
  15179. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15180. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15181. this._batchCache.mustReturn = true;
  15182. return this._batchCache;
  15183. }
  15184. if (currentRenderId !== selfRenderId) {
  15185. this._batchCache.renderSelf[subMeshId] = false;
  15186. }
  15187. }
  15188. this._renderIdForInstances[subMeshId] = currentRenderId;
  15189. }
  15190. return this._batchCache;
  15191. };
  15192. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15193. var visibleInstances = batch.visibleInstances[subMesh._id];
  15194. var matricesCount = visibleInstances.length + 1;
  15195. var bufferSize = matricesCount * 16 * 4;
  15196. while (this._instancesBufferSize < bufferSize) {
  15197. this._instancesBufferSize *= 2;
  15198. }
  15199. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15200. if (this._worldMatricesInstancesBuffer) {
  15201. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15202. }
  15203. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15204. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15205. }
  15206. var offset = 0;
  15207. var instancesCount = 0;
  15208. var world = this.getWorldMatrix();
  15209. if (batch.renderSelf[subMesh._id]) {
  15210. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15211. offset += 16;
  15212. instancesCount++;
  15213. }
  15214. if (visibleInstances) {
  15215. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15216. var instance = visibleInstances[instanceIndex];
  15217. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15218. offset += 16;
  15219. instancesCount++;
  15220. }
  15221. }
  15222. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15223. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15224. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15225. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15226. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15227. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15228. this._draw(subMesh, fillMode, instancesCount);
  15229. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15230. };
  15231. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15232. var scene = this.getScene();
  15233. var engine = scene.getEngine();
  15234. if (hardwareInstancedRendering) {
  15235. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15236. }
  15237. else {
  15238. if (batch.renderSelf[subMesh._id]) {
  15239. // Draw
  15240. if (onBeforeDraw) {
  15241. onBeforeDraw(false, this.getWorldMatrix());
  15242. }
  15243. this._draw(subMesh, fillMode);
  15244. }
  15245. if (batch.visibleInstances[subMesh._id]) {
  15246. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15247. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15248. // World
  15249. var world = instance.getWorldMatrix();
  15250. if (onBeforeDraw) {
  15251. onBeforeDraw(true, world);
  15252. }
  15253. // Draw
  15254. this._draw(subMesh, fillMode);
  15255. }
  15256. }
  15257. }
  15258. };
  15259. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15260. var scene = this.getScene();
  15261. // Managing instances
  15262. var batch = this._getInstancesRenderList(subMesh._id);
  15263. if (batch.mustReturn) {
  15264. return;
  15265. }
  15266. // Checking geometry state
  15267. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15268. return;
  15269. }
  15270. var callbackIndex;
  15271. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15272. this._onBeforeRenderCallbacks[callbackIndex](this);
  15273. }
  15274. var engine = scene.getEngine();
  15275. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15276. // Material
  15277. var effectiveMaterial = subMesh.getMaterial();
  15278. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15279. return;
  15280. }
  15281. // Outline - step 1
  15282. var savedDepthWrite = engine.getDepthWrite();
  15283. if (this.renderOutline) {
  15284. engine.setDepthWrite(false);
  15285. scene.getOutlineRenderer().render(subMesh, batch);
  15286. engine.setDepthWrite(savedDepthWrite);
  15287. }
  15288. effectiveMaterial._preBind();
  15289. var effect = effectiveMaterial.getEffect();
  15290. // Bind
  15291. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15292. this._bind(subMesh, effect, fillMode);
  15293. var world = this.getWorldMatrix();
  15294. effectiveMaterial.bind(world, this);
  15295. // Alpha mode
  15296. if (enableAlphaMode) {
  15297. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15298. }
  15299. // Draw
  15300. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15301. if (isInstance) {
  15302. effectiveMaterial.bindOnlyWorldMatrix(world);
  15303. }
  15304. });
  15305. // Unbind
  15306. effectiveMaterial.unbind();
  15307. // Outline - step 2
  15308. if (this.renderOutline && savedDepthWrite) {
  15309. engine.setDepthWrite(true);
  15310. engine.setColorWrite(false);
  15311. scene.getOutlineRenderer().render(subMesh, batch);
  15312. engine.setColorWrite(true);
  15313. }
  15314. // Overlay
  15315. if (this.renderOverlay) {
  15316. var currentMode = engine.getAlphaMode();
  15317. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15318. scene.getOutlineRenderer().render(subMesh, batch, true);
  15319. engine.setAlphaMode(currentMode);
  15320. }
  15321. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15322. this._onAfterRenderCallbacks[callbackIndex](this);
  15323. }
  15324. };
  15325. Mesh.prototype.getEmittedParticleSystems = function () {
  15326. var results = new Array();
  15327. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15328. var particleSystem = this.getScene().particleSystems[index];
  15329. if (particleSystem.emitter === this) {
  15330. results.push(particleSystem);
  15331. }
  15332. }
  15333. return results;
  15334. };
  15335. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15336. var results = new Array();
  15337. var descendants = this.getDescendants();
  15338. descendants.push(this);
  15339. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15340. var particleSystem = this.getScene().particleSystems[index];
  15341. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15342. results.push(particleSystem);
  15343. }
  15344. }
  15345. return results;
  15346. };
  15347. Mesh.prototype.getChildren = function () {
  15348. var results = [];
  15349. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15350. var mesh = this.getScene().meshes[index];
  15351. if (mesh.parent === this) {
  15352. results.push(mesh);
  15353. }
  15354. }
  15355. return results;
  15356. };
  15357. Mesh.prototype._checkDelayState = function () {
  15358. var _this = this;
  15359. var that = this;
  15360. var scene = this.getScene();
  15361. if (this._geometry) {
  15362. this._geometry.load(scene);
  15363. }
  15364. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15365. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15366. scene._addPendingData(that);
  15367. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15368. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15369. if (data instanceof ArrayBuffer) {
  15370. _this._delayLoadingFunction(data, _this);
  15371. }
  15372. else {
  15373. _this._delayLoadingFunction(JSON.parse(data), _this);
  15374. }
  15375. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15376. scene._removePendingData(_this);
  15377. }, function () { }, scene.database, getBinaryData);
  15378. }
  15379. };
  15380. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15381. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15382. return false;
  15383. }
  15384. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15385. return false;
  15386. }
  15387. this._checkDelayState();
  15388. return true;
  15389. };
  15390. Mesh.prototype.setMaterialByID = function (id) {
  15391. var materials = this.getScene().materials;
  15392. var index;
  15393. for (index = 0; index < materials.length; index++) {
  15394. if (materials[index].id === id) {
  15395. this.material = materials[index];
  15396. return;
  15397. }
  15398. }
  15399. // Multi
  15400. var multiMaterials = this.getScene().multiMaterials;
  15401. for (index = 0; index < multiMaterials.length; index++) {
  15402. if (multiMaterials[index].id === id) {
  15403. this.material = multiMaterials[index];
  15404. return;
  15405. }
  15406. }
  15407. };
  15408. Mesh.prototype.getAnimatables = function () {
  15409. var results = [];
  15410. if (this.material) {
  15411. results.push(this.material);
  15412. }
  15413. if (this.skeleton) {
  15414. results.push(this.skeleton);
  15415. }
  15416. return results;
  15417. };
  15418. // Geometry
  15419. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15420. // Position
  15421. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15422. return;
  15423. }
  15424. this._resetPointsArrayCache();
  15425. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15426. var temp = [];
  15427. var index;
  15428. for (index = 0; index < data.length; index += 3) {
  15429. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15430. }
  15431. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15432. // Normals
  15433. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15434. return;
  15435. }
  15436. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15437. temp = [];
  15438. for (index = 0; index < data.length; index += 3) {
  15439. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15440. }
  15441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15442. // flip faces?
  15443. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15444. this.flipFaces();
  15445. }
  15446. };
  15447. // Will apply current transform to mesh and reset world matrix
  15448. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15449. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15450. this.scaling.copyFromFloats(1, 1, 1);
  15451. this.position.copyFromFloats(0, 0, 0);
  15452. this.rotation.copyFromFloats(0, 0, 0);
  15453. //only if quaternion is already set
  15454. if (this.rotationQuaternion) {
  15455. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15456. }
  15457. this._worldMatrix = BABYLON.Matrix.Identity();
  15458. };
  15459. // Cache
  15460. Mesh.prototype._resetPointsArrayCache = function () {
  15461. this._positions = null;
  15462. };
  15463. Mesh.prototype._generatePointsArray = function () {
  15464. if (this._positions)
  15465. return true;
  15466. this._positions = [];
  15467. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15468. if (!data) {
  15469. return false;
  15470. }
  15471. for (var index = 0; index < data.length; index += 3) {
  15472. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15473. }
  15474. return true;
  15475. };
  15476. // Clone
  15477. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15478. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15479. };
  15480. // Dispose
  15481. Mesh.prototype.dispose = function (doNotRecurse) {
  15482. if (this._geometry) {
  15483. this._geometry.releaseForMesh(this, true);
  15484. }
  15485. // Instances
  15486. if (this._worldMatricesInstancesBuffer) {
  15487. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15488. this._worldMatricesInstancesBuffer = null;
  15489. }
  15490. while (this.instances.length) {
  15491. this.instances[0].dispose();
  15492. }
  15493. _super.prototype.dispose.call(this, doNotRecurse);
  15494. };
  15495. // Geometric tools
  15496. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15497. var _this = this;
  15498. var scene = this.getScene();
  15499. var onload = function (img) {
  15500. // Getting height map data
  15501. var canvas = document.createElement("canvas");
  15502. var context = canvas.getContext("2d");
  15503. var heightMapWidth = img.width;
  15504. var heightMapHeight = img.height;
  15505. canvas.width = heightMapWidth;
  15506. canvas.height = heightMapHeight;
  15507. context.drawImage(img, 0, 0);
  15508. // Create VertexData from map data
  15509. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15510. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15511. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15512. //execute success callback, if set
  15513. if (onSuccess) {
  15514. onSuccess(_this);
  15515. }
  15516. };
  15517. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15518. };
  15519. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15520. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15521. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15522. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15523. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15524. return;
  15525. }
  15526. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15527. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15528. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15529. var position = BABYLON.Vector3.Zero();
  15530. var normal = BABYLON.Vector3.Zero();
  15531. var uv = BABYLON.Vector2.Zero();
  15532. for (var index = 0; index < positions.length; index += 3) {
  15533. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15534. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15535. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15536. // Compute height
  15537. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15538. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15539. var pos = (u + v * heightMapWidth) * 4;
  15540. var r = buffer[pos] / 255.0;
  15541. var g = buffer[pos + 1] / 255.0;
  15542. var b = buffer[pos + 2] / 255.0;
  15543. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15544. normal.normalize();
  15545. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15546. position = position.add(normal);
  15547. position.toArray(positions, index);
  15548. }
  15549. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15550. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15551. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15552. };
  15553. Mesh.prototype.convertToFlatShadedMesh = function () {
  15554. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15555. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15556. var kinds = this.getVerticesDataKinds();
  15557. var vbs = [];
  15558. var data = [];
  15559. var newdata = [];
  15560. var updatableNormals = false;
  15561. var kindIndex;
  15562. var kind;
  15563. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15564. kind = kinds[kindIndex];
  15565. var vertexBuffer = this.getVertexBuffer(kind);
  15566. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15567. updatableNormals = vertexBuffer.isUpdatable();
  15568. kinds.splice(kindIndex, 1);
  15569. kindIndex--;
  15570. continue;
  15571. }
  15572. vbs[kind] = vertexBuffer;
  15573. data[kind] = vbs[kind].getData();
  15574. newdata[kind] = [];
  15575. }
  15576. // Save previous submeshes
  15577. var previousSubmeshes = this.subMeshes.slice(0);
  15578. var indices = this.getIndices();
  15579. var totalIndices = this.getTotalIndices();
  15580. // Generating unique vertices per face
  15581. var index;
  15582. for (index = 0; index < totalIndices; index++) {
  15583. var vertexIndex = indices[index];
  15584. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15585. kind = kinds[kindIndex];
  15586. var stride = vbs[kind].getStrideSize();
  15587. for (var offset = 0; offset < stride; offset++) {
  15588. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15589. }
  15590. }
  15591. }
  15592. // Updating faces & normal
  15593. var normals = [];
  15594. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15595. for (index = 0; index < totalIndices; index += 3) {
  15596. indices[index] = index;
  15597. indices[index + 1] = index + 1;
  15598. indices[index + 2] = index + 2;
  15599. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15600. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15601. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15602. var p1p2 = p1.subtract(p2);
  15603. var p3p2 = p3.subtract(p2);
  15604. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15605. // Store same normals for every vertex
  15606. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15607. normals.push(normal.x);
  15608. normals.push(normal.y);
  15609. normals.push(normal.z);
  15610. }
  15611. }
  15612. this.setIndices(indices);
  15613. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15614. // Updating vertex buffers
  15615. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15616. kind = kinds[kindIndex];
  15617. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15618. }
  15619. // Updating submeshes
  15620. this.releaseSubMeshes();
  15621. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15622. var previousOne = previousSubmeshes[submeshIndex];
  15623. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15624. }
  15625. this.synchronizeInstances();
  15626. };
  15627. Mesh.prototype.convertToUnIndexedMesh = function () {
  15628. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15629. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15630. var kinds = this.getVerticesDataKinds();
  15631. var vbs = [];
  15632. var data = [];
  15633. var newdata = [];
  15634. var updatableNormals = false;
  15635. var kindIndex;
  15636. var kind;
  15637. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15638. kind = kinds[kindIndex];
  15639. var vertexBuffer = this.getVertexBuffer(kind);
  15640. vbs[kind] = vertexBuffer;
  15641. data[kind] = vbs[kind].getData();
  15642. newdata[kind] = [];
  15643. }
  15644. // Save previous submeshes
  15645. var previousSubmeshes = this.subMeshes.slice(0);
  15646. var indices = this.getIndices();
  15647. var totalIndices = this.getTotalIndices();
  15648. // Generating unique vertices per face
  15649. var index;
  15650. for (index = 0; index < totalIndices; index++) {
  15651. var vertexIndex = indices[index];
  15652. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15653. kind = kinds[kindIndex];
  15654. var stride = vbs[kind].getStrideSize();
  15655. for (var offset = 0; offset < stride; offset++) {
  15656. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15657. }
  15658. }
  15659. }
  15660. // Updating indices
  15661. for (index = 0; index < totalIndices; index += 3) {
  15662. indices[index] = index;
  15663. indices[index + 1] = index + 1;
  15664. indices[index + 2] = index + 2;
  15665. }
  15666. this.setIndices(indices);
  15667. // Updating vertex buffers
  15668. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15669. kind = kinds[kindIndex];
  15670. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15671. }
  15672. // Updating submeshes
  15673. this.releaseSubMeshes();
  15674. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15675. var previousOne = previousSubmeshes[submeshIndex];
  15676. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15677. }
  15678. this._unIndexed = true;
  15679. this.synchronizeInstances();
  15680. };
  15681. // will inverse faces orientations, and invert normals too if specified
  15682. Mesh.prototype.flipFaces = function (flipNormals) {
  15683. if (flipNormals === void 0) { flipNormals = false; }
  15684. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15685. var i;
  15686. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15687. for (i = 0; i < vertex_data.normals.length; i++) {
  15688. vertex_data.normals[i] *= -1;
  15689. }
  15690. }
  15691. var temp;
  15692. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15693. // reassign indices
  15694. temp = vertex_data.indices[i + 1];
  15695. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15696. vertex_data.indices[i + 2] = temp;
  15697. }
  15698. vertex_data.applyToMesh(this);
  15699. };
  15700. // Instances
  15701. Mesh.prototype.createInstance = function (name) {
  15702. return new BABYLON.InstancedMesh(name, this);
  15703. };
  15704. Mesh.prototype.synchronizeInstances = function () {
  15705. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15706. var instance = this.instances[instanceIndex];
  15707. instance._syncSubMeshes();
  15708. }
  15709. };
  15710. /**
  15711. * Simplify the mesh according to the given array of settings.
  15712. * Function will return immediately and will simplify async.
  15713. * @param settings a collection of simplification settings.
  15714. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15715. * @param type the type of simplification to run.
  15716. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15717. */
  15718. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15719. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15720. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15721. this.getScene().simplificationQueue.addTask({
  15722. settings: settings,
  15723. parallelProcessing: parallelProcessing,
  15724. mesh: this,
  15725. simplificationType: simplificationType,
  15726. successCallback: successCallback
  15727. });
  15728. };
  15729. /**
  15730. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15731. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15732. * This should be used together with the simplification to avoid disappearing triangles.
  15733. * @param successCallback an optional success callback to be called after the optimization finished.
  15734. */
  15735. Mesh.prototype.optimizeIndices = function (successCallback) {
  15736. var _this = this;
  15737. var indices = this.getIndices();
  15738. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15739. var vectorPositions = [];
  15740. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15741. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15742. }
  15743. var dupes = [];
  15744. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15745. var realPos = vectorPositions.length - 1 - iteration;
  15746. var testedPosition = vectorPositions[realPos];
  15747. for (var j = 0; j < realPos; ++j) {
  15748. var againstPosition = vectorPositions[j];
  15749. if (testedPosition.equals(againstPosition)) {
  15750. dupes[realPos] = j;
  15751. break;
  15752. }
  15753. }
  15754. }, function () {
  15755. for (var i = 0; i < indices.length; ++i) {
  15756. indices[i] = dupes[indices[i]] || indices[i];
  15757. }
  15758. //indices are now reordered
  15759. var originalSubMeshes = _this.subMeshes.slice(0);
  15760. _this.setIndices(indices);
  15761. _this.subMeshes = originalSubMeshes;
  15762. if (successCallback) {
  15763. successCallback(_this);
  15764. }
  15765. });
  15766. };
  15767. // Statics
  15768. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15769. var mesh = new Mesh(parsedMesh.name, scene);
  15770. mesh.id = parsedMesh.id;
  15771. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15772. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15773. if (parsedMesh.rotationQuaternion) {
  15774. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15775. }
  15776. else if (parsedMesh.rotation) {
  15777. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15778. }
  15779. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15780. if (parsedMesh.localMatrix) {
  15781. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15782. }
  15783. else if (parsedMesh.pivotMatrix) {
  15784. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15785. }
  15786. mesh.setEnabled(parsedMesh.isEnabled);
  15787. mesh.isVisible = parsedMesh.isVisible;
  15788. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15789. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15790. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15791. if (parsedMesh.applyFog !== undefined) {
  15792. mesh.applyFog = parsedMesh.applyFog;
  15793. }
  15794. if (parsedMesh.pickable !== undefined) {
  15795. mesh.isPickable = parsedMesh.pickable;
  15796. }
  15797. if (parsedMesh.alphaIndex !== undefined) {
  15798. mesh.alphaIndex = parsedMesh.alphaIndex;
  15799. }
  15800. mesh.receiveShadows = parsedMesh.receiveShadows;
  15801. mesh.billboardMode = parsedMesh.billboardMode;
  15802. if (parsedMesh.visibility !== undefined) {
  15803. mesh.visibility = parsedMesh.visibility;
  15804. }
  15805. mesh.checkCollisions = parsedMesh.checkCollisions;
  15806. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15807. // freezeWorldMatrix
  15808. if (parsedMesh.freezeWorldMatrix) {
  15809. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15810. }
  15811. // Parent
  15812. if (parsedMesh.parentId) {
  15813. mesh._waitingParentId = parsedMesh.parentId;
  15814. }
  15815. // Actions
  15816. if (parsedMesh.actions !== undefined) {
  15817. mesh._waitingActions = parsedMesh.actions;
  15818. }
  15819. // Geometry
  15820. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15821. if (parsedMesh.delayLoadingFile) {
  15822. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15823. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15824. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15825. if (parsedMesh._binaryInfo) {
  15826. mesh._binaryInfo = parsedMesh._binaryInfo;
  15827. }
  15828. mesh._delayInfo = [];
  15829. if (parsedMesh.hasUVs) {
  15830. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15831. }
  15832. if (parsedMesh.hasUVs2) {
  15833. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15834. }
  15835. if (parsedMesh.hasUVs3) {
  15836. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15837. }
  15838. if (parsedMesh.hasUVs4) {
  15839. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15840. }
  15841. if (parsedMesh.hasUVs5) {
  15842. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15843. }
  15844. if (parsedMesh.hasUVs6) {
  15845. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15846. }
  15847. if (parsedMesh.hasColors) {
  15848. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15849. }
  15850. if (parsedMesh.hasMatricesIndices) {
  15851. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15852. }
  15853. if (parsedMesh.hasMatricesWeights) {
  15854. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15855. }
  15856. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15857. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15858. mesh._checkDelayState();
  15859. }
  15860. }
  15861. else {
  15862. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15863. }
  15864. // Material
  15865. if (parsedMesh.materialId) {
  15866. mesh.setMaterialByID(parsedMesh.materialId);
  15867. }
  15868. else {
  15869. mesh.material = null;
  15870. }
  15871. // Skeleton
  15872. if (parsedMesh.skeletonId > -1) {
  15873. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15874. if (parsedMesh.numBoneInfluencers) {
  15875. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15876. }
  15877. }
  15878. // Physics
  15879. if (parsedMesh.physicsImpostor) {
  15880. if (!scene.isPhysicsEnabled()) {
  15881. scene.enablePhysics();
  15882. }
  15883. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15884. }
  15885. // Animations
  15886. if (parsedMesh.animations) {
  15887. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15888. var parsedAnimation = parsedMesh.animations[animationIndex];
  15889. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15890. }
  15891. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15892. }
  15893. if (parsedMesh.autoAnimate) {
  15894. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15895. }
  15896. // Layer Mask
  15897. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15898. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15899. }
  15900. else {
  15901. mesh.layerMask = 0x0FFFFFFF;
  15902. }
  15903. // Instances
  15904. if (parsedMesh.instances) {
  15905. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15906. var parsedInstance = parsedMesh.instances[index];
  15907. var instance = mesh.createInstance(parsedInstance.name);
  15908. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15909. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15910. if (parsedInstance.rotationQuaternion) {
  15911. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15912. }
  15913. else if (parsedInstance.rotation) {
  15914. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15915. }
  15916. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15917. instance.checkCollisions = mesh.checkCollisions;
  15918. if (parsedMesh.animations) {
  15919. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15920. parsedAnimation = parsedMesh.animations[animationIndex];
  15921. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15922. }
  15923. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15924. }
  15925. }
  15926. }
  15927. return mesh;
  15928. };
  15929. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15930. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15931. pathArray: pathArray,
  15932. closeArray: closeArray,
  15933. closePath: closePath,
  15934. offset: offset,
  15935. updatable: updatable,
  15936. sideOrientation: sideOrientation,
  15937. instance: instance
  15938. }, scene);
  15939. };
  15940. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15941. var options = {
  15942. radius: radius,
  15943. tessellation: tessellation,
  15944. sideOrientation: sideOrientation,
  15945. updatable: updatable
  15946. };
  15947. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15948. };
  15949. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15950. var options = {
  15951. size: size,
  15952. sideOrientation: sideOrientation,
  15953. updatable: updatable
  15954. };
  15955. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15956. };
  15957. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15958. var options = {
  15959. segments: segments,
  15960. diameterX: diameter,
  15961. diameterY: diameter,
  15962. diameterZ: diameter,
  15963. sideOrientation: sideOrientation,
  15964. updatable: updatable
  15965. };
  15966. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15967. };
  15968. // Cylinder and cone
  15969. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15970. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15971. if (scene !== undefined) {
  15972. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15973. updatable = scene;
  15974. }
  15975. scene = subdivisions;
  15976. subdivisions = 1;
  15977. }
  15978. var options = {
  15979. height: height,
  15980. diameterTop: diameterTop,
  15981. diameterBottom: diameterBottom,
  15982. tessellation: tessellation,
  15983. subdivisions: subdivisions,
  15984. sideOrientation: sideOrientation,
  15985. updatable: updatable
  15986. };
  15987. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15988. };
  15989. // Torus (Code from SharpDX.org)
  15990. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15991. var options = {
  15992. diameter: diameter,
  15993. thickness: thickness,
  15994. tessellation: tessellation,
  15995. sideOrientation: sideOrientation,
  15996. updatable: updatable
  15997. };
  15998. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15999. };
  16000. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16001. var options = {
  16002. radius: radius,
  16003. tube: tube,
  16004. radialSegments: radialSegments,
  16005. tubularSegments: tubularSegments,
  16006. p: p,
  16007. q: q,
  16008. sideOrientation: sideOrientation,
  16009. updatable: updatable
  16010. };
  16011. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16012. };
  16013. // Lines
  16014. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16015. var options = {
  16016. points: points,
  16017. updatable: updatable,
  16018. instance: instance
  16019. };
  16020. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16021. };
  16022. // Dashed Lines
  16023. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16024. var options = {
  16025. points: points,
  16026. dashSize: dashSize,
  16027. gapSize: gapSize,
  16028. dashNb: dashNb,
  16029. updatable: updatable
  16030. };
  16031. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16032. };
  16033. // Extrusion
  16034. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16035. var options = {
  16036. shape: shape,
  16037. path: path,
  16038. scale: scale,
  16039. rotation: rotation,
  16040. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16041. sideOrientation: sideOrientation,
  16042. instance: instance,
  16043. updatable: updatable
  16044. };
  16045. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16046. };
  16047. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16048. var options = {
  16049. shape: shape,
  16050. path: path,
  16051. scaleFunction: scaleFunction,
  16052. rotationFunction: rotationFunction,
  16053. ribbonCloseArray: ribbonCloseArray,
  16054. ribbonClosePath: ribbonClosePath,
  16055. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16056. sideOrientation: sideOrientation,
  16057. instance: instance,
  16058. updatable: updatable
  16059. };
  16060. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16061. };
  16062. // Lathe
  16063. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16064. var options = {
  16065. shape: shape,
  16066. radius: radius,
  16067. tessellation: tessellation,
  16068. sideOrientation: sideOrientation,
  16069. updatable: updatable
  16070. };
  16071. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16072. };
  16073. // Plane & ground
  16074. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16075. var options = {
  16076. size: size,
  16077. width: size,
  16078. height: size,
  16079. sideOrientation: sideOrientation,
  16080. updatable: updatable
  16081. };
  16082. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16083. };
  16084. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16085. var options = {
  16086. width: width,
  16087. height: height,
  16088. subdivisions: subdivisions,
  16089. updatable: updatable
  16090. };
  16091. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16092. };
  16093. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16094. var options = {
  16095. xmin: xmin,
  16096. zmin: zmin,
  16097. xmax: xmax,
  16098. zmax: zmax,
  16099. subdivisions: subdivisions,
  16100. precision: precision,
  16101. updatable: updatable
  16102. };
  16103. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16104. };
  16105. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16106. var options = {
  16107. width: width,
  16108. height: height,
  16109. subdivisions: subdivisions,
  16110. minHeight: minHeight,
  16111. maxHeight: maxHeight,
  16112. updatable: updatable,
  16113. onReady: onReady
  16114. };
  16115. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16116. };
  16117. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16118. var options = {
  16119. path: path,
  16120. radius: radius,
  16121. tessellation: tessellation,
  16122. radiusFunction: radiusFunction,
  16123. arc: 1,
  16124. cap: cap,
  16125. updatable: updatable,
  16126. sideOrientation: sideOrientation,
  16127. instance: instance
  16128. };
  16129. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16130. };
  16131. Mesh.CreatePolyhedron = function (name, options, scene) {
  16132. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16133. };
  16134. Mesh.CreateIcoSphere = function (name, options, scene) {
  16135. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16136. };
  16137. // Decals
  16138. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16139. var options = {
  16140. position: position,
  16141. normal: normal,
  16142. size: size,
  16143. angle: angle
  16144. };
  16145. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16146. };
  16147. // Skeletons
  16148. /**
  16149. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16150. */
  16151. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16152. var source;
  16153. if (!this._sourcePositions) {
  16154. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16155. this._sourcePositions = new Float32Array(source);
  16156. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16157. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16158. }
  16159. }
  16160. return this._sourcePositions;
  16161. };
  16162. /**
  16163. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16164. */
  16165. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16166. var source;
  16167. if (!this._sourceNormals) {
  16168. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16169. this._sourceNormals = new Float32Array(source);
  16170. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16171. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16172. }
  16173. }
  16174. return this._sourceNormals;
  16175. };
  16176. /**
  16177. * Update the vertex buffers by applying transformation from the bones
  16178. * @param {skeleton} skeleton to apply
  16179. */
  16180. Mesh.prototype.applySkeleton = function (skeleton) {
  16181. if (!this.geometry) {
  16182. return;
  16183. }
  16184. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16185. return;
  16186. }
  16187. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16188. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16189. return this;
  16190. }
  16191. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16192. return this;
  16193. }
  16194. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16195. return this;
  16196. }
  16197. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16198. return this;
  16199. }
  16200. if (!this._sourcePositions) {
  16201. this.setPositionsForCPUSkinning();
  16202. }
  16203. if (!this._sourceNormals) {
  16204. this.setNormalsForCPUSkinning();
  16205. }
  16206. // positionsData checks for not being Float32Array will only pass at most once
  16207. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16208. if (!(positionsData instanceof Float32Array)) {
  16209. positionsData = new Float32Array(positionsData);
  16210. }
  16211. // normalsData checks for not being Float32Array will only pass at most once
  16212. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16213. if (!(normalsData instanceof Float32Array)) {
  16214. normalsData = new Float32Array(normalsData);
  16215. }
  16216. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16217. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16218. var needExtras = this.numBoneInfluencers > 4;
  16219. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16220. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16221. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16222. var tempVector3 = BABYLON.Vector3.Zero();
  16223. var finalMatrix = new BABYLON.Matrix();
  16224. var tempMatrix = new BABYLON.Matrix();
  16225. var matWeightIdx = 0;
  16226. var inf;
  16227. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16228. var weight;
  16229. for (inf = 0; inf < 4; inf++) {
  16230. weight = matricesWeightsData[matWeightIdx + inf];
  16231. if (weight > 0) {
  16232. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16233. finalMatrix.addToSelf(tempMatrix);
  16234. }
  16235. else
  16236. break;
  16237. }
  16238. if (needExtras) {
  16239. for (inf = 0; inf < 4; inf++) {
  16240. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16241. if (weight > 0) {
  16242. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16243. finalMatrix.addToSelf(tempMatrix);
  16244. }
  16245. else
  16246. break;
  16247. }
  16248. }
  16249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16250. tempVector3.toArray(positionsData, index);
  16251. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16252. tempVector3.toArray(normalsData, index);
  16253. finalMatrix.reset();
  16254. }
  16255. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16256. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16257. return this;
  16258. };
  16259. // Tools
  16260. Mesh.MinMax = function (meshes) {
  16261. var minVector = null;
  16262. var maxVector = null;
  16263. for (var i in meshes) {
  16264. var mesh = meshes[i];
  16265. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16266. if (!minVector) {
  16267. minVector = boundingBox.minimumWorld;
  16268. maxVector = boundingBox.maximumWorld;
  16269. continue;
  16270. }
  16271. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16272. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16273. }
  16274. return {
  16275. min: minVector,
  16276. max: maxVector
  16277. };
  16278. };
  16279. Mesh.Center = function (meshesOrMinMaxVector) {
  16280. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16281. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16282. };
  16283. /**
  16284. * Merge the array of meshes into a single mesh for performance reasons.
  16285. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16286. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16287. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16288. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16289. */
  16290. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16291. if (disposeSource === void 0) { disposeSource = true; }
  16292. var index;
  16293. if (!allow32BitsIndices) {
  16294. var totalVertices = 0;
  16295. // Counting vertices
  16296. for (index = 0; index < meshes.length; index++) {
  16297. if (meshes[index]) {
  16298. totalVertices += meshes[index].getTotalVertices();
  16299. if (totalVertices > 65536) {
  16300. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16301. return null;
  16302. }
  16303. }
  16304. }
  16305. }
  16306. // Merge
  16307. var vertexData;
  16308. var otherVertexData;
  16309. var source;
  16310. for (index = 0; index < meshes.length; index++) {
  16311. if (meshes[index]) {
  16312. meshes[index].computeWorldMatrix(true);
  16313. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16314. otherVertexData.transform(meshes[index].getWorldMatrix());
  16315. if (vertexData) {
  16316. vertexData.merge(otherVertexData);
  16317. }
  16318. else {
  16319. vertexData = otherVertexData;
  16320. source = meshes[index];
  16321. }
  16322. }
  16323. }
  16324. if (!meshSubclass) {
  16325. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16326. }
  16327. vertexData.applyToMesh(meshSubclass);
  16328. // Setting properties
  16329. meshSubclass.material = source.material;
  16330. meshSubclass.checkCollisions = source.checkCollisions;
  16331. // Cleaning
  16332. if (disposeSource) {
  16333. for (index = 0; index < meshes.length; index++) {
  16334. if (meshes[index]) {
  16335. meshes[index].dispose();
  16336. }
  16337. }
  16338. }
  16339. return meshSubclass;
  16340. };
  16341. // Consts
  16342. Mesh._FRONTSIDE = 0;
  16343. Mesh._BACKSIDE = 1;
  16344. Mesh._DOUBLESIDE = 2;
  16345. Mesh._DEFAULTSIDE = 0;
  16346. Mesh._NO_CAP = 0;
  16347. Mesh._CAP_START = 1;
  16348. Mesh._CAP_END = 2;
  16349. Mesh._CAP_ALL = 3;
  16350. return Mesh;
  16351. })(BABYLON.AbstractMesh);
  16352. BABYLON.Mesh = Mesh;
  16353. })(BABYLON || (BABYLON = {}));
  16354. var BABYLON;
  16355. (function (BABYLON) {
  16356. var SubMesh = (function () {
  16357. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16358. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16359. this.materialIndex = materialIndex;
  16360. this.verticesStart = verticesStart;
  16361. this.verticesCount = verticesCount;
  16362. this.indexStart = indexStart;
  16363. this.indexCount = indexCount;
  16364. this._renderId = 0;
  16365. this._mesh = mesh;
  16366. this._renderingMesh = renderingMesh || mesh;
  16367. mesh.subMeshes.push(this);
  16368. this._trianglePlanes = [];
  16369. this._id = mesh.subMeshes.length - 1;
  16370. if (createBoundingBox) {
  16371. this.refreshBoundingInfo();
  16372. mesh.computeWorldMatrix(true);
  16373. }
  16374. }
  16375. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16376. get: function () {
  16377. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. SubMesh.prototype.getBoundingInfo = function () {
  16383. if (this.IsGlobal) {
  16384. return this._mesh.getBoundingInfo();
  16385. }
  16386. return this._boundingInfo;
  16387. };
  16388. SubMesh.prototype.getMesh = function () {
  16389. return this._mesh;
  16390. };
  16391. SubMesh.prototype.getRenderingMesh = function () {
  16392. return this._renderingMesh;
  16393. };
  16394. SubMesh.prototype.getMaterial = function () {
  16395. var rootMaterial = this._renderingMesh.material;
  16396. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16397. var multiMaterial = rootMaterial;
  16398. return multiMaterial.getSubMaterial(this.materialIndex);
  16399. }
  16400. if (!rootMaterial) {
  16401. return this._mesh.getScene().defaultMaterial;
  16402. }
  16403. return rootMaterial;
  16404. };
  16405. // Methods
  16406. SubMesh.prototype.refreshBoundingInfo = function () {
  16407. if (this.IsGlobal) {
  16408. return;
  16409. }
  16410. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16411. if (!data) {
  16412. this._boundingInfo = this._mesh._boundingInfo;
  16413. return;
  16414. }
  16415. var indices = this._renderingMesh.getIndices();
  16416. var extend;
  16417. //is this the only submesh?
  16418. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16419. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16420. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16421. }
  16422. else {
  16423. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16424. }
  16425. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16426. };
  16427. SubMesh.prototype._checkCollision = function (collider) {
  16428. return this.getBoundingInfo()._checkCollision(collider);
  16429. };
  16430. SubMesh.prototype.updateBoundingInfo = function (world) {
  16431. if (!this.getBoundingInfo()) {
  16432. this.refreshBoundingInfo();
  16433. }
  16434. this.getBoundingInfo().update(world);
  16435. };
  16436. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16437. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16438. };
  16439. SubMesh.prototype.render = function (enableAlphaMode) {
  16440. this._renderingMesh.render(this, enableAlphaMode);
  16441. };
  16442. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16443. if (!this._linesIndexBuffer) {
  16444. var linesIndices = [];
  16445. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16446. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16447. }
  16448. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16449. this.linesIndexCount = linesIndices.length;
  16450. }
  16451. return this._linesIndexBuffer;
  16452. };
  16453. SubMesh.prototype.canIntersects = function (ray) {
  16454. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16455. };
  16456. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16457. var intersectInfo = null;
  16458. // Triangles test
  16459. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16460. var p0 = positions[indices[index]];
  16461. var p1 = positions[indices[index + 1]];
  16462. var p2 = positions[indices[index + 2]];
  16463. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16464. if (currentIntersectInfo) {
  16465. if (currentIntersectInfo.distance < 0) {
  16466. continue;
  16467. }
  16468. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16469. intersectInfo = currentIntersectInfo;
  16470. intersectInfo.faceId = index / 3;
  16471. if (fastCheck) {
  16472. break;
  16473. }
  16474. }
  16475. }
  16476. }
  16477. return intersectInfo;
  16478. };
  16479. // Clone
  16480. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16481. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16482. if (!this.IsGlobal) {
  16483. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16484. }
  16485. return result;
  16486. };
  16487. // Dispose
  16488. SubMesh.prototype.dispose = function () {
  16489. if (this._linesIndexBuffer) {
  16490. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16491. this._linesIndexBuffer = null;
  16492. }
  16493. // Remove from mesh
  16494. var index = this._mesh.subMeshes.indexOf(this);
  16495. this._mesh.subMeshes.splice(index, 1);
  16496. };
  16497. // Statics
  16498. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16499. var minVertexIndex = Number.MAX_VALUE;
  16500. var maxVertexIndex = -Number.MAX_VALUE;
  16501. renderingMesh = renderingMesh || mesh;
  16502. var indices = renderingMesh.getIndices();
  16503. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16504. var vertexIndex = indices[index];
  16505. if (vertexIndex < minVertexIndex)
  16506. minVertexIndex = vertexIndex;
  16507. if (vertexIndex > maxVertexIndex)
  16508. maxVertexIndex = vertexIndex;
  16509. }
  16510. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16511. };
  16512. return SubMesh;
  16513. })();
  16514. BABYLON.SubMesh = SubMesh;
  16515. })(BABYLON || (BABYLON = {}));
  16516. var BABYLON;
  16517. (function (BABYLON) {
  16518. var MeshBuilder = (function () {
  16519. function MeshBuilder() {
  16520. }
  16521. MeshBuilder.CreateBox = function (name, options, scene) {
  16522. var box = new BABYLON.Mesh(name, scene);
  16523. var vertexData = BABYLON.VertexData.CreateBox(options);
  16524. vertexData.applyToMesh(box, options.updatable);
  16525. return box;
  16526. };
  16527. MeshBuilder.CreateSphere = function (name, options, scene) {
  16528. var sphere = new BABYLON.Mesh(name, scene);
  16529. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16530. vertexData.applyToMesh(sphere, options.updatable);
  16531. return sphere;
  16532. };
  16533. MeshBuilder.CreateDisc = function (name, options, scene) {
  16534. var disc = new BABYLON.Mesh(name, scene);
  16535. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16536. vertexData.applyToMesh(disc, options.updatable);
  16537. return disc;
  16538. };
  16539. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16540. var sphere = new BABYLON.Mesh(name, scene);
  16541. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16542. vertexData.applyToMesh(sphere, options.updatable);
  16543. return sphere;
  16544. };
  16545. ;
  16546. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16547. var pathArray = options.pathArray;
  16548. var closeArray = options.closeArray;
  16549. var closePath = options.closePath;
  16550. var offset = options.offset;
  16551. var sideOrientation = options.sideOrientation;
  16552. var instance = options.instance;
  16553. var updatable = options.updatable;
  16554. if (instance) {
  16555. // positionFunction : ribbon case
  16556. // only pathArray and sideOrientation parameters are taken into account for positions update
  16557. var positionFunction = function (positions) {
  16558. var minlg = pathArray[0].length;
  16559. var i = 0;
  16560. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16561. for (var si = 1; si <= ns; si++) {
  16562. for (var p = 0; p < pathArray.length; p++) {
  16563. var path = pathArray[p];
  16564. var l = path.length;
  16565. minlg = (minlg < l) ? minlg : l;
  16566. var j = 0;
  16567. while (j < minlg) {
  16568. positions[i] = path[j].x;
  16569. positions[i + 1] = path[j].y;
  16570. positions[i + 2] = path[j].z;
  16571. j++;
  16572. i += 3;
  16573. }
  16574. if (instance._closePath) {
  16575. positions[i] = path[0].x;
  16576. positions[i + 1] = path[0].y;
  16577. positions[i + 2] = path[0].z;
  16578. i += 3;
  16579. }
  16580. }
  16581. }
  16582. };
  16583. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16584. positionFunction(positions);
  16585. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16586. if (!(instance.areNormalsFrozen)) {
  16587. var indices = instance.getIndices();
  16588. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16589. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16590. if (instance._closePath) {
  16591. var indexFirst = 0;
  16592. var indexLast = 0;
  16593. for (var p = 0; p < pathArray.length; p++) {
  16594. indexFirst = instance._idx[p] * 3;
  16595. if (p + 1 < pathArray.length) {
  16596. indexLast = (instance._idx[p + 1] - 1) * 3;
  16597. }
  16598. else {
  16599. indexLast = normals.length - 3;
  16600. }
  16601. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16602. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16603. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16604. normals[indexLast] = normals[indexFirst];
  16605. normals[indexLast + 1] = normals[indexFirst + 1];
  16606. normals[indexLast + 2] = normals[indexFirst + 2];
  16607. }
  16608. }
  16609. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16610. }
  16611. return instance;
  16612. }
  16613. else {
  16614. var ribbon = new BABYLON.Mesh(name, scene);
  16615. ribbon.sideOrientation = sideOrientation;
  16616. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16617. if (closePath) {
  16618. ribbon._idx = vertexData._idx;
  16619. }
  16620. ribbon._closePath = closePath;
  16621. ribbon._closeArray = closeArray;
  16622. vertexData.applyToMesh(ribbon, updatable);
  16623. return ribbon;
  16624. }
  16625. };
  16626. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16627. var cylinder = new BABYLON.Mesh(name, scene);
  16628. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16629. vertexData.applyToMesh(cylinder, options.updatable);
  16630. return cylinder;
  16631. };
  16632. MeshBuilder.CreateTorus = function (name, options, scene) {
  16633. var torus = new BABYLON.Mesh(name, scene);
  16634. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16635. vertexData.applyToMesh(torus, options.updatable);
  16636. return torus;
  16637. };
  16638. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16639. var torusKnot = new BABYLON.Mesh(name, scene);
  16640. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16641. vertexData.applyToMesh(torusKnot, options.updatable);
  16642. return torusKnot;
  16643. };
  16644. MeshBuilder.CreateLines = function (name, options, scene) {
  16645. var instance = options.instance;
  16646. var points = options.points;
  16647. if (instance) {
  16648. var positionFunction = function (positions) {
  16649. var i = 0;
  16650. for (var p = 0; p < points.length; p++) {
  16651. positions[i] = points[p].x;
  16652. positions[i + 1] = points[p].y;
  16653. positions[i + 2] = points[p].z;
  16654. i += 3;
  16655. }
  16656. };
  16657. instance.updateMeshPositions(positionFunction, false);
  16658. return instance;
  16659. }
  16660. // lines creation
  16661. var lines = new BABYLON.LinesMesh(name, scene);
  16662. var vertexData = BABYLON.VertexData.CreateLines(options);
  16663. vertexData.applyToMesh(lines, options.updatable);
  16664. return lines;
  16665. };
  16666. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16667. var points = options.points;
  16668. var instance = options.instance;
  16669. var gapSize = options.gapSize;
  16670. var dashNb = options.dashNb;
  16671. var dashSize = options.dashSize;
  16672. if (instance) {
  16673. var positionFunction = function (positions) {
  16674. var curvect = BABYLON.Vector3.Zero();
  16675. var nbSeg = positions.length / 6;
  16676. var lg = 0;
  16677. var nb = 0;
  16678. var shft = 0;
  16679. var dashshft = 0;
  16680. var curshft = 0;
  16681. var p = 0;
  16682. var i = 0;
  16683. var j = 0;
  16684. for (i = 0; i < points.length - 1; i++) {
  16685. points[i + 1].subtractToRef(points[i], curvect);
  16686. lg += curvect.length();
  16687. }
  16688. shft = lg / nbSeg;
  16689. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16690. for (i = 0; i < points.length - 1; i++) {
  16691. points[i + 1].subtractToRef(points[i], curvect);
  16692. nb = Math.floor(curvect.length() / shft);
  16693. curvect.normalize();
  16694. j = 0;
  16695. while (j < nb && p < positions.length) {
  16696. curshft = shft * j;
  16697. positions[p] = points[i].x + curshft * curvect.x;
  16698. positions[p + 1] = points[i].y + curshft * curvect.y;
  16699. positions[p + 2] = points[i].z + curshft * curvect.z;
  16700. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16701. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16702. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16703. p += 6;
  16704. j++;
  16705. }
  16706. }
  16707. while (p < positions.length) {
  16708. positions[p] = points[i].x;
  16709. positions[p + 1] = points[i].y;
  16710. positions[p + 2] = points[i].z;
  16711. p += 3;
  16712. }
  16713. };
  16714. instance.updateMeshPositions(positionFunction, false);
  16715. return instance;
  16716. }
  16717. // dashed lines creation
  16718. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16719. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16720. vertexData.applyToMesh(dashedLines, options.updatable);
  16721. dashedLines.dashSize = dashSize;
  16722. dashedLines.gapSize = gapSize;
  16723. return dashedLines;
  16724. };
  16725. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16726. var path = options.path;
  16727. var shape = options.shape;
  16728. var scale = options.scale || 1;
  16729. var rotation = options.rotation || 0;
  16730. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16731. var updatable = options.updatable;
  16732. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16733. var instance = options.instance;
  16734. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16735. };
  16736. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16737. var path = options.path;
  16738. var shape = options.shape;
  16739. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16740. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16741. var ribbonCloseArray = options.ribbonCloseArray || false;
  16742. var ribbonClosePath = options.ribbonClosePath || false;
  16743. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16744. var updatable = options.updatable;
  16745. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16746. var instance = options.instance;
  16747. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16748. };
  16749. MeshBuilder.CreateLathe = function (name, options, scene) {
  16750. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16751. var closed = (options.closed === undefined) ? true : options.closed;
  16752. var shape = options.shape;
  16753. var radius = options.radius || 1;
  16754. var tessellation = options.tessellation || 64;
  16755. var updatable = options.updatable;
  16756. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16757. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16758. var pi2 = Math.PI * 2;
  16759. var paths = new Array();
  16760. var i = 0;
  16761. var p = 0;
  16762. var step = pi2 / tessellation * arc;
  16763. var rotated;
  16764. var path = new Array();
  16765. ;
  16766. for (i = 0; i <= tessellation; i++) {
  16767. var path = [];
  16768. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16769. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16770. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16771. }
  16772. for (p = 0; p < shape.length; p++) {
  16773. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16774. path.push(rotated);
  16775. }
  16776. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16777. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16778. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16779. }
  16780. paths.push(path);
  16781. }
  16782. // lathe ribbon
  16783. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16784. return lathe;
  16785. };
  16786. MeshBuilder.CreatePlane = function (name, options, scene) {
  16787. var plane = new BABYLON.Mesh(name, scene);
  16788. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16789. vertexData.applyToMesh(plane, options.updatable);
  16790. if (options.sourcePlane) {
  16791. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16792. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16793. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16794. plane.rotate(vectorProduct, product);
  16795. }
  16796. return plane;
  16797. };
  16798. MeshBuilder.CreateGround = function (name, options, scene) {
  16799. var ground = new BABYLON.GroundMesh(name, scene);
  16800. ground._setReady(false);
  16801. ground._subdivisions = options.subdivisions || 1;
  16802. ground._width = options.width || 1;
  16803. ground._height = options.height || 1;
  16804. ground._maxX = ground._width / 2;
  16805. ground._maxZ = ground._height / 2;
  16806. ground._minX = -ground._maxX;
  16807. ground._minZ = -ground._maxZ;
  16808. var vertexData = BABYLON.VertexData.CreateGround(options);
  16809. vertexData.applyToMesh(ground, options.updatable);
  16810. ground._setReady(true);
  16811. return ground;
  16812. };
  16813. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16814. var tiledGround = new BABYLON.Mesh(name, scene);
  16815. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16816. vertexData.applyToMesh(tiledGround, options.updatable);
  16817. return tiledGround;
  16818. };
  16819. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16820. var width = options.width || 10;
  16821. var height = options.height || 10;
  16822. var subdivisions = options.subdivisions || 1;
  16823. var minHeight = options.minHeight;
  16824. var maxHeight = options.maxHeight || 10;
  16825. var updatable = options.updatable;
  16826. var onReady = options.onReady;
  16827. var ground = new BABYLON.GroundMesh(name, scene);
  16828. ground._subdivisions = subdivisions;
  16829. ground._width = width;
  16830. ground._height = height;
  16831. ground._maxX = ground._width / 2;
  16832. ground._maxZ = ground._height / 2;
  16833. ground._minX = -ground._maxX;
  16834. ground._minZ = -ground._maxZ;
  16835. ground._setReady(false);
  16836. var onload = function (img) {
  16837. // Getting height map data
  16838. var canvas = document.createElement("canvas");
  16839. var context = canvas.getContext("2d");
  16840. var bufferWidth = img.width;
  16841. var bufferHeight = img.height;
  16842. canvas.width = bufferWidth;
  16843. canvas.height = bufferHeight;
  16844. context.drawImage(img, 0, 0);
  16845. // Create VertexData from map data
  16846. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16847. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16848. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16849. width: width, height: height,
  16850. subdivisions: subdivisions,
  16851. minHeight: minHeight, maxHeight: maxHeight,
  16852. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16853. });
  16854. vertexData.applyToMesh(ground, updatable);
  16855. ground._setReady(true);
  16856. //execute ready callback, if set
  16857. if (onReady) {
  16858. onReady(ground);
  16859. }
  16860. };
  16861. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16862. return ground;
  16863. };
  16864. MeshBuilder.CreateTube = function (name, options, scene) {
  16865. var path = options.path;
  16866. var radius = options.radius || 1;
  16867. var tessellation = options.tessellation || 64;
  16868. var radiusFunction = options.radiusFunction;
  16869. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16870. var updatable = options.updatable;
  16871. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16872. var instance = options.instance;
  16873. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16874. // tube geometry
  16875. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16876. var tangents = path3D.getTangents();
  16877. var normals = path3D.getNormals();
  16878. var distances = path3D.getDistances();
  16879. var pi2 = Math.PI * 2;
  16880. var step = pi2 / tessellation * arc;
  16881. var returnRadius = function () { return radius; };
  16882. var radiusFunctionFinal = radiusFunction || returnRadius;
  16883. var circlePath;
  16884. var rad;
  16885. var normal;
  16886. var rotated;
  16887. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16888. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16889. for (var i = 0; i < path.length; i++) {
  16890. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16891. circlePath = Array(); // current circle array
  16892. normal = normals[i]; // current normal
  16893. for (var t = 0; t < tessellation; t++) {
  16894. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16895. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16896. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16897. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16898. circlePath[t] = rotated;
  16899. }
  16900. circlePaths[index] = circlePath;
  16901. index++;
  16902. }
  16903. // cap
  16904. var capPath = function (nbPoints, pathIndex) {
  16905. var pointCap = Array();
  16906. for (var i = 0; i < nbPoints; i++) {
  16907. pointCap.push(path[pathIndex]);
  16908. }
  16909. return pointCap;
  16910. };
  16911. switch (cap) {
  16912. case BABYLON.Mesh.NO_CAP:
  16913. break;
  16914. case BABYLON.Mesh.CAP_START:
  16915. circlePaths[0] = capPath(tessellation, 0);
  16916. circlePaths[1] = circlePaths[2].slice(0);
  16917. break;
  16918. case BABYLON.Mesh.CAP_END:
  16919. circlePaths[index] = circlePaths[index - 1].slice(0);
  16920. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16921. break;
  16922. case BABYLON.Mesh.CAP_ALL:
  16923. circlePaths[0] = capPath(tessellation, 0);
  16924. circlePaths[1] = circlePaths[2].slice(0);
  16925. circlePaths[index] = circlePaths[index - 1].slice(0);
  16926. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16927. break;
  16928. default:
  16929. break;
  16930. }
  16931. return circlePaths;
  16932. };
  16933. var path3D;
  16934. var pathArray;
  16935. if (instance) {
  16936. var arc = options.arc || instance.arc;
  16937. path3D = (instance.path3D).update(path);
  16938. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16939. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16940. instance.path3D = path3D;
  16941. instance.pathArray = pathArray;
  16942. instance.arc = arc;
  16943. return instance;
  16944. }
  16945. // tube creation
  16946. path3D = new BABYLON.Path3D(path);
  16947. var newPathArray = new Array();
  16948. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16949. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16950. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16951. tube.pathArray = pathArray;
  16952. tube.path3D = path3D;
  16953. tube.tessellation = tessellation;
  16954. tube.cap = cap;
  16955. tube.arc = options.arc;
  16956. return tube;
  16957. };
  16958. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16959. var polyhedron = new BABYLON.Mesh(name, scene);
  16960. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16961. vertexData.applyToMesh(polyhedron, options.updatable);
  16962. return polyhedron;
  16963. };
  16964. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16965. var indices = sourceMesh.getIndices();
  16966. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16967. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16968. var position = options.position || BABYLON.Vector3.Zero();
  16969. var normal = options.normal || BABYLON.Vector3.Up();
  16970. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16971. var angle = options.angle || 0;
  16972. // Getting correct rotation
  16973. if (!normal) {
  16974. var target = new BABYLON.Vector3(0, 0, 1);
  16975. var camera = sourceMesh.getScene().activeCamera;
  16976. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16977. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16978. }
  16979. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16980. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16981. var pitch = Math.atan2(normal.y, len);
  16982. // Matrix
  16983. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16984. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16985. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16986. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16987. var vertexData = new BABYLON.VertexData();
  16988. vertexData.indices = [];
  16989. vertexData.positions = [];
  16990. vertexData.normals = [];
  16991. vertexData.uvs = [];
  16992. var currentVertexDataIndex = 0;
  16993. var extractDecalVector3 = function (indexId) {
  16994. var vertexId = indices[indexId];
  16995. var result = new BABYLON.PositionNormalVertex();
  16996. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16997. // Send vector to decal local world
  16998. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16999. // Get normal
  17000. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17001. return result;
  17002. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17003. var clip = function (vertices, axis) {
  17004. if (vertices.length === 0) {
  17005. return vertices;
  17006. }
  17007. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17008. var clipVertices = function (v0, v1) {
  17009. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17010. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17011. };
  17012. var result = new Array();
  17013. for (var index = 0; index < vertices.length; index += 3) {
  17014. var v1Out;
  17015. var v2Out;
  17016. var v3Out;
  17017. var total = 0;
  17018. var nV1, nV2, nV3, nV4;
  17019. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17020. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17021. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17022. v1Out = d1 > 0;
  17023. v2Out = d2 > 0;
  17024. v3Out = d3 > 0;
  17025. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17026. switch (total) {
  17027. case 0:
  17028. result.push(vertices[index]);
  17029. result.push(vertices[index + 1]);
  17030. result.push(vertices[index + 2]);
  17031. break;
  17032. case 1:
  17033. if (v1Out) {
  17034. nV1 = vertices[index + 1];
  17035. nV2 = vertices[index + 2];
  17036. nV3 = clipVertices(vertices[index], nV1);
  17037. nV4 = clipVertices(vertices[index], nV2);
  17038. }
  17039. if (v2Out) {
  17040. nV1 = vertices[index];
  17041. nV2 = vertices[index + 2];
  17042. nV3 = clipVertices(vertices[index + 1], nV1);
  17043. nV4 = clipVertices(vertices[index + 1], nV2);
  17044. result.push(nV3);
  17045. result.push(nV2.clone());
  17046. result.push(nV1.clone());
  17047. result.push(nV2.clone());
  17048. result.push(nV3.clone());
  17049. result.push(nV4);
  17050. break;
  17051. }
  17052. if (v3Out) {
  17053. nV1 = vertices[index];
  17054. nV2 = vertices[index + 1];
  17055. nV3 = clipVertices(vertices[index + 2], nV1);
  17056. nV4 = clipVertices(vertices[index + 2], nV2);
  17057. }
  17058. result.push(nV1.clone());
  17059. result.push(nV2.clone());
  17060. result.push(nV3);
  17061. result.push(nV4);
  17062. result.push(nV3.clone());
  17063. result.push(nV2.clone());
  17064. break;
  17065. case 2:
  17066. if (!v1Out) {
  17067. nV1 = vertices[index].clone();
  17068. nV2 = clipVertices(nV1, vertices[index + 1]);
  17069. nV3 = clipVertices(nV1, vertices[index + 2]);
  17070. result.push(nV1);
  17071. result.push(nV2);
  17072. result.push(nV3);
  17073. }
  17074. if (!v2Out) {
  17075. nV1 = vertices[index + 1].clone();
  17076. nV2 = clipVertices(nV1, vertices[index + 2]);
  17077. nV3 = clipVertices(nV1, vertices[index]);
  17078. result.push(nV1);
  17079. result.push(nV2);
  17080. result.push(nV3);
  17081. }
  17082. if (!v3Out) {
  17083. nV1 = vertices[index + 2].clone();
  17084. nV2 = clipVertices(nV1, vertices[index]);
  17085. nV3 = clipVertices(nV1, vertices[index + 1]);
  17086. result.push(nV1);
  17087. result.push(nV2);
  17088. result.push(nV3);
  17089. }
  17090. break;
  17091. case 3:
  17092. break;
  17093. }
  17094. }
  17095. return result;
  17096. };
  17097. for (var index = 0; index < indices.length; index += 3) {
  17098. var faceVertices = new Array();
  17099. faceVertices.push(extractDecalVector3(index));
  17100. faceVertices.push(extractDecalVector3(index + 1));
  17101. faceVertices.push(extractDecalVector3(index + 2));
  17102. // Clip
  17103. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17104. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17105. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17106. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17107. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17108. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17109. if (faceVertices.length === 0) {
  17110. continue;
  17111. }
  17112. // Add UVs and get back to world
  17113. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17114. var vertex = faceVertices[vIndex];
  17115. //TODO check for Int32Array
  17116. vertexData.indices.push(currentVertexDataIndex);
  17117. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17118. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17119. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17120. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17121. currentVertexDataIndex++;
  17122. }
  17123. }
  17124. // Return mesh
  17125. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17126. vertexData.applyToMesh(decal);
  17127. decal.position = position.clone();
  17128. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17129. return decal;
  17130. };
  17131. // Privates
  17132. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17133. // extrusion geometry
  17134. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17135. var tangents = path3D.getTangents();
  17136. var normals = path3D.getNormals();
  17137. var binormals = path3D.getBinormals();
  17138. var distances = path3D.getDistances();
  17139. var angle = 0;
  17140. var returnScale = function () { return scale; };
  17141. var returnRotation = function () { return rotation; };
  17142. var rotate = custom ? rotateFunction : returnRotation;
  17143. var scl = custom ? scaleFunction : returnScale;
  17144. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17145. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17146. for (var i = 0; i < curve.length; i++) {
  17147. var shapePath = new Array();
  17148. var angleStep = rotate(i, distances[i]);
  17149. var scaleRatio = scl(i, distances[i]);
  17150. for (var p = 0; p < shape.length; p++) {
  17151. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17152. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17153. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17154. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17155. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17156. shapePath[p] = rotated;
  17157. }
  17158. shapePaths[index] = shapePath;
  17159. angle += angleStep;
  17160. index++;
  17161. }
  17162. // cap
  17163. var capPath = function (shapePath) {
  17164. var pointCap = Array();
  17165. var barycenter = BABYLON.Vector3.Zero();
  17166. var i;
  17167. for (i = 0; i < shapePath.length; i++) {
  17168. barycenter.addInPlace(shapePath[i]);
  17169. }
  17170. barycenter.scaleInPlace(1 / shapePath.length);
  17171. for (i = 0; i < shapePath.length; i++) {
  17172. pointCap.push(barycenter);
  17173. }
  17174. return pointCap;
  17175. };
  17176. switch (cap) {
  17177. case BABYLON.Mesh.NO_CAP:
  17178. break;
  17179. case BABYLON.Mesh.CAP_START:
  17180. shapePaths[0] = capPath(shapePaths[2]);
  17181. shapePaths[1] = shapePaths[2].slice(0);
  17182. break;
  17183. case BABYLON.Mesh.CAP_END:
  17184. shapePaths[index] = shapePaths[index - 1];
  17185. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17186. break;
  17187. case BABYLON.Mesh.CAP_ALL:
  17188. shapePaths[0] = capPath(shapePaths[2]);
  17189. shapePaths[1] = shapePaths[2].slice(0);
  17190. shapePaths[index] = shapePaths[index - 1];
  17191. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17192. break;
  17193. default:
  17194. break;
  17195. }
  17196. return shapePaths;
  17197. };
  17198. var path3D;
  17199. var pathArray;
  17200. if (instance) {
  17201. path3D = (instance.path3D).update(curve);
  17202. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17203. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17204. return instance;
  17205. }
  17206. // extruded shape creation
  17207. path3D = new BABYLON.Path3D(curve);
  17208. var newShapePaths = new Array();
  17209. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17210. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17211. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17212. extrudedGeneric.pathArray = pathArray;
  17213. extrudedGeneric.path3D = path3D;
  17214. extrudedGeneric.cap = cap;
  17215. return extrudedGeneric;
  17216. };
  17217. return MeshBuilder;
  17218. })();
  17219. BABYLON.MeshBuilder = MeshBuilder;
  17220. })(BABYLON || (BABYLON = {}));
  17221. var BABYLON;
  17222. (function (BABYLON) {
  17223. var BaseTexture = (function () {
  17224. function BaseTexture(scene) {
  17225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17226. this.hasAlpha = false;
  17227. this.getAlphaFromRGB = false;
  17228. this.level = 1;
  17229. this.isCube = false;
  17230. this.isRenderTarget = false;
  17231. this.animations = new Array();
  17232. this.coordinatesIndex = 0;
  17233. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17234. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17235. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17236. this.anisotropicFilteringLevel = 4;
  17237. this._scene = scene;
  17238. this._scene.textures.push(this);
  17239. }
  17240. BaseTexture.prototype.getScene = function () {
  17241. return this._scene;
  17242. };
  17243. BaseTexture.prototype.getTextureMatrix = function () {
  17244. return null;
  17245. };
  17246. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17247. return null;
  17248. };
  17249. BaseTexture.prototype.getInternalTexture = function () {
  17250. return this._texture;
  17251. };
  17252. BaseTexture.prototype.isReady = function () {
  17253. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17254. return true;
  17255. }
  17256. if (this._texture) {
  17257. return this._texture.isReady;
  17258. }
  17259. return false;
  17260. };
  17261. BaseTexture.prototype.getSize = function () {
  17262. if (this._texture._width) {
  17263. return { width: this._texture._width, height: this._texture._height };
  17264. }
  17265. if (this._texture._size) {
  17266. return { width: this._texture._size, height: this._texture._size };
  17267. }
  17268. return { width: 0, height: 0 };
  17269. };
  17270. BaseTexture.prototype.getBaseSize = function () {
  17271. if (!this.isReady())
  17272. return { width: 0, height: 0 };
  17273. if (this._texture._size) {
  17274. return { width: this._texture._size, height: this._texture._size };
  17275. }
  17276. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17277. };
  17278. BaseTexture.prototype.scale = function (ratio) {
  17279. };
  17280. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17281. get: function () {
  17282. return false;
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17288. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17289. for (var index = 0; index < texturesCache.length; index++) {
  17290. var texturesCacheEntry = texturesCache[index];
  17291. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17292. texturesCache.splice(index, 1);
  17293. return;
  17294. }
  17295. }
  17296. };
  17297. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17298. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17299. for (var index = 0; index < texturesCache.length; index++) {
  17300. var texturesCacheEntry = texturesCache[index];
  17301. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17302. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17303. texturesCacheEntry.references++;
  17304. return texturesCacheEntry;
  17305. }
  17306. }
  17307. }
  17308. return null;
  17309. };
  17310. BaseTexture.prototype.delayLoad = function () {
  17311. };
  17312. BaseTexture.prototype.clone = function () {
  17313. return null;
  17314. };
  17315. BaseTexture.prototype.releaseInternalTexture = function () {
  17316. if (this._texture) {
  17317. this._scene.getEngine().releaseInternalTexture(this._texture);
  17318. delete this._texture;
  17319. }
  17320. };
  17321. BaseTexture.prototype.dispose = function () {
  17322. // Animations
  17323. this.getScene().stopAnimation(this);
  17324. // Remove from scene
  17325. var index = this._scene.textures.indexOf(this);
  17326. if (index >= 0) {
  17327. this._scene.textures.splice(index, 1);
  17328. }
  17329. if (this._texture === undefined) {
  17330. return;
  17331. }
  17332. // Release
  17333. this.releaseInternalTexture();
  17334. // Callback
  17335. if (this.onDispose) {
  17336. this.onDispose();
  17337. }
  17338. };
  17339. BaseTexture.prototype.serialize = function () {
  17340. var serializationObject = {};
  17341. if (!this.name) {
  17342. return null;
  17343. }
  17344. serializationObject.name = this.name;
  17345. serializationObject.hasAlpha = this.hasAlpha;
  17346. serializationObject.level = this.level;
  17347. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17348. serializationObject.coordinatesMode = this.coordinatesMode;
  17349. serializationObject.wrapU = this.wrapU;
  17350. serializationObject.wrapV = this.wrapV;
  17351. // Animations
  17352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17353. return serializationObject;
  17354. };
  17355. return BaseTexture;
  17356. })();
  17357. BABYLON.BaseTexture = BaseTexture;
  17358. })(BABYLON || (BABYLON = {}));
  17359. var BABYLON;
  17360. (function (BABYLON) {
  17361. var Texture = (function (_super) {
  17362. __extends(Texture, _super);
  17363. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17364. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17365. if (onLoad === void 0) { onLoad = null; }
  17366. if (onError === void 0) { onError = null; }
  17367. if (buffer === void 0) { buffer = null; }
  17368. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17369. _super.call(this, scene);
  17370. this.uOffset = 0;
  17371. this.vOffset = 0;
  17372. this.uScale = 1.0;
  17373. this.vScale = 1.0;
  17374. this.uAng = 0;
  17375. this.vAng = 0;
  17376. this.wAng = 0;
  17377. this.name = url;
  17378. this.url = url;
  17379. this._noMipmap = noMipmap;
  17380. this._invertY = invertY;
  17381. this._samplingMode = samplingMode;
  17382. this._buffer = buffer;
  17383. this._deleteBuffer = deleteBuffer;
  17384. if (!url) {
  17385. return;
  17386. }
  17387. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17388. if (!this._texture) {
  17389. if (!scene.useDelayedTextureLoading) {
  17390. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17391. if (deleteBuffer) {
  17392. delete this._buffer;
  17393. }
  17394. }
  17395. else {
  17396. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17397. }
  17398. }
  17399. else {
  17400. BABYLON.Tools.SetImmediate(function () {
  17401. if (onLoad) {
  17402. onLoad();
  17403. }
  17404. });
  17405. }
  17406. }
  17407. Texture.prototype.delayLoad = function () {
  17408. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17409. return;
  17410. }
  17411. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17412. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17413. if (!this._texture) {
  17414. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17415. if (this._deleteBuffer) {
  17416. delete this._buffer;
  17417. }
  17418. }
  17419. };
  17420. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17421. if (!this._texture) {
  17422. return;
  17423. }
  17424. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17425. };
  17426. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17427. x *= this.uScale;
  17428. y *= this.vScale;
  17429. x -= 0.5 * this.uScale;
  17430. y -= 0.5 * this.vScale;
  17431. z -= 0.5;
  17432. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17433. t.x += 0.5 * this.uScale + this.uOffset;
  17434. t.y += 0.5 * this.vScale + this.vOffset;
  17435. t.z += 0.5;
  17436. };
  17437. Texture.prototype.getTextureMatrix = function () {
  17438. if (this.uOffset === this._cachedUOffset &&
  17439. this.vOffset === this._cachedVOffset &&
  17440. this.uScale === this._cachedUScale &&
  17441. this.vScale === this._cachedVScale &&
  17442. this.uAng === this._cachedUAng &&
  17443. this.vAng === this._cachedVAng &&
  17444. this.wAng === this._cachedWAng) {
  17445. return this._cachedTextureMatrix;
  17446. }
  17447. this._cachedUOffset = this.uOffset;
  17448. this._cachedVOffset = this.vOffset;
  17449. this._cachedUScale = this.uScale;
  17450. this._cachedVScale = this.vScale;
  17451. this._cachedUAng = this.uAng;
  17452. this._cachedVAng = this.vAng;
  17453. this._cachedWAng = this.wAng;
  17454. if (!this._cachedTextureMatrix) {
  17455. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17456. this._rowGenerationMatrix = new BABYLON.Matrix();
  17457. this._t0 = BABYLON.Vector3.Zero();
  17458. this._t1 = BABYLON.Vector3.Zero();
  17459. this._t2 = BABYLON.Vector3.Zero();
  17460. }
  17461. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17462. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17463. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17464. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17465. this._t1.subtractInPlace(this._t0);
  17466. this._t2.subtractInPlace(this._t0);
  17467. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17468. this._cachedTextureMatrix.m[0] = this._t1.x;
  17469. this._cachedTextureMatrix.m[1] = this._t1.y;
  17470. this._cachedTextureMatrix.m[2] = this._t1.z;
  17471. this._cachedTextureMatrix.m[4] = this._t2.x;
  17472. this._cachedTextureMatrix.m[5] = this._t2.y;
  17473. this._cachedTextureMatrix.m[6] = this._t2.z;
  17474. this._cachedTextureMatrix.m[8] = this._t0.x;
  17475. this._cachedTextureMatrix.m[9] = this._t0.y;
  17476. this._cachedTextureMatrix.m[10] = this._t0.z;
  17477. return this._cachedTextureMatrix;
  17478. };
  17479. Texture.prototype.getReflectionTextureMatrix = function () {
  17480. if (this.uOffset === this._cachedUOffset &&
  17481. this.vOffset === this._cachedVOffset &&
  17482. this.uScale === this._cachedUScale &&
  17483. this.vScale === this._cachedVScale &&
  17484. this.coordinatesMode === this._cachedCoordinatesMode) {
  17485. return this._cachedTextureMatrix;
  17486. }
  17487. if (!this._cachedTextureMatrix) {
  17488. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17489. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17490. }
  17491. this._cachedCoordinatesMode = this.coordinatesMode;
  17492. switch (this.coordinatesMode) {
  17493. case Texture.PLANAR_MODE:
  17494. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17495. this._cachedTextureMatrix[0] = this.uScale;
  17496. this._cachedTextureMatrix[5] = this.vScale;
  17497. this._cachedTextureMatrix[12] = this.uOffset;
  17498. this._cachedTextureMatrix[13] = this.vOffset;
  17499. break;
  17500. case Texture.PROJECTION_MODE:
  17501. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17502. this._projectionModeMatrix.m[0] = 0.5;
  17503. this._projectionModeMatrix.m[5] = -0.5;
  17504. this._projectionModeMatrix.m[10] = 0.0;
  17505. this._projectionModeMatrix.m[12] = 0.5;
  17506. this._projectionModeMatrix.m[13] = 0.5;
  17507. this._projectionModeMatrix.m[14] = 1.0;
  17508. this._projectionModeMatrix.m[15] = 1.0;
  17509. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17510. break;
  17511. default:
  17512. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17513. break;
  17514. }
  17515. return this._cachedTextureMatrix;
  17516. };
  17517. Texture.prototype.clone = function () {
  17518. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17519. // Base texture
  17520. newTexture.hasAlpha = this.hasAlpha;
  17521. newTexture.level = this.level;
  17522. newTexture.wrapU = this.wrapU;
  17523. newTexture.wrapV = this.wrapV;
  17524. newTexture.coordinatesIndex = this.coordinatesIndex;
  17525. newTexture.coordinatesMode = this.coordinatesMode;
  17526. // Texture
  17527. newTexture.uOffset = this.uOffset;
  17528. newTexture.vOffset = this.vOffset;
  17529. newTexture.uScale = this.uScale;
  17530. newTexture.vScale = this.vScale;
  17531. newTexture.uAng = this.uAng;
  17532. newTexture.vAng = this.vAng;
  17533. newTexture.wAng = this.wAng;
  17534. return newTexture;
  17535. };
  17536. Texture.prototype.serialize = function () {
  17537. if (!this.name) {
  17538. return null;
  17539. }
  17540. var serializationObject = _super.prototype.serialize.call(this);
  17541. serializationObject.uOffset = this.uOffset;
  17542. serializationObject.vOffset = this.vOffset;
  17543. serializationObject.uScale = this.uScale;
  17544. serializationObject.vScale = this.vScale;
  17545. serializationObject.uAng = this.uAng;
  17546. serializationObject.vAng = this.vAng;
  17547. serializationObject.wAng = this.wAng;
  17548. return serializationObject;
  17549. };
  17550. // Statics
  17551. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17552. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17553. if (onLoad === void 0) { onLoad = null; }
  17554. if (onError === void 0) { onError = null; }
  17555. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17556. };
  17557. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17558. if (parsedTexture.isCube) {
  17559. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17560. }
  17561. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17562. return null;
  17563. }
  17564. var texture;
  17565. if (parsedTexture.mirrorPlane) {
  17566. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17567. texture._waitingRenderList = parsedTexture.renderList;
  17568. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17569. }
  17570. else if (parsedTexture.isRenderTarget) {
  17571. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17572. texture._waitingRenderList = parsedTexture.renderList;
  17573. }
  17574. else {
  17575. if (parsedTexture.base64String) {
  17576. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17577. }
  17578. else {
  17579. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17580. }
  17581. }
  17582. texture.name = parsedTexture.name;
  17583. texture.hasAlpha = parsedTexture.hasAlpha;
  17584. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17585. texture.level = parsedTexture.level;
  17586. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17587. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17588. texture.uOffset = parsedTexture.uOffset;
  17589. texture.vOffset = parsedTexture.vOffset;
  17590. texture.uScale = parsedTexture.uScale;
  17591. texture.vScale = parsedTexture.vScale;
  17592. texture.uAng = parsedTexture.uAng;
  17593. texture.vAng = parsedTexture.vAng;
  17594. texture.wAng = parsedTexture.wAng;
  17595. texture.wrapU = parsedTexture.wrapU;
  17596. texture.wrapV = parsedTexture.wrapV;
  17597. // Animations
  17598. if (parsedTexture.animations) {
  17599. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17600. var parsedAnimation = parsedTexture.animations[animationIndex];
  17601. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17602. }
  17603. }
  17604. return texture;
  17605. };
  17606. // Constants
  17607. Texture.NEAREST_SAMPLINGMODE = 1;
  17608. Texture.BILINEAR_SAMPLINGMODE = 2;
  17609. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17610. Texture.EXPLICIT_MODE = 0;
  17611. Texture.SPHERICAL_MODE = 1;
  17612. Texture.PLANAR_MODE = 2;
  17613. Texture.CUBIC_MODE = 3;
  17614. Texture.PROJECTION_MODE = 4;
  17615. Texture.SKYBOX_MODE = 5;
  17616. Texture.INVCUBIC_MODE = 6;
  17617. Texture.EQUIRECTANGULAR_MODE = 7;
  17618. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17619. Texture.CLAMP_ADDRESSMODE = 0;
  17620. Texture.WRAP_ADDRESSMODE = 1;
  17621. Texture.MIRROR_ADDRESSMODE = 2;
  17622. return Texture;
  17623. })(BABYLON.BaseTexture);
  17624. BABYLON.Texture = Texture;
  17625. })(BABYLON || (BABYLON = {}));
  17626. var BABYLON;
  17627. (function (BABYLON) {
  17628. var CubeTexture = (function (_super) {
  17629. __extends(CubeTexture, _super);
  17630. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17631. _super.call(this, scene);
  17632. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17633. this.name = rootUrl;
  17634. this.url = rootUrl;
  17635. this._noMipmap = noMipmap;
  17636. this.hasAlpha = false;
  17637. if (!rootUrl && !files) {
  17638. return;
  17639. }
  17640. this._texture = this._getFromCache(rootUrl, noMipmap);
  17641. if (!files) {
  17642. if (!extensions) {
  17643. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17644. }
  17645. files = [];
  17646. for (var index = 0; index < extensions.length; index++) {
  17647. files.push(rootUrl + extensions[index]);
  17648. }
  17649. this._extensions = extensions;
  17650. }
  17651. this._files = files;
  17652. if (!this._texture) {
  17653. if (!scene.useDelayedTextureLoading) {
  17654. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17655. }
  17656. else {
  17657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17658. }
  17659. }
  17660. this.isCube = true;
  17661. this._textureMatrix = BABYLON.Matrix.Identity();
  17662. }
  17663. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17664. return new CubeTexture("", scene, null, noMipmap, files);
  17665. };
  17666. CubeTexture.prototype.clone = function () {
  17667. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17668. // Base texture
  17669. newTexture.level = this.level;
  17670. newTexture.wrapU = this.wrapU;
  17671. newTexture.wrapV = this.wrapV;
  17672. newTexture.coordinatesIndex = this.coordinatesIndex;
  17673. newTexture.coordinatesMode = this.coordinatesMode;
  17674. return newTexture;
  17675. };
  17676. // Methods
  17677. CubeTexture.prototype.delayLoad = function () {
  17678. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17679. return;
  17680. }
  17681. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17682. this._texture = this._getFromCache(this.url, this._noMipmap);
  17683. if (!this._texture) {
  17684. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17685. }
  17686. };
  17687. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17688. return this._textureMatrix;
  17689. };
  17690. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17691. var texture = null;
  17692. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17693. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17694. texture.name = parsedTexture.name;
  17695. texture.hasAlpha = parsedTexture.hasAlpha;
  17696. texture.level = parsedTexture.level;
  17697. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17698. }
  17699. return texture;
  17700. };
  17701. CubeTexture.prototype.serialize = function () {
  17702. if (!this.name) {
  17703. return null;
  17704. }
  17705. var serializationObject = {};
  17706. serializationObject.name = this.name;
  17707. serializationObject.hasAlpha = this.hasAlpha;
  17708. serializationObject.isCube = true;
  17709. serializationObject.level = this.level;
  17710. serializationObject.coordinatesMode = this.coordinatesMode;
  17711. return serializationObject;
  17712. };
  17713. return CubeTexture;
  17714. })(BABYLON.BaseTexture);
  17715. BABYLON.CubeTexture = CubeTexture;
  17716. })(BABYLON || (BABYLON = {}));
  17717. var BABYLON;
  17718. (function (BABYLON) {
  17719. var RenderTargetTexture = (function (_super) {
  17720. __extends(RenderTargetTexture, _super);
  17721. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17722. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17723. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17724. if (isCube === void 0) { isCube = false; }
  17725. _super.call(this, null, scene, !generateMipMaps);
  17726. this.isCube = isCube;
  17727. this.renderList = new Array();
  17728. this.renderParticles = true;
  17729. this.renderSprites = false;
  17730. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17731. this._currentRefreshId = -1;
  17732. this._refreshRate = 1;
  17733. this.name = name;
  17734. this.isRenderTarget = true;
  17735. this._size = size;
  17736. this._generateMipMaps = generateMipMaps;
  17737. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17738. if (isCube) {
  17739. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17740. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17741. this._textureMatrix = BABYLON.Matrix.Identity();
  17742. }
  17743. else {
  17744. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17745. }
  17746. // Rendering groups
  17747. this._renderingManager = new BABYLON.RenderingManager(scene);
  17748. }
  17749. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17750. get: function () {
  17751. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17757. get: function () {
  17758. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17764. get: function () {
  17765. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17771. this._currentRefreshId = -1;
  17772. };
  17773. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17774. get: function () {
  17775. return this._refreshRate;
  17776. },
  17777. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17778. set: function (value) {
  17779. this._refreshRate = value;
  17780. this.resetRefreshCounter();
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. RenderTargetTexture.prototype._shouldRender = function () {
  17786. if (this._currentRefreshId === -1) {
  17787. this._currentRefreshId = 1;
  17788. return true;
  17789. }
  17790. if (this.refreshRate === this._currentRefreshId) {
  17791. this._currentRefreshId = 1;
  17792. return true;
  17793. }
  17794. this._currentRefreshId++;
  17795. return false;
  17796. };
  17797. RenderTargetTexture.prototype.isReady = function () {
  17798. if (!this.getScene().renderTargetsEnabled) {
  17799. return false;
  17800. }
  17801. return _super.prototype.isReady.call(this);
  17802. };
  17803. RenderTargetTexture.prototype.getRenderSize = function () {
  17804. return this._size;
  17805. };
  17806. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17807. get: function () {
  17808. return true;
  17809. },
  17810. enumerable: true,
  17811. configurable: true
  17812. });
  17813. RenderTargetTexture.prototype.scale = function (ratio) {
  17814. var newSize = this._size * ratio;
  17815. this.resize(newSize, this._generateMipMaps);
  17816. };
  17817. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17818. if (this.isCube) {
  17819. return this._textureMatrix;
  17820. }
  17821. return _super.prototype.getReflectionTextureMatrix.call(this);
  17822. };
  17823. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17824. this.releaseInternalTexture();
  17825. if (this.isCube) {
  17826. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17827. }
  17828. else {
  17829. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17830. }
  17831. };
  17832. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17833. var scene = this.getScene();
  17834. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17835. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17836. }
  17837. if (this._waitingRenderList) {
  17838. this.renderList = [];
  17839. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17840. var id = this._waitingRenderList[index];
  17841. this.renderList.push(scene.getMeshByID(id));
  17842. }
  17843. delete this._waitingRenderList;
  17844. }
  17845. if (this.renderList && this.renderList.length === 0) {
  17846. return;
  17847. }
  17848. // Prepare renderingManager
  17849. this._renderingManager.reset();
  17850. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17851. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17852. var mesh = currentRenderList[meshIndex];
  17853. if (mesh) {
  17854. if (!mesh.isReady()) {
  17855. // Reset _currentRefreshId
  17856. this.resetRefreshCounter();
  17857. continue;
  17858. }
  17859. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17860. mesh._activate(scene.getRenderId());
  17861. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17862. var subMesh = mesh.subMeshes[subIndex];
  17863. scene._activeIndices += subMesh.indexCount;
  17864. this._renderingManager.dispatch(subMesh);
  17865. }
  17866. }
  17867. }
  17868. }
  17869. if (this.isCube) {
  17870. for (var face = 0; face < 6; face++) {
  17871. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17872. scene.incrementRenderId();
  17873. }
  17874. }
  17875. else {
  17876. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17877. }
  17878. if (this.onAfterUnbind) {
  17879. this.onAfterUnbind();
  17880. }
  17881. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17882. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17883. }
  17884. scene.resetCachedMaterial();
  17885. };
  17886. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17887. var scene = this.getScene();
  17888. var engine = scene.getEngine();
  17889. // Bind
  17890. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17891. if (this.isCube) {
  17892. engine.bindFramebuffer(this._texture, faceIndex);
  17893. }
  17894. else {
  17895. engine.bindFramebuffer(this._texture);
  17896. }
  17897. }
  17898. if (this.onBeforeRender) {
  17899. this.onBeforeRender(faceIndex);
  17900. }
  17901. // Clear
  17902. if (this.onClear) {
  17903. this.onClear(engine);
  17904. }
  17905. else {
  17906. engine.clear(scene.clearColor, true, true);
  17907. }
  17908. if (!this._doNotChangeAspectRatio) {
  17909. scene.updateTransformMatrix(true);
  17910. }
  17911. // Render
  17912. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17913. if (useCameraPostProcess) {
  17914. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17915. }
  17916. if (!this._doNotChangeAspectRatio) {
  17917. scene.updateTransformMatrix(true);
  17918. }
  17919. if (this.onAfterRender) {
  17920. this.onAfterRender(faceIndex);
  17921. }
  17922. // Dump ?
  17923. if (dumpForDebug) {
  17924. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17925. }
  17926. // Unbind
  17927. if (!this.isCube || faceIndex === 5) {
  17928. if (this.isCube) {
  17929. if (faceIndex === 5) {
  17930. engine.generateMipMapsForCubemap(this._texture);
  17931. }
  17932. }
  17933. engine.unBindFramebuffer(this._texture, this.isCube);
  17934. }
  17935. };
  17936. RenderTargetTexture.prototype.clone = function () {
  17937. var textureSize = this.getSize();
  17938. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17939. // Base texture
  17940. newTexture.hasAlpha = this.hasAlpha;
  17941. newTexture.level = this.level;
  17942. // RenderTarget Texture
  17943. newTexture.coordinatesMode = this.coordinatesMode;
  17944. newTexture.renderList = this.renderList.slice(0);
  17945. return newTexture;
  17946. };
  17947. RenderTargetTexture.prototype.serialize = function () {
  17948. if (!this.name) {
  17949. return null;
  17950. }
  17951. var serializationObject = _super.prototype.serialize.call(this);
  17952. serializationObject.renderTargetSize = this.getRenderSize();
  17953. serializationObject.renderList = [];
  17954. for (var index = 0; index < this.renderList.length; index++) {
  17955. serializationObject.renderList.push(this.renderList[index].id);
  17956. }
  17957. return serializationObject;
  17958. };
  17959. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17960. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17961. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17962. return RenderTargetTexture;
  17963. })(BABYLON.Texture);
  17964. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17965. })(BABYLON || (BABYLON = {}));
  17966. var BABYLON;
  17967. (function (BABYLON) {
  17968. var ProceduralTexture = (function (_super) {
  17969. __extends(ProceduralTexture, _super);
  17970. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  17971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17972. if (isCube === void 0) { isCube = false; }
  17973. _super.call(this, null, scene, !generateMipMaps);
  17974. this.isCube = isCube;
  17975. this.isEnabled = true;
  17976. this._currentRefreshId = -1;
  17977. this._refreshRate = 1;
  17978. this._vertexDeclaration = [2];
  17979. this._vertexStrideSize = 2 * 4;
  17980. this._uniforms = new Array();
  17981. this._samplers = new Array();
  17982. this._textures = new Array();
  17983. this._floats = new Array();
  17984. this._floatsArrays = {};
  17985. this._colors3 = new Array();
  17986. this._colors4 = new Array();
  17987. this._vectors2 = new Array();
  17988. this._vectors3 = new Array();
  17989. this._matrices = new Array();
  17990. this._fallbackTextureUsed = false;
  17991. scene._proceduralTextures.push(this);
  17992. this.name = name;
  17993. this.isRenderTarget = true;
  17994. this._size = size;
  17995. this._generateMipMaps = generateMipMaps;
  17996. this.setFragment(fragment);
  17997. this._fallbackTexture = fallbackTexture;
  17998. if (isCube) {
  17999. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18000. this.setFloat("face", 0);
  18001. }
  18002. else {
  18003. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18004. }
  18005. // VBO
  18006. var vertices = [];
  18007. vertices.push(1, 1);
  18008. vertices.push(-1, 1);
  18009. vertices.push(-1, -1);
  18010. vertices.push(1, -1);
  18011. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18012. // Indices
  18013. var indices = [];
  18014. indices.push(0);
  18015. indices.push(1);
  18016. indices.push(2);
  18017. indices.push(0);
  18018. indices.push(2);
  18019. indices.push(3);
  18020. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18021. }
  18022. ProceduralTexture.prototype.reset = function () {
  18023. if (this._effect === undefined) {
  18024. return;
  18025. }
  18026. var engine = this.getScene().getEngine();
  18027. engine._releaseEffect(this._effect);
  18028. };
  18029. ProceduralTexture.prototype.isReady = function () {
  18030. var _this = this;
  18031. var engine = this.getScene().getEngine();
  18032. var shaders;
  18033. if (!this._fragment) {
  18034. return false;
  18035. }
  18036. if (this._fallbackTextureUsed) {
  18037. return true;
  18038. }
  18039. if (this._fragment.fragmentElement !== undefined) {
  18040. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18041. }
  18042. else {
  18043. shaders = { vertex: "procedural", fragment: this._fragment };
  18044. }
  18045. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18046. _this.releaseInternalTexture();
  18047. if (_this._fallbackTexture) {
  18048. _this._texture = _this._fallbackTexture._texture;
  18049. _this._texture.references++;
  18050. }
  18051. _this._fallbackTextureUsed = true;
  18052. });
  18053. return this._effect.isReady();
  18054. };
  18055. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18056. this._currentRefreshId = -1;
  18057. };
  18058. ProceduralTexture.prototype.setFragment = function (fragment) {
  18059. this._fragment = fragment;
  18060. };
  18061. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18062. get: function () {
  18063. return this._refreshRate;
  18064. },
  18065. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18066. set: function (value) {
  18067. this._refreshRate = value;
  18068. this.resetRefreshCounter();
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. ProceduralTexture.prototype._shouldRender = function () {
  18074. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18075. return false;
  18076. }
  18077. if (this._fallbackTextureUsed) {
  18078. return false;
  18079. }
  18080. if (this._currentRefreshId === -1) {
  18081. this._currentRefreshId = 1;
  18082. return true;
  18083. }
  18084. if (this.refreshRate === this._currentRefreshId) {
  18085. this._currentRefreshId = 1;
  18086. return true;
  18087. }
  18088. this._currentRefreshId++;
  18089. return false;
  18090. };
  18091. ProceduralTexture.prototype.getRenderSize = function () {
  18092. return this._size;
  18093. };
  18094. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18095. if (this._fallbackTextureUsed) {
  18096. return;
  18097. }
  18098. this.releaseInternalTexture();
  18099. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18100. };
  18101. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18102. if (this._uniforms.indexOf(uniformName) === -1) {
  18103. this._uniforms.push(uniformName);
  18104. }
  18105. };
  18106. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18107. if (this._samplers.indexOf(name) === -1) {
  18108. this._samplers.push(name);
  18109. }
  18110. this._textures[name] = texture;
  18111. return this;
  18112. };
  18113. ProceduralTexture.prototype.setFloat = function (name, value) {
  18114. this._checkUniform(name);
  18115. this._floats[name] = value;
  18116. return this;
  18117. };
  18118. ProceduralTexture.prototype.setFloats = function (name, value) {
  18119. this._checkUniform(name);
  18120. this._floatsArrays[name] = value;
  18121. return this;
  18122. };
  18123. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18124. this._checkUniform(name);
  18125. this._colors3[name] = value;
  18126. return this;
  18127. };
  18128. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18129. this._checkUniform(name);
  18130. this._colors4[name] = value;
  18131. return this;
  18132. };
  18133. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18134. this._checkUniform(name);
  18135. this._vectors2[name] = value;
  18136. return this;
  18137. };
  18138. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18139. this._checkUniform(name);
  18140. this._vectors3[name] = value;
  18141. return this;
  18142. };
  18143. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18144. this._checkUniform(name);
  18145. this._matrices[name] = value;
  18146. return this;
  18147. };
  18148. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18149. var scene = this.getScene();
  18150. var engine = scene.getEngine();
  18151. // Render
  18152. engine.enableEffect(this._effect);
  18153. engine.setState(false);
  18154. // Texture
  18155. for (var name in this._textures) {
  18156. this._effect.setTexture(name, this._textures[name]);
  18157. }
  18158. // Float
  18159. for (name in this._floats) {
  18160. this._effect.setFloat(name, this._floats[name]);
  18161. }
  18162. // Floats
  18163. for (name in this._floatsArrays) {
  18164. this._effect.setArray(name, this._floatsArrays[name]);
  18165. }
  18166. // Color3
  18167. for (name in this._colors3) {
  18168. this._effect.setColor3(name, this._colors3[name]);
  18169. }
  18170. // Color4
  18171. for (name in this._colors4) {
  18172. var color = this._colors4[name];
  18173. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18174. }
  18175. // Vector2
  18176. for (name in this._vectors2) {
  18177. this._effect.setVector2(name, this._vectors2[name]);
  18178. }
  18179. // Vector3
  18180. for (name in this._vectors3) {
  18181. this._effect.setVector3(name, this._vectors3[name]);
  18182. }
  18183. // Matrix
  18184. for (name in this._matrices) {
  18185. this._effect.setMatrix(name, this._matrices[name]);
  18186. }
  18187. // VBOs
  18188. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18189. if (this.isCube) {
  18190. for (var face = 0; face < 6; face++) {
  18191. engine.bindFramebuffer(this._texture, face);
  18192. this._effect.setFloat("face", face);
  18193. // Clear
  18194. engine.clear(scene.clearColor, true, true);
  18195. // Draw order
  18196. engine.draw(true, 0, 6);
  18197. // Mipmaps
  18198. if (face === 5) {
  18199. engine.generateMipMapsForCubemap(this._texture);
  18200. }
  18201. }
  18202. }
  18203. else {
  18204. engine.bindFramebuffer(this._texture);
  18205. // Clear
  18206. engine.clear(scene.clearColor, true, true);
  18207. // Draw order
  18208. engine.draw(true, 0, 6);
  18209. }
  18210. // Unbind
  18211. engine.unBindFramebuffer(this._texture, this.isCube);
  18212. if (this.onGenerated) {
  18213. this.onGenerated();
  18214. }
  18215. };
  18216. ProceduralTexture.prototype.clone = function () {
  18217. var textureSize = this.getSize();
  18218. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18219. // Base texture
  18220. newTexture.hasAlpha = this.hasAlpha;
  18221. newTexture.level = this.level;
  18222. // RenderTarget Texture
  18223. newTexture.coordinatesMode = this.coordinatesMode;
  18224. return newTexture;
  18225. };
  18226. ProceduralTexture.prototype.dispose = function () {
  18227. var index = this.getScene()._proceduralTextures.indexOf(this);
  18228. if (index >= 0) {
  18229. this.getScene()._proceduralTextures.splice(index, 1);
  18230. }
  18231. _super.prototype.dispose.call(this);
  18232. };
  18233. return ProceduralTexture;
  18234. })(BABYLON.Texture);
  18235. BABYLON.ProceduralTexture = ProceduralTexture;
  18236. })(BABYLON || (BABYLON = {}));
  18237. var BABYLON;
  18238. (function (BABYLON) {
  18239. var MirrorTexture = (function (_super) {
  18240. __extends(MirrorTexture, _super);
  18241. function MirrorTexture(name, size, scene, generateMipMaps) {
  18242. var _this = this;
  18243. _super.call(this, name, size, scene, generateMipMaps, true);
  18244. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18245. this._transformMatrix = BABYLON.Matrix.Zero();
  18246. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18247. this.onBeforeRender = function () {
  18248. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18249. _this._savedViewMatrix = scene.getViewMatrix();
  18250. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18251. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18252. scene.clipPlane = _this.mirrorPlane;
  18253. scene.getEngine().cullBackFaces = false;
  18254. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18255. };
  18256. this.onAfterRender = function () {
  18257. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18258. scene.getEngine().cullBackFaces = true;
  18259. scene._mirroredCameraPosition = null;
  18260. delete scene.clipPlane;
  18261. };
  18262. }
  18263. MirrorTexture.prototype.clone = function () {
  18264. var textureSize = this.getSize();
  18265. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18266. // Base texture
  18267. newTexture.hasAlpha = this.hasAlpha;
  18268. newTexture.level = this.level;
  18269. // Mirror Texture
  18270. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18271. newTexture.renderList = this.renderList.slice(0);
  18272. return newTexture;
  18273. };
  18274. MirrorTexture.prototype.serialize = function () {
  18275. if (!this.name) {
  18276. return null;
  18277. }
  18278. var serializationObject = _super.prototype.serialize.call(this);
  18279. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18280. return serializationObject;
  18281. };
  18282. return MirrorTexture;
  18283. })(BABYLON.RenderTargetTexture);
  18284. BABYLON.MirrorTexture = MirrorTexture;
  18285. })(BABYLON || (BABYLON = {}));
  18286. var BABYLON;
  18287. (function (BABYLON) {
  18288. /**
  18289. * Creates a refraction texture used by refraction channel of the standard material.
  18290. * @param name the texture name
  18291. * @param size size of the underlying texture
  18292. * @param scene root scene
  18293. */
  18294. var RefractionTexture = (function (_super) {
  18295. __extends(RefractionTexture, _super);
  18296. function RefractionTexture(name, size, scene, generateMipMaps) {
  18297. var _this = this;
  18298. _super.call(this, name, size, scene, generateMipMaps, true);
  18299. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18300. this.depth = 2.0;
  18301. this.onBeforeRender = function () {
  18302. scene.clipPlane = _this.refractionPlane;
  18303. };
  18304. this.onAfterRender = function () {
  18305. delete scene.clipPlane;
  18306. };
  18307. }
  18308. RefractionTexture.prototype.clone = function () {
  18309. var textureSize = this.getSize();
  18310. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18311. // Base texture
  18312. newTexture.hasAlpha = this.hasAlpha;
  18313. newTexture.level = this.level;
  18314. // Refraction Texture
  18315. newTexture.refractionPlane = this.refractionPlane.clone();
  18316. newTexture.renderList = this.renderList.slice(0);
  18317. newTexture.depth = this.depth;
  18318. return newTexture;
  18319. };
  18320. RefractionTexture.prototype.serialize = function () {
  18321. if (!this.name) {
  18322. return null;
  18323. }
  18324. var serializationObject = _super.prototype.serialize.call(this);
  18325. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18326. serializationObject.depth = this.depth;
  18327. return serializationObject;
  18328. };
  18329. return RefractionTexture;
  18330. })(BABYLON.RenderTargetTexture);
  18331. BABYLON.RefractionTexture = RefractionTexture;
  18332. })(BABYLON || (BABYLON = {}));
  18333. var BABYLON;
  18334. (function (BABYLON) {
  18335. var DynamicTexture = (function (_super) {
  18336. __extends(DynamicTexture, _super);
  18337. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18339. _super.call(this, null, scene, !generateMipMaps);
  18340. this.name = name;
  18341. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18342. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18343. this._generateMipMaps = generateMipMaps;
  18344. if (options.getContext) {
  18345. this._canvas = options;
  18346. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18347. }
  18348. else {
  18349. this._canvas = document.createElement("canvas");
  18350. if (options.width) {
  18351. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18352. }
  18353. else {
  18354. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18355. }
  18356. }
  18357. var textureSize = this.getSize();
  18358. this._canvas.width = textureSize.width;
  18359. this._canvas.height = textureSize.height;
  18360. this._context = this._canvas.getContext("2d");
  18361. }
  18362. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18363. get: function () {
  18364. return true;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. DynamicTexture.prototype.scale = function (ratio) {
  18370. var textureSize = this.getSize();
  18371. textureSize.width *= ratio;
  18372. textureSize.height *= ratio;
  18373. this._canvas.width = textureSize.width;
  18374. this._canvas.height = textureSize.height;
  18375. this.releaseInternalTexture();
  18376. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18377. };
  18378. DynamicTexture.prototype.getContext = function () {
  18379. return this._context;
  18380. };
  18381. DynamicTexture.prototype.clear = function () {
  18382. var size = this.getSize();
  18383. this._context.fillRect(0, 0, size.width, size.height);
  18384. };
  18385. DynamicTexture.prototype.update = function (invertY) {
  18386. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18387. };
  18388. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18389. if (update === void 0) { update = true; }
  18390. var size = this.getSize();
  18391. if (clearColor) {
  18392. this._context.fillStyle = clearColor;
  18393. this._context.fillRect(0, 0, size.width, size.height);
  18394. }
  18395. this._context.font = font;
  18396. if (x === null) {
  18397. var textSize = this._context.measureText(text);
  18398. x = (size.width - textSize.width) / 2;
  18399. }
  18400. this._context.fillStyle = color;
  18401. this._context.fillText(text, x, y);
  18402. if (update) {
  18403. this.update(invertY);
  18404. }
  18405. };
  18406. DynamicTexture.prototype.clone = function () {
  18407. var textureSize = this.getSize();
  18408. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18409. // Base texture
  18410. newTexture.hasAlpha = this.hasAlpha;
  18411. newTexture.level = this.level;
  18412. // Dynamic Texture
  18413. newTexture.wrapU = this.wrapU;
  18414. newTexture.wrapV = this.wrapV;
  18415. return newTexture;
  18416. };
  18417. return DynamicTexture;
  18418. })(BABYLON.Texture);
  18419. BABYLON.DynamicTexture = DynamicTexture;
  18420. })(BABYLON || (BABYLON = {}));
  18421. var BABYLON;
  18422. (function (BABYLON) {
  18423. var VideoTexture = (function (_super) {
  18424. __extends(VideoTexture, _super);
  18425. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18426. var _this = this;
  18427. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18428. if (invertY === void 0) { invertY = false; }
  18429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18430. _super.call(this, null, scene, !generateMipMaps, invertY);
  18431. this._autoLaunch = true;
  18432. this.name = name;
  18433. this.video = document.createElement("video");
  18434. this.video.autoplay = false;
  18435. this.video.loop = true;
  18436. this.video.addEventListener("canplaythrough", function () {
  18437. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18438. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18439. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18440. }
  18441. else {
  18442. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18443. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18444. generateMipMaps = false;
  18445. }
  18446. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18447. _this._texture.isReady = true;
  18448. });
  18449. urls.forEach(function (url) {
  18450. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18451. var source = document.createElement("source");
  18452. source.src = url;
  18453. _this.video.appendChild(source);
  18454. });
  18455. this._lastUpdate = BABYLON.Tools.Now;
  18456. }
  18457. VideoTexture.prototype.update = function () {
  18458. if (this._autoLaunch) {
  18459. this._autoLaunch = false;
  18460. this.video.play();
  18461. }
  18462. var now = BABYLON.Tools.Now;
  18463. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18464. return false;
  18465. }
  18466. this._lastUpdate = now;
  18467. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18468. return true;
  18469. };
  18470. return VideoTexture;
  18471. })(BABYLON.Texture);
  18472. BABYLON.VideoTexture = VideoTexture;
  18473. })(BABYLON || (BABYLON = {}));
  18474. var BABYLON;
  18475. (function (BABYLON) {
  18476. var CustomProceduralTexture = (function (_super) {
  18477. __extends(CustomProceduralTexture, _super);
  18478. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18479. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18480. this._animate = true;
  18481. this._time = 0;
  18482. this._texturePath = texturePath;
  18483. //Try to load json
  18484. this.loadJson(texturePath);
  18485. this.refreshRate = 1;
  18486. }
  18487. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18488. var _this = this;
  18489. var that = this;
  18490. function noConfigFile() {
  18491. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18492. try {
  18493. that.setFragment(that._texturePath);
  18494. }
  18495. catch (ex) {
  18496. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18497. }
  18498. }
  18499. var configFileUrl = jsonUrl + "/config.json";
  18500. var xhr = new XMLHttpRequest();
  18501. xhr.open("GET", configFileUrl, true);
  18502. xhr.addEventListener("load", function () {
  18503. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18504. try {
  18505. _this._config = JSON.parse(xhr.response);
  18506. _this.updateShaderUniforms();
  18507. _this.updateTextures();
  18508. _this.setFragment(_this._texturePath + "/custom");
  18509. _this._animate = _this._config.animate;
  18510. _this.refreshRate = _this._config.refreshrate;
  18511. }
  18512. catch (ex) {
  18513. noConfigFile();
  18514. }
  18515. }
  18516. else {
  18517. noConfigFile();
  18518. }
  18519. }, false);
  18520. xhr.addEventListener("error", function () {
  18521. noConfigFile();
  18522. }, false);
  18523. try {
  18524. xhr.send();
  18525. }
  18526. catch (ex) {
  18527. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18528. }
  18529. };
  18530. CustomProceduralTexture.prototype.isReady = function () {
  18531. if (!_super.prototype.isReady.call(this)) {
  18532. return false;
  18533. }
  18534. for (var name in this._textures) {
  18535. var texture = this._textures[name];
  18536. if (!texture.isReady()) {
  18537. return false;
  18538. }
  18539. }
  18540. return true;
  18541. };
  18542. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18543. if (this._animate) {
  18544. this._time += this.getScene().getAnimationRatio() * 0.03;
  18545. this.updateShaderUniforms();
  18546. }
  18547. _super.prototype.render.call(this, useCameraPostProcess);
  18548. };
  18549. CustomProceduralTexture.prototype.updateTextures = function () {
  18550. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18551. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18552. }
  18553. };
  18554. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18555. if (this._config) {
  18556. for (var j = 0; j < this._config.uniforms.length; j++) {
  18557. var uniform = this._config.uniforms[j];
  18558. switch (uniform.type) {
  18559. case "float":
  18560. this.setFloat(uniform.name, uniform.value);
  18561. break;
  18562. case "color3":
  18563. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18564. break;
  18565. case "color4":
  18566. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18567. break;
  18568. case "vector2":
  18569. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18570. break;
  18571. case "vector3":
  18572. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18573. break;
  18574. }
  18575. }
  18576. }
  18577. this.setFloat("time", this._time);
  18578. };
  18579. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18580. get: function () {
  18581. return this._animate;
  18582. },
  18583. set: function (value) {
  18584. this._animate = value;
  18585. },
  18586. enumerable: true,
  18587. configurable: true
  18588. });
  18589. return CustomProceduralTexture;
  18590. })(BABYLON.ProceduralTexture);
  18591. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18592. })(BABYLON || (BABYLON = {}));
  18593. var BABYLON;
  18594. (function (BABYLON) {
  18595. var EffectFallbacks = (function () {
  18596. function EffectFallbacks() {
  18597. this._defines = {};
  18598. this._currentRank = 32;
  18599. this._maxRank = -1;
  18600. }
  18601. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18602. if (!this._defines[rank]) {
  18603. if (rank < this._currentRank) {
  18604. this._currentRank = rank;
  18605. }
  18606. if (rank > this._maxRank) {
  18607. this._maxRank = rank;
  18608. }
  18609. this._defines[rank] = new Array();
  18610. }
  18611. this._defines[rank].push(define);
  18612. };
  18613. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18614. this._meshRank = rank;
  18615. this._mesh = mesh;
  18616. if (rank > this._maxRank) {
  18617. this._maxRank = rank;
  18618. }
  18619. };
  18620. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18621. get: function () {
  18622. return this._currentRank <= this._maxRank;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18628. var currentFallbacks = this._defines[this._currentRank];
  18629. for (var index = 0; index < currentFallbacks.length; index++) {
  18630. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18631. }
  18632. if (this._mesh && this._currentRank === this._meshRank) {
  18633. this._mesh.computeBonesUsingShaders = false;
  18634. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18635. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18636. }
  18637. this._currentRank++;
  18638. return currentDefines;
  18639. };
  18640. return EffectFallbacks;
  18641. })();
  18642. BABYLON.EffectFallbacks = EffectFallbacks;
  18643. var Effect = (function () {
  18644. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18645. var _this = this;
  18646. this._isReady = false;
  18647. this._compilationError = "";
  18648. this._valueCache = [];
  18649. this._engine = engine;
  18650. this.name = baseName;
  18651. this.defines = defines;
  18652. this._uniformsNames = uniformsNames.concat(samplers);
  18653. this._samplers = samplers;
  18654. this._attributesNames = attributesNames;
  18655. this.onError = onError;
  18656. this.onCompiled = onCompiled;
  18657. var vertexSource;
  18658. var fragmentSource;
  18659. if (baseName.vertexElement) {
  18660. vertexSource = document.getElementById(baseName.vertexElement);
  18661. if (!vertexSource) {
  18662. vertexSource = baseName.vertexElement;
  18663. }
  18664. }
  18665. else {
  18666. vertexSource = baseName.vertex || baseName;
  18667. }
  18668. if (baseName.fragmentElement) {
  18669. fragmentSource = document.getElementById(baseName.fragmentElement);
  18670. if (!fragmentSource) {
  18671. fragmentSource = baseName.fragmentElement;
  18672. }
  18673. }
  18674. else {
  18675. fragmentSource = baseName.fragment || baseName;
  18676. }
  18677. this._loadVertexShader(vertexSource, function (vertexCode) {
  18678. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18679. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18680. });
  18681. });
  18682. }
  18683. // Properties
  18684. Effect.prototype.isReady = function () {
  18685. return this._isReady;
  18686. };
  18687. Effect.prototype.getProgram = function () {
  18688. return this._program;
  18689. };
  18690. Effect.prototype.getAttributesNames = function () {
  18691. return this._attributesNames;
  18692. };
  18693. Effect.prototype.getAttributeLocation = function (index) {
  18694. return this._attributes[index];
  18695. };
  18696. Effect.prototype.getAttributeLocationByName = function (name) {
  18697. var index = this._attributesNames.indexOf(name);
  18698. return this._attributes[index];
  18699. };
  18700. Effect.prototype.getAttributesCount = function () {
  18701. return this._attributes.length;
  18702. };
  18703. Effect.prototype.getUniformIndex = function (uniformName) {
  18704. return this._uniformsNames.indexOf(uniformName);
  18705. };
  18706. Effect.prototype.getUniform = function (uniformName) {
  18707. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18708. };
  18709. Effect.prototype.getSamplers = function () {
  18710. return this._samplers;
  18711. };
  18712. Effect.prototype.getCompilationError = function () {
  18713. return this._compilationError;
  18714. };
  18715. // Methods
  18716. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18717. // DOM element ?
  18718. if (vertex instanceof HTMLElement) {
  18719. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18720. callback(vertexCode);
  18721. return;
  18722. }
  18723. // Is in local store ?
  18724. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18725. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18726. return;
  18727. }
  18728. var vertexShaderUrl;
  18729. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18730. vertexShaderUrl = vertex;
  18731. }
  18732. else {
  18733. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18734. }
  18735. // Vertex shader
  18736. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18737. };
  18738. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18739. // DOM element ?
  18740. if (fragment instanceof HTMLElement) {
  18741. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18742. callback(fragmentCode);
  18743. return;
  18744. }
  18745. // Is in local store ?
  18746. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18747. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18748. return;
  18749. }
  18750. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18751. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18752. return;
  18753. }
  18754. var fragmentShaderUrl;
  18755. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18756. fragmentShaderUrl = fragment;
  18757. }
  18758. else {
  18759. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18760. }
  18761. // Fragment shader
  18762. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18763. };
  18764. Effect.prototype._dumpShadersName = function () {
  18765. if (this.name.vertexElement) {
  18766. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18767. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18768. }
  18769. else if (this.name.vertex) {
  18770. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18771. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18772. }
  18773. else {
  18774. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18775. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18776. }
  18777. };
  18778. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18779. try {
  18780. var engine = this._engine;
  18781. if (!engine.getCaps().highPrecisionShaderSupported) {
  18782. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18783. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18784. }
  18785. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18786. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18787. this._attributes = engine.getAttributes(this._program, attributesNames);
  18788. for (var index = 0; index < this._samplers.length; index++) {
  18789. var sampler = this.getUniform(this._samplers[index]);
  18790. if (sampler == null) {
  18791. this._samplers.splice(index, 1);
  18792. index--;
  18793. }
  18794. }
  18795. engine.bindSamplers(this);
  18796. this._isReady = true;
  18797. if (this.onCompiled) {
  18798. this.onCompiled(this);
  18799. }
  18800. }
  18801. catch (e) {
  18802. // Is it a problem with precision?
  18803. if (e.message.indexOf("highp") !== -1) {
  18804. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18805. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18806. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18807. return;
  18808. }
  18809. // Let's go through fallbacks then
  18810. if (fallbacks && fallbacks.isMoreFallbacks) {
  18811. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18812. this._dumpShadersName();
  18813. defines = fallbacks.reduce(defines);
  18814. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18815. }
  18816. else {
  18817. BABYLON.Tools.Error("Unable to compile effect: ");
  18818. this._dumpShadersName();
  18819. BABYLON.Tools.Error("Defines: " + defines);
  18820. BABYLON.Tools.Error("Error: " + e.message);
  18821. this._compilationError = e.message;
  18822. if (this.onError) {
  18823. this.onError(this, this._compilationError);
  18824. }
  18825. }
  18826. }
  18827. };
  18828. Object.defineProperty(Effect.prototype, "isSupported", {
  18829. get: function () {
  18830. return this._compilationError === "";
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Effect.prototype._bindTexture = function (channel, texture) {
  18836. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18837. };
  18838. Effect.prototype.setTexture = function (channel, texture) {
  18839. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18840. };
  18841. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18842. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18843. };
  18844. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18845. if (!this._valueCache[uniformName]) {
  18846. this._valueCache[uniformName] = new BABYLON.Matrix();
  18847. }
  18848. for (var index = 0; index < 16; index++) {
  18849. this._valueCache[uniformName].m[index] = matrix.m[index];
  18850. }
  18851. };
  18852. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18853. if (!this._valueCache[uniformName]) {
  18854. this._valueCache[uniformName] = [x, y];
  18855. return;
  18856. }
  18857. this._valueCache[uniformName][0] = x;
  18858. this._valueCache[uniformName][1] = y;
  18859. };
  18860. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18861. if (!this._valueCache[uniformName]) {
  18862. this._valueCache[uniformName] = [x, y, z];
  18863. return;
  18864. }
  18865. this._valueCache[uniformName][0] = x;
  18866. this._valueCache[uniformName][1] = y;
  18867. this._valueCache[uniformName][2] = z;
  18868. };
  18869. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18870. if (!this._valueCache[uniformName]) {
  18871. this._valueCache[uniformName] = [x, y, z, w];
  18872. return;
  18873. }
  18874. this._valueCache[uniformName][0] = x;
  18875. this._valueCache[uniformName][1] = y;
  18876. this._valueCache[uniformName][2] = z;
  18877. this._valueCache[uniformName][3] = w;
  18878. };
  18879. Effect.prototype.setArray = function (uniformName, array) {
  18880. this._engine.setArray(this.getUniform(uniformName), array);
  18881. return this;
  18882. };
  18883. Effect.prototype.setArray2 = function (uniformName, array) {
  18884. this._engine.setArray2(this.getUniform(uniformName), array);
  18885. return this;
  18886. };
  18887. Effect.prototype.setArray3 = function (uniformName, array) {
  18888. this._engine.setArray3(this.getUniform(uniformName), array);
  18889. return this;
  18890. };
  18891. Effect.prototype.setArray4 = function (uniformName, array) {
  18892. this._engine.setArray4(this.getUniform(uniformName), array);
  18893. return this;
  18894. };
  18895. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18896. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18897. return this;
  18898. };
  18899. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18900. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18901. // return this;
  18902. // this._cacheMatrix(uniformName, matrix);
  18903. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18904. return this;
  18905. };
  18906. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18907. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18908. return this;
  18909. };
  18910. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18911. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18912. return this;
  18913. };
  18914. Effect.prototype.setFloat = function (uniformName, value) {
  18915. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18916. return this;
  18917. this._valueCache[uniformName] = value;
  18918. this._engine.setFloat(this.getUniform(uniformName), value);
  18919. return this;
  18920. };
  18921. Effect.prototype.setBool = function (uniformName, bool) {
  18922. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18923. return this;
  18924. this._valueCache[uniformName] = bool;
  18925. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18926. return this;
  18927. };
  18928. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18929. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18930. return this;
  18931. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18932. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18933. return this;
  18934. };
  18935. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18936. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18937. return this;
  18938. this._cacheFloat2(uniformName, x, y);
  18939. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18940. return this;
  18941. };
  18942. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18943. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18944. return this;
  18945. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18946. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18947. return this;
  18948. };
  18949. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18950. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18951. return this;
  18952. this._cacheFloat3(uniformName, x, y, z);
  18953. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18954. return this;
  18955. };
  18956. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18957. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18958. return this;
  18959. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18960. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18961. return this;
  18962. };
  18963. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18964. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18965. return this;
  18966. this._cacheFloat4(uniformName, x, y, z, w);
  18967. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18968. return this;
  18969. };
  18970. Effect.prototype.setColor3 = function (uniformName, color3) {
  18971. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18972. return this;
  18973. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18974. this._engine.setColor3(this.getUniform(uniformName), color3);
  18975. return this;
  18976. };
  18977. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18978. 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)
  18979. return this;
  18980. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18981. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18982. return this;
  18983. };
  18984. // Statics
  18985. Effect.ShadersStore = {};
  18986. return Effect;
  18987. })();
  18988. BABYLON.Effect = Effect;
  18989. })(BABYLON || (BABYLON = {}));
  18990. var BABYLON;
  18991. (function (BABYLON) {
  18992. var MaterialDefines = (function () {
  18993. function MaterialDefines() {
  18994. }
  18995. MaterialDefines.prototype.isEqual = function (other) {
  18996. for (var index = 0; index < this._keys.length; index++) {
  18997. var prop = this._keys[index];
  18998. if (this[prop] !== other[prop]) {
  18999. return false;
  19000. }
  19001. }
  19002. return true;
  19003. };
  19004. MaterialDefines.prototype.cloneTo = function (other) {
  19005. for (var index = 0; index < this._keys.length; index++) {
  19006. var prop = this._keys[index];
  19007. other[prop] = this[prop];
  19008. }
  19009. };
  19010. MaterialDefines.prototype.reset = function () {
  19011. for (var index = 0; index < this._keys.length; index++) {
  19012. var prop = this._keys[index];
  19013. if (typeof (this[prop]) === "number") {
  19014. this[prop] = 0;
  19015. }
  19016. else {
  19017. this[prop] = false;
  19018. }
  19019. }
  19020. };
  19021. MaterialDefines.prototype.toString = function () {
  19022. var result = "";
  19023. for (var index = 0; index < this._keys.length; index++) {
  19024. var prop = this._keys[index];
  19025. if (typeof (this[prop]) === "number") {
  19026. result += "#define " + prop + " " + this[prop] + "\n";
  19027. }
  19028. else if (this[prop]) {
  19029. result += "#define " + prop + "\n";
  19030. }
  19031. }
  19032. return result;
  19033. };
  19034. return MaterialDefines;
  19035. })();
  19036. BABYLON.MaterialDefines = MaterialDefines;
  19037. var Material = (function () {
  19038. function Material(name, scene, doNotAdd) {
  19039. this.name = name;
  19040. this.checkReadyOnEveryCall = false;
  19041. this.checkReadyOnlyOnce = false;
  19042. this.state = "";
  19043. this.alpha = 1.0;
  19044. this.backFaceCulling = true;
  19045. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19046. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19047. this.disableDepthWrite = false;
  19048. this.fogEnabled = true;
  19049. this._wasPreviouslyReady = false;
  19050. this._fillMode = Material.TriangleFillMode;
  19051. this.pointSize = 1.0;
  19052. this.zOffset = 0;
  19053. this.id = name;
  19054. this._scene = scene;
  19055. if (!doNotAdd) {
  19056. scene.materials.push(this);
  19057. }
  19058. }
  19059. Object.defineProperty(Material, "TriangleFillMode", {
  19060. get: function () {
  19061. return Material._TriangleFillMode;
  19062. },
  19063. enumerable: true,
  19064. configurable: true
  19065. });
  19066. Object.defineProperty(Material, "WireFrameFillMode", {
  19067. get: function () {
  19068. return Material._WireFrameFillMode;
  19069. },
  19070. enumerable: true,
  19071. configurable: true
  19072. });
  19073. Object.defineProperty(Material, "PointFillMode", {
  19074. get: function () {
  19075. return Material._PointFillMode;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19081. get: function () {
  19082. return Material._ClockWiseSideOrientation;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19088. get: function () {
  19089. return Material._CounterClockWiseSideOrientation;
  19090. },
  19091. enumerable: true,
  19092. configurable: true
  19093. });
  19094. Object.defineProperty(Material.prototype, "wireframe", {
  19095. get: function () {
  19096. return this._fillMode === Material.WireFrameFillMode;
  19097. },
  19098. set: function (value) {
  19099. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. Object.defineProperty(Material.prototype, "pointsCloud", {
  19105. get: function () {
  19106. return this._fillMode === Material.PointFillMode;
  19107. },
  19108. set: function (value) {
  19109. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19110. },
  19111. enumerable: true,
  19112. configurable: true
  19113. });
  19114. Object.defineProperty(Material.prototype, "fillMode", {
  19115. get: function () {
  19116. return this._fillMode;
  19117. },
  19118. set: function (value) {
  19119. this._fillMode = value;
  19120. },
  19121. enumerable: true,
  19122. configurable: true
  19123. });
  19124. Object.defineProperty(Material.prototype, "isFrozen", {
  19125. get: function () {
  19126. return this.checkReadyOnlyOnce;
  19127. },
  19128. enumerable: true,
  19129. configurable: true
  19130. });
  19131. Material.prototype.freeze = function () {
  19132. this.checkReadyOnlyOnce = true;
  19133. };
  19134. Material.prototype.unfreeze = function () {
  19135. this.checkReadyOnlyOnce = false;
  19136. };
  19137. Material.prototype.isReady = function (mesh, useInstances) {
  19138. return true;
  19139. };
  19140. Material.prototype.getEffect = function () {
  19141. return this._effect;
  19142. };
  19143. Material.prototype.getScene = function () {
  19144. return this._scene;
  19145. };
  19146. Material.prototype.needAlphaBlending = function () {
  19147. return (this.alpha < 1.0);
  19148. };
  19149. Material.prototype.needAlphaTesting = function () {
  19150. return false;
  19151. };
  19152. Material.prototype.getAlphaTestTexture = function () {
  19153. return null;
  19154. };
  19155. Material.prototype.trackCreation = function (onCompiled, onError) {
  19156. };
  19157. Material.prototype.markDirty = function () {
  19158. this._wasPreviouslyReady = false;
  19159. };
  19160. Material.prototype._preBind = function () {
  19161. var engine = this._scene.getEngine();
  19162. engine.enableEffect(this._effect);
  19163. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19164. };
  19165. Material.prototype.bind = function (world, mesh) {
  19166. this._scene._cachedMaterial = this;
  19167. if (this.onBind) {
  19168. this.onBind(this, mesh);
  19169. }
  19170. if (this.disableDepthWrite) {
  19171. var engine = this._scene.getEngine();
  19172. this._cachedDepthWriteState = engine.getDepthWrite();
  19173. engine.setDepthWrite(false);
  19174. }
  19175. };
  19176. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19177. };
  19178. Material.prototype.unbind = function () {
  19179. if (this.disableDepthWrite) {
  19180. var engine = this._scene.getEngine();
  19181. engine.setDepthWrite(this._cachedDepthWriteState);
  19182. }
  19183. };
  19184. Material.prototype.clone = function (name) {
  19185. return null;
  19186. };
  19187. Material.prototype.getBindedMeshes = function () {
  19188. var result = new Array();
  19189. for (var index = 0; index < this._scene.meshes.length; index++) {
  19190. var mesh = this._scene.meshes[index];
  19191. if (mesh.material === this) {
  19192. result.push(mesh);
  19193. }
  19194. }
  19195. return result;
  19196. };
  19197. Material.prototype.dispose = function (forceDisposeEffect) {
  19198. // Animations
  19199. this.getScene().stopAnimation(this);
  19200. // Remove from scene
  19201. var index = this._scene.materials.indexOf(this);
  19202. if (index >= 0) {
  19203. this._scene.materials.splice(index, 1);
  19204. }
  19205. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19206. if (forceDisposeEffect && this._effect) {
  19207. this._scene.getEngine()._releaseEffect(this._effect);
  19208. this._effect = null;
  19209. }
  19210. // Remove from meshes
  19211. for (index = 0; index < this._scene.meshes.length; index++) {
  19212. var mesh = this._scene.meshes[index];
  19213. if (mesh.material === this) {
  19214. mesh.material = null;
  19215. }
  19216. }
  19217. // Callback
  19218. if (this.onDispose) {
  19219. this.onDispose();
  19220. }
  19221. };
  19222. Material.prototype.copyTo = function (other) {
  19223. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19224. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19225. other.alpha = this.alpha;
  19226. other.fillMode = this.fillMode;
  19227. other.backFaceCulling = this.backFaceCulling;
  19228. other.fogEnabled = this.fogEnabled;
  19229. other.wireframe = this.wireframe;
  19230. other.zOffset = this.zOffset;
  19231. other.alphaMode = this.alphaMode;
  19232. other.sideOrientation = this.sideOrientation;
  19233. other.disableDepthWrite = this.disableDepthWrite;
  19234. other.pointSize = this.pointSize;
  19235. other.pointsCloud = this.pointsCloud;
  19236. };
  19237. Material.prototype.serialize = function () {
  19238. var serializationObject = {};
  19239. serializationObject.name = this.name;
  19240. serializationObject.alpha = this.alpha;
  19241. serializationObject.id = this.id;
  19242. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19243. serializationObject.backFaceCulling = this.backFaceCulling;
  19244. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19245. serializationObject.disableDepthWrite = this.disableDepthWrite;
  19246. return serializationObject;
  19247. };
  19248. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19249. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19250. multiMaterial.id = parsedMultiMaterial.id;
  19251. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19252. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19253. var subMatId = parsedMultiMaterial.materials[matIndex];
  19254. if (subMatId) {
  19255. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19256. }
  19257. else {
  19258. multiMaterial.subMaterials.push(null);
  19259. }
  19260. }
  19261. return multiMaterial;
  19262. };
  19263. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19264. if (!parsedMaterial.customType) {
  19265. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19266. }
  19267. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19268. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19269. ;
  19270. };
  19271. Material._TriangleFillMode = 0;
  19272. Material._WireFrameFillMode = 1;
  19273. Material._PointFillMode = 2;
  19274. Material._ClockWiseSideOrientation = 0;
  19275. Material._CounterClockWiseSideOrientation = 1;
  19276. return Material;
  19277. })();
  19278. BABYLON.Material = Material;
  19279. })(BABYLON || (BABYLON = {}));
  19280. var BABYLON;
  19281. (function (BABYLON) {
  19282. var maxSimultaneousLights = 4;
  19283. var FresnelParameters = (function () {
  19284. function FresnelParameters() {
  19285. this.isEnabled = true;
  19286. this.leftColor = BABYLON.Color3.White();
  19287. this.rightColor = BABYLON.Color3.Black();
  19288. this.bias = 0;
  19289. this.power = 1;
  19290. }
  19291. FresnelParameters.prototype.clone = function () {
  19292. var newFresnelParameters = new FresnelParameters();
  19293. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19294. return new FresnelParameters;
  19295. };
  19296. FresnelParameters.prototype.serialize = function () {
  19297. var serializationObject = {};
  19298. serializationObject.isEnabled = this.isEnabled;
  19299. serializationObject.leftColor = this.leftColor;
  19300. serializationObject.rightColor = this.rightColor;
  19301. serializationObject.bias = this.bias;
  19302. serializationObject.power = this.power;
  19303. return serializationObject;
  19304. };
  19305. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19306. var fresnelParameters = new FresnelParameters();
  19307. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19308. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19309. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19310. fresnelParameters.bias = parsedFresnelParameters.bias;
  19311. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19312. return fresnelParameters;
  19313. };
  19314. return FresnelParameters;
  19315. })();
  19316. BABYLON.FresnelParameters = FresnelParameters;
  19317. var StandardMaterialDefines = (function (_super) {
  19318. __extends(StandardMaterialDefines, _super);
  19319. function StandardMaterialDefines() {
  19320. _super.call(this);
  19321. this.DIFFUSE = false;
  19322. this.AMBIENT = false;
  19323. this.OPACITY = false;
  19324. this.OPACITYRGB = false;
  19325. this.REFLECTION = false;
  19326. this.EMISSIVE = false;
  19327. this.SPECULAR = false;
  19328. this.BUMP = false;
  19329. this.SPECULAROVERALPHA = false;
  19330. this.CLIPPLANE = false;
  19331. this.ALPHATEST = false;
  19332. this.ALPHAFROMDIFFUSE = false;
  19333. this.POINTSIZE = false;
  19334. this.FOG = false;
  19335. this.LIGHT0 = false;
  19336. this.LIGHT1 = false;
  19337. this.LIGHT2 = false;
  19338. this.LIGHT3 = false;
  19339. this.SPOTLIGHT0 = false;
  19340. this.SPOTLIGHT1 = false;
  19341. this.SPOTLIGHT2 = false;
  19342. this.SPOTLIGHT3 = false;
  19343. this.HEMILIGHT0 = false;
  19344. this.HEMILIGHT1 = false;
  19345. this.HEMILIGHT2 = false;
  19346. this.HEMILIGHT3 = false;
  19347. this.POINTLIGHT0 = false;
  19348. this.POINTLIGHT1 = false;
  19349. this.POINTLIGHT2 = false;
  19350. this.POINTLIGHT3 = false;
  19351. this.DIRLIGHT0 = false;
  19352. this.DIRLIGHT1 = false;
  19353. this.DIRLIGHT2 = false;
  19354. this.DIRLIGHT3 = false;
  19355. this.SPECULARTERM = false;
  19356. this.SHADOW0 = false;
  19357. this.SHADOW1 = false;
  19358. this.SHADOW2 = false;
  19359. this.SHADOW3 = false;
  19360. this.SHADOWS = false;
  19361. this.SHADOWVSM0 = false;
  19362. this.SHADOWVSM1 = false;
  19363. this.SHADOWVSM2 = false;
  19364. this.SHADOWVSM3 = false;
  19365. this.SHADOWPCF0 = false;
  19366. this.SHADOWPCF1 = false;
  19367. this.SHADOWPCF2 = false;
  19368. this.SHADOWPCF3 = false;
  19369. this.DIFFUSEFRESNEL = false;
  19370. this.OPACITYFRESNEL = false;
  19371. this.REFLECTIONFRESNEL = false;
  19372. this.REFRACTIONFRESNEL = false;
  19373. this.EMISSIVEFRESNEL = false;
  19374. this.FRESNEL = false;
  19375. this.NORMAL = false;
  19376. this.UV1 = false;
  19377. this.UV2 = false;
  19378. this.VERTEXCOLOR = false;
  19379. this.VERTEXALPHA = false;
  19380. this.NUM_BONE_INFLUENCERS = 0;
  19381. this.BonesPerMesh = 0;
  19382. this.INSTANCES = false;
  19383. this.GLOSSINESS = false;
  19384. this.ROUGHNESS = false;
  19385. this.EMISSIVEASILLUMINATION = false;
  19386. this.LINKEMISSIVEWITHDIFFUSE = false;
  19387. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19388. this.LIGHTMAP = false;
  19389. this.USELIGHTMAPASSHADOWMAP = false;
  19390. this.REFLECTIONMAP_3D = false;
  19391. this.REFLECTIONMAP_SPHERICAL = false;
  19392. this.REFLECTIONMAP_PLANAR = false;
  19393. this.REFLECTIONMAP_CUBIC = false;
  19394. this.REFLECTIONMAP_PROJECTION = false;
  19395. this.REFLECTIONMAP_SKYBOX = false;
  19396. this.REFLECTIONMAP_EXPLICIT = false;
  19397. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19398. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19399. this.INVERTCUBICMAP = false;
  19400. this.LOGARITHMICDEPTH = false;
  19401. this.REFRACTION = false;
  19402. this.REFRACTIONMAP_3D = false;
  19403. this._keys = Object.keys(this);
  19404. }
  19405. return StandardMaterialDefines;
  19406. })(BABYLON.MaterialDefines);
  19407. var StandardMaterial = (function (_super) {
  19408. __extends(StandardMaterial, _super);
  19409. function StandardMaterial(name, scene) {
  19410. var _this = this;
  19411. _super.call(this, name, scene);
  19412. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19413. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19414. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19415. this.specularPower = 64;
  19416. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19417. this.useAlphaFromDiffuseTexture = false;
  19418. this.useEmissiveAsIllumination = false;
  19419. this.linkEmissiveWithDiffuse = false;
  19420. this.useReflectionFresnelFromSpecular = false;
  19421. this.useSpecularOverAlpha = false;
  19422. this.disableLighting = false;
  19423. this.roughness = 0;
  19424. this.indexOfRefraction = 1.05;
  19425. this.invertRefractionY = true;
  19426. this.useLightmapAsShadowmap = false;
  19427. this.useGlossinessFromSpecularMapAlpha = false;
  19428. this._renderTargets = new BABYLON.SmartArray(16);
  19429. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19430. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19431. this._defines = new StandardMaterialDefines();
  19432. this._cachedDefines = new StandardMaterialDefines();
  19433. this._cachedDefines.BonesPerMesh = -1;
  19434. this.getRenderTargetTextures = function () {
  19435. _this._renderTargets.reset();
  19436. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19437. _this._renderTargets.push(_this.reflectionTexture);
  19438. }
  19439. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  19440. _this._renderTargets.push(_this.refractionTexture);
  19441. }
  19442. return _this._renderTargets;
  19443. };
  19444. }
  19445. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19446. get: function () {
  19447. return this._useLogarithmicDepth;
  19448. },
  19449. set: function (value) {
  19450. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. StandardMaterial.prototype.needAlphaBlending = function () {
  19456. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19457. };
  19458. StandardMaterial.prototype.needAlphaTesting = function () {
  19459. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19460. };
  19461. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19462. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19463. };
  19464. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19465. return this.diffuseTexture;
  19466. };
  19467. // Methods
  19468. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19469. if (!mesh) {
  19470. return true;
  19471. }
  19472. if (this._defines.INSTANCES !== useInstances) {
  19473. return false;
  19474. }
  19475. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19476. return true;
  19477. }
  19478. return false;
  19479. };
  19480. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19481. var lightIndex = 0;
  19482. var needNormals = false;
  19483. for (var index = 0; index < scene.lights.length; index++) {
  19484. var light = scene.lights[index];
  19485. if (!light.isEnabled()) {
  19486. continue;
  19487. }
  19488. // Excluded check
  19489. if (light._excludedMeshesIds.length > 0) {
  19490. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19491. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19492. if (excludedMesh) {
  19493. light.excludedMeshes.push(excludedMesh);
  19494. }
  19495. }
  19496. light._excludedMeshesIds = [];
  19497. }
  19498. // Included check
  19499. if (light._includedOnlyMeshesIds.length > 0) {
  19500. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19501. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19502. if (includedOnlyMesh) {
  19503. light.includedOnlyMeshes.push(includedOnlyMesh);
  19504. }
  19505. }
  19506. light._includedOnlyMeshesIds = [];
  19507. }
  19508. if (!light.canAffectMesh(mesh)) {
  19509. continue;
  19510. }
  19511. needNormals = true;
  19512. defines["LIGHT" + lightIndex] = true;
  19513. var type;
  19514. if (light instanceof BABYLON.SpotLight) {
  19515. type = "SPOTLIGHT" + lightIndex;
  19516. }
  19517. else if (light instanceof BABYLON.HemisphericLight) {
  19518. type = "HEMILIGHT" + lightIndex;
  19519. }
  19520. else if (light instanceof BABYLON.PointLight) {
  19521. type = "POINTLIGHT" + lightIndex;
  19522. }
  19523. else {
  19524. type = "DIRLIGHT" + lightIndex;
  19525. }
  19526. defines[type] = true;
  19527. // Specular
  19528. if (!light.specular.equalsFloats(0, 0, 0)) {
  19529. defines["SPECULARTERM"] = true;
  19530. }
  19531. // Shadows
  19532. if (scene.shadowsEnabled) {
  19533. var shadowGenerator = light.getShadowGenerator();
  19534. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19535. defines["SHADOW" + lightIndex] = true;
  19536. defines["SHADOWS"] = true;
  19537. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19538. defines["SHADOWVSM" + lightIndex] = true;
  19539. }
  19540. if (shadowGenerator.usePoissonSampling) {
  19541. defines["SHADOWPCF" + lightIndex] = true;
  19542. }
  19543. }
  19544. }
  19545. lightIndex++;
  19546. if (lightIndex === maxSimultaneousLights)
  19547. break;
  19548. }
  19549. return needNormals;
  19550. };
  19551. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19552. var lightIndex = 0;
  19553. var depthValuesAlreadySet = false;
  19554. for (var index = 0; index < scene.lights.length; index++) {
  19555. var light = scene.lights[index];
  19556. if (!light.isEnabled()) {
  19557. continue;
  19558. }
  19559. if (!light.canAffectMesh(mesh)) {
  19560. continue;
  19561. }
  19562. if (light instanceof BABYLON.PointLight) {
  19563. // Point Light
  19564. light.transferToEffect(effect, "vLightData" + lightIndex);
  19565. }
  19566. else if (light instanceof BABYLON.DirectionalLight) {
  19567. // Directional Light
  19568. light.transferToEffect(effect, "vLightData" + lightIndex);
  19569. }
  19570. else if (light instanceof BABYLON.SpotLight) {
  19571. // Spot Light
  19572. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19573. }
  19574. else if (light instanceof BABYLON.HemisphericLight) {
  19575. // Hemispheric Light
  19576. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19577. }
  19578. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19579. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19580. if (defines["SPECULARTERM"]) {
  19581. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19582. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19583. }
  19584. // Shadows
  19585. if (scene.shadowsEnabled) {
  19586. var shadowGenerator = light.getShadowGenerator();
  19587. if (mesh.receiveShadows && shadowGenerator) {
  19588. if (!light.needCube()) {
  19589. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19590. }
  19591. else {
  19592. if (!depthValuesAlreadySet) {
  19593. depthValuesAlreadySet = true;
  19594. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19595. }
  19596. }
  19597. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19598. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19599. }
  19600. }
  19601. lightIndex++;
  19602. if (lightIndex === maxSimultaneousLights)
  19603. break;
  19604. }
  19605. };
  19606. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19607. if (this.isFrozen) {
  19608. if (this._wasPreviouslyReady) {
  19609. return true;
  19610. }
  19611. }
  19612. var scene = this.getScene();
  19613. if (!this.checkReadyOnEveryCall) {
  19614. if (this._renderId === scene.getRenderId()) {
  19615. if (this._checkCache(scene, mesh, useInstances)) {
  19616. return true;
  19617. }
  19618. }
  19619. }
  19620. var engine = scene.getEngine();
  19621. var needNormals = false;
  19622. var needUVs = false;
  19623. this._defines.reset();
  19624. // Textures
  19625. if (scene.texturesEnabled) {
  19626. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19627. if (!this.diffuseTexture.isReady()) {
  19628. return false;
  19629. }
  19630. else {
  19631. needUVs = true;
  19632. this._defines.DIFFUSE = true;
  19633. }
  19634. }
  19635. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19636. if (!this.ambientTexture.isReady()) {
  19637. return false;
  19638. }
  19639. else {
  19640. needUVs = true;
  19641. this._defines.AMBIENT = true;
  19642. }
  19643. }
  19644. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19645. if (!this.opacityTexture.isReady()) {
  19646. return false;
  19647. }
  19648. else {
  19649. needUVs = true;
  19650. this._defines.OPACITY = true;
  19651. if (this.opacityTexture.getAlphaFromRGB) {
  19652. this._defines.OPACITYRGB = true;
  19653. }
  19654. }
  19655. }
  19656. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19657. if (!this.reflectionTexture.isReady()) {
  19658. return false;
  19659. }
  19660. else {
  19661. needNormals = true;
  19662. this._defines.REFLECTION = true;
  19663. if (this.roughness > 0) {
  19664. this._defines.ROUGHNESS = true;
  19665. }
  19666. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19667. this._defines.INVERTCUBICMAP = true;
  19668. }
  19669. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19670. switch (this.reflectionTexture.coordinatesMode) {
  19671. case BABYLON.Texture.CUBIC_MODE:
  19672. case BABYLON.Texture.INVCUBIC_MODE:
  19673. this._defines.REFLECTIONMAP_CUBIC = true;
  19674. break;
  19675. case BABYLON.Texture.EXPLICIT_MODE:
  19676. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19677. break;
  19678. case BABYLON.Texture.PLANAR_MODE:
  19679. this._defines.REFLECTIONMAP_PLANAR = true;
  19680. break;
  19681. case BABYLON.Texture.PROJECTION_MODE:
  19682. this._defines.REFLECTIONMAP_PROJECTION = true;
  19683. break;
  19684. case BABYLON.Texture.SKYBOX_MODE:
  19685. this._defines.REFLECTIONMAP_SKYBOX = true;
  19686. break;
  19687. case BABYLON.Texture.SPHERICAL_MODE:
  19688. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19689. break;
  19690. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19691. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19692. break;
  19693. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19694. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19695. break;
  19696. }
  19697. }
  19698. }
  19699. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19700. if (!this.emissiveTexture.isReady()) {
  19701. return false;
  19702. }
  19703. else {
  19704. needUVs = true;
  19705. this._defines.EMISSIVE = true;
  19706. }
  19707. }
  19708. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  19709. if (!this.lightmapTexture.isReady()) {
  19710. return false;
  19711. }
  19712. else {
  19713. needUVs = true;
  19714. this._defines.LIGHTMAP = true;
  19715. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19716. }
  19717. }
  19718. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19719. if (!this.specularTexture.isReady()) {
  19720. return false;
  19721. }
  19722. else {
  19723. needUVs = true;
  19724. this._defines.SPECULAR = true;
  19725. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19726. }
  19727. }
  19728. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19729. if (!this.bumpTexture.isReady()) {
  19730. return false;
  19731. }
  19732. else {
  19733. needUVs = true;
  19734. this._defines.BUMP = true;
  19735. }
  19736. }
  19737. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  19738. if (!this.refractionTexture.isReady()) {
  19739. return false;
  19740. }
  19741. else {
  19742. needUVs = true;
  19743. this._defines.REFRACTION = true;
  19744. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  19745. }
  19746. }
  19747. }
  19748. // Effect
  19749. if (scene.clipPlane) {
  19750. this._defines.CLIPPLANE = true;
  19751. }
  19752. if (engine.getAlphaTesting()) {
  19753. this._defines.ALPHATEST = true;
  19754. }
  19755. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19756. this._defines.ALPHAFROMDIFFUSE = true;
  19757. }
  19758. if (this.useEmissiveAsIllumination) {
  19759. this._defines.EMISSIVEASILLUMINATION = true;
  19760. }
  19761. if (this.linkEmissiveWithDiffuse) {
  19762. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19763. }
  19764. if (this.useReflectionFresnelFromSpecular) {
  19765. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19766. }
  19767. if (this.useLogarithmicDepth) {
  19768. this._defines.LOGARITHMICDEPTH = true;
  19769. }
  19770. // Point size
  19771. if (this.pointsCloud || scene.forcePointsCloud) {
  19772. this._defines.POINTSIZE = true;
  19773. }
  19774. // Fog
  19775. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19776. this._defines.FOG = true;
  19777. }
  19778. if (scene.lightsEnabled && !this.disableLighting) {
  19779. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19780. }
  19781. if (StandardMaterial.FresnelEnabled) {
  19782. // Fresnel
  19783. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19784. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19785. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19786. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  19787. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19788. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19789. this._defines.DIFFUSEFRESNEL = true;
  19790. }
  19791. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19792. this._defines.OPACITYFRESNEL = true;
  19793. }
  19794. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19795. this._defines.REFLECTIONFRESNEL = true;
  19796. }
  19797. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  19798. this._defines.REFRACTIONFRESNEL = true;
  19799. }
  19800. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19801. this._defines.EMISSIVEFRESNEL = true;
  19802. }
  19803. needNormals = true;
  19804. this._defines.FRESNEL = true;
  19805. }
  19806. }
  19807. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19808. this._defines.SPECULAROVERALPHA = true;
  19809. }
  19810. // Attribs
  19811. if (mesh) {
  19812. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19813. this._defines.NORMAL = true;
  19814. }
  19815. if (needUVs) {
  19816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19817. this._defines.UV1 = true;
  19818. }
  19819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19820. this._defines.UV2 = true;
  19821. }
  19822. }
  19823. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19824. this._defines.VERTEXCOLOR = true;
  19825. if (mesh.hasVertexAlpha) {
  19826. this._defines.VERTEXALPHA = true;
  19827. }
  19828. }
  19829. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19830. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19831. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19832. }
  19833. // Instances
  19834. if (useInstances) {
  19835. this._defines.INSTANCES = true;
  19836. }
  19837. }
  19838. // Get correct effect
  19839. if (!this._defines.isEqual(this._cachedDefines)) {
  19840. this._defines.cloneTo(this._cachedDefines);
  19841. scene.resetCachedMaterial();
  19842. // Fallbacks
  19843. var fallbacks = new BABYLON.EffectFallbacks();
  19844. if (this._defines.REFLECTION) {
  19845. fallbacks.addFallback(0, "REFLECTION");
  19846. }
  19847. if (this._defines.SPECULAR) {
  19848. fallbacks.addFallback(0, "SPECULAR");
  19849. }
  19850. if (this._defines.BUMP) {
  19851. fallbacks.addFallback(0, "BUMP");
  19852. }
  19853. if (this._defines.SPECULAROVERALPHA) {
  19854. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19855. }
  19856. if (this._defines.FOG) {
  19857. fallbacks.addFallback(1, "FOG");
  19858. }
  19859. if (this._defines.POINTSIZE) {
  19860. fallbacks.addFallback(0, "POINTSIZE");
  19861. }
  19862. if (this._defines.LOGARITHMICDEPTH) {
  19863. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19864. }
  19865. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19866. if (!this._defines["LIGHT" + lightIndex]) {
  19867. continue;
  19868. }
  19869. if (lightIndex > 0) {
  19870. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19871. }
  19872. if (this._defines["SHADOW" + lightIndex]) {
  19873. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19874. }
  19875. if (this._defines["SHADOWPCF" + lightIndex]) {
  19876. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19877. }
  19878. if (this._defines["SHADOWVSM" + lightIndex]) {
  19879. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19880. }
  19881. }
  19882. if (this._defines.SPECULARTERM) {
  19883. fallbacks.addFallback(0, "SPECULARTERM");
  19884. }
  19885. if (this._defines.DIFFUSEFRESNEL) {
  19886. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19887. }
  19888. if (this._defines.OPACITYFRESNEL) {
  19889. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19890. }
  19891. if (this._defines.REFLECTIONFRESNEL) {
  19892. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19893. }
  19894. if (this._defines.EMISSIVEFRESNEL) {
  19895. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19896. }
  19897. if (this._defines.FRESNEL) {
  19898. fallbacks.addFallback(4, "FRESNEL");
  19899. }
  19900. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19901. fallbacks.addCPUSkinningFallback(0, mesh);
  19902. }
  19903. //Attributes
  19904. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19905. if (this._defines.NORMAL) {
  19906. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19907. }
  19908. if (this._defines.UV1) {
  19909. attribs.push(BABYLON.VertexBuffer.UVKind);
  19910. }
  19911. if (this._defines.UV2) {
  19912. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19913. }
  19914. if (this._defines.VERTEXCOLOR) {
  19915. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19916. }
  19917. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19918. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19919. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19920. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19921. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19922. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19923. }
  19924. }
  19925. if (this._defines.INSTANCES) {
  19926. attribs.push("world0");
  19927. attribs.push("world1");
  19928. attribs.push("world2");
  19929. attribs.push("world3");
  19930. }
  19931. // Legacy browser patch
  19932. var shaderName = "default";
  19933. if (!scene.getEngine().getCaps().standardDerivatives) {
  19934. shaderName = "legacydefault";
  19935. }
  19936. var join = this._defines.toString();
  19937. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19938. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19939. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19940. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19941. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19942. "vFogInfos", "vFogColor", "pointSize",
  19943. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  19944. "mBones",
  19945. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  19946. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19947. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  19948. "logarithmicDepthConstant"
  19949. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  19950. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19951. ], join, fallbacks, this.onCompiled, this.onError);
  19952. }
  19953. if (!this._effect.isReady()) {
  19954. return false;
  19955. }
  19956. this._renderId = scene.getRenderId();
  19957. this._wasPreviouslyReady = true;
  19958. if (mesh) {
  19959. if (!mesh._materialDefines) {
  19960. mesh._materialDefines = new StandardMaterialDefines();
  19961. }
  19962. this._defines.cloneTo(mesh._materialDefines);
  19963. }
  19964. return true;
  19965. };
  19966. StandardMaterial.prototype.unbind = function () {
  19967. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19968. this._effect.setTexture("reflection2DSampler", null);
  19969. }
  19970. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  19971. this._effect.setTexture("refraction2DSampler", null);
  19972. }
  19973. _super.prototype.unbind.call(this);
  19974. };
  19975. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19976. this._effect.setMatrix("world", world);
  19977. };
  19978. StandardMaterial.prototype.bind = function (world, mesh) {
  19979. var scene = this.getScene();
  19980. // Matrices
  19981. this.bindOnlyWorldMatrix(world);
  19982. // Bones
  19983. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19984. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19985. }
  19986. if (scene.getCachedMaterial() !== this) {
  19987. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19988. if (StandardMaterial.FresnelEnabled) {
  19989. // Fresnel
  19990. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19991. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19992. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19993. }
  19994. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19995. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19996. }
  19997. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19998. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19999. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20000. }
  20001. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20002. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20003. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20004. }
  20005. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20006. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20007. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20008. }
  20009. }
  20010. // Textures
  20011. if (scene.texturesEnabled) {
  20012. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20013. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20014. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20015. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20016. }
  20017. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20018. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20019. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20020. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20021. }
  20022. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20023. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20024. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20025. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20026. }
  20027. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20028. if (this.reflectionTexture.isCube) {
  20029. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20030. }
  20031. else {
  20032. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20033. }
  20034. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20035. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20036. }
  20037. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20038. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20039. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20040. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20041. }
  20042. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20043. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20044. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20045. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20046. }
  20047. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20048. this._effect.setTexture("specularSampler", this.specularTexture);
  20049. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20050. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20051. }
  20052. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20053. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20054. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20055. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20056. }
  20057. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20058. var depth = 1.0;
  20059. if (this.refractionTexture.isCube) {
  20060. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20061. }
  20062. else {
  20063. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20064. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20065. if (this.refractionTexture.depth) {
  20066. depth = this.refractionTexture.depth;
  20067. }
  20068. }
  20069. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20070. }
  20071. }
  20072. // Clip plane
  20073. if (scene.clipPlane) {
  20074. var clipPlane = scene.clipPlane;
  20075. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20076. }
  20077. // Point size
  20078. if (this.pointsCloud) {
  20079. this._effect.setFloat("pointSize", this.pointSize);
  20080. }
  20081. // Colors
  20082. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20083. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20084. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20085. if (this._defines.SPECULARTERM) {
  20086. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20087. }
  20088. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20089. }
  20090. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20091. // Diffuse
  20092. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20093. // Lights
  20094. if (scene.lightsEnabled && !this.disableLighting) {
  20095. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  20096. }
  20097. // View
  20098. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20099. this._effect.setMatrix("view", scene.getViewMatrix());
  20100. }
  20101. // Fog
  20102. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20103. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20104. this._effect.setColor3("vFogColor", scene.fogColor);
  20105. }
  20106. // Log. depth
  20107. if (this._defines.LOGARITHMICDEPTH) {
  20108. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20109. }
  20110. }
  20111. _super.prototype.bind.call(this, world, mesh);
  20112. };
  20113. StandardMaterial.prototype.getAnimatables = function () {
  20114. var results = [];
  20115. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20116. results.push(this.diffuseTexture);
  20117. }
  20118. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20119. results.push(this.ambientTexture);
  20120. }
  20121. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20122. results.push(this.opacityTexture);
  20123. }
  20124. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20125. results.push(this.reflectionTexture);
  20126. }
  20127. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20128. results.push(this.emissiveTexture);
  20129. }
  20130. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20131. results.push(this.specularTexture);
  20132. }
  20133. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20134. results.push(this.bumpTexture);
  20135. }
  20136. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20137. results.push(this.lightmapTexture);
  20138. }
  20139. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20140. results.push(this.refractionTexture);
  20141. }
  20142. return results;
  20143. };
  20144. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20145. if (this.diffuseTexture) {
  20146. this.diffuseTexture.dispose();
  20147. }
  20148. if (this.ambientTexture) {
  20149. this.ambientTexture.dispose();
  20150. }
  20151. if (this.opacityTexture) {
  20152. this.opacityTexture.dispose();
  20153. }
  20154. if (this.reflectionTexture) {
  20155. this.reflectionTexture.dispose();
  20156. }
  20157. if (this.emissiveTexture) {
  20158. this.emissiveTexture.dispose();
  20159. }
  20160. if (this.specularTexture) {
  20161. this.specularTexture.dispose();
  20162. }
  20163. if (this.bumpTexture) {
  20164. this.bumpTexture.dispose();
  20165. }
  20166. if (this.lightmapTexture) {
  20167. this.lightmapTexture.dispose();
  20168. }
  20169. if (this.refractionTexture) {
  20170. this.refractionTexture.dispose();
  20171. }
  20172. _super.prototype.dispose.call(this, forceDisposeEffect);
  20173. };
  20174. StandardMaterial.prototype.clone = function (name) {
  20175. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  20176. // Base material
  20177. this.copyTo(newStandardMaterial);
  20178. // Standard material
  20179. if (this.diffuseTexture && this.diffuseTexture.clone) {
  20180. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  20181. }
  20182. if (this.ambientTexture && this.ambientTexture.clone) {
  20183. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  20184. }
  20185. if (this.opacityTexture && this.opacityTexture.clone) {
  20186. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  20187. }
  20188. if (this.reflectionTexture && this.reflectionTexture.clone) {
  20189. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  20190. }
  20191. if (this.emissiveTexture && this.emissiveTexture.clone) {
  20192. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  20193. }
  20194. if (this.specularTexture && this.specularTexture.clone) {
  20195. newStandardMaterial.specularTexture = this.specularTexture.clone();
  20196. }
  20197. if (this.bumpTexture && this.bumpTexture.clone) {
  20198. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  20199. }
  20200. if (this.lightmapTexture && this.lightmapTexture.clone) {
  20201. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  20202. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20203. }
  20204. if (this.refractionTexture && this.refractionTexture.clone) {
  20205. newStandardMaterial.refractionTexture = this.refractionTexture.clone();
  20206. }
  20207. newStandardMaterial.ambientColor = this.ambientColor.clone();
  20208. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  20209. newStandardMaterial.specularColor = this.specularColor.clone();
  20210. newStandardMaterial.specularPower = this.specularPower;
  20211. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  20212. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  20213. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20214. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  20215. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20216. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  20217. newStandardMaterial.roughness = this.roughness;
  20218. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  20219. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  20220. }
  20221. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  20222. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  20223. }
  20224. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  20225. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  20226. }
  20227. if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
  20228. newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
  20229. }
  20230. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  20231. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  20232. }
  20233. return newStandardMaterial;
  20234. };
  20235. StandardMaterial.prototype.serialize = function () {
  20236. var serializationObject = _super.prototype.serialize.call(this);
  20237. serializationObject.ambient = this.ambientColor.asArray();
  20238. serializationObject.diffuse = this.diffuseColor.asArray();
  20239. serializationObject.specular = this.specularColor.asArray();
  20240. serializationObject.specularPower = this.specularPower;
  20241. serializationObject.emissive = this.emissiveColor.asArray();
  20242. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  20243. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  20244. if (this.diffuseTexture) {
  20245. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  20246. }
  20247. if (this.diffuseFresnelParameters) {
  20248. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  20249. }
  20250. if (this.ambientTexture) {
  20251. serializationObject.ambientTexture = this.ambientTexture.serialize();
  20252. }
  20253. if (this.opacityTexture) {
  20254. serializationObject.opacityTexture = this.opacityTexture.serialize();
  20255. }
  20256. if (this.opacityFresnelParameters) {
  20257. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  20258. }
  20259. if (this.reflectionTexture) {
  20260. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  20261. }
  20262. if (this.reflectionFresnelParameters) {
  20263. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  20264. }
  20265. if (this.refractionFresnelParameters) {
  20266. serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
  20267. }
  20268. if (this.emissiveTexture) {
  20269. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  20270. }
  20271. if (this.lightmapTexture) {
  20272. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  20273. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20274. }
  20275. if (this.emissiveFresnelParameters) {
  20276. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  20277. }
  20278. if (this.specularTexture) {
  20279. serializationObject.specularTexture = this.specularTexture.serialize();
  20280. }
  20281. if (this.bumpTexture) {
  20282. serializationObject.bumpTexture = this.bumpTexture.serialize();
  20283. }
  20284. if (this.refractionTexture) {
  20285. serializationObject.refractionTexture = this.refractionTexture.serialize();
  20286. }
  20287. return serializationObject;
  20288. };
  20289. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20290. var material = new StandardMaterial(source.name, scene);
  20291. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  20292. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  20293. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  20294. material.specularPower = source.specularPower;
  20295. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  20296. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  20297. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  20298. material.alpha = source.alpha;
  20299. material.id = source.id;
  20300. if (source.disableDepthWrite) {
  20301. material.disableDepthWrite = source.disableDepthWrite;
  20302. }
  20303. BABYLON.Tags.AddTagsTo(material, source.tags);
  20304. material.backFaceCulling = source.backFaceCulling;
  20305. material.wireframe = source.wireframe;
  20306. if (source.diffuseTexture) {
  20307. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  20308. }
  20309. if (source.diffuseFresnelParameters) {
  20310. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  20311. }
  20312. if (source.ambientTexture) {
  20313. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  20314. }
  20315. if (source.opacityTexture) {
  20316. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  20317. }
  20318. if (source.opacityFresnelParameters) {
  20319. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  20320. }
  20321. if (source.reflectionTexture) {
  20322. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  20323. }
  20324. if (source.reflectionFresnelParameters) {
  20325. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  20326. }
  20327. if (source.refractionFresnelParameters) {
  20328. material.refractionFresnelParameters = FresnelParameters.Parse(source.refractionFresnelParameters);
  20329. }
  20330. if (source.emissiveTexture) {
  20331. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20332. }
  20333. if (source.lightmapTexture) {
  20334. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20335. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20336. }
  20337. if (source.emissiveFresnelParameters) {
  20338. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  20339. }
  20340. if (source.specularTexture) {
  20341. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20342. }
  20343. if (source.bumpTexture) {
  20344. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20345. }
  20346. if (source.refractionTexture) {
  20347. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  20348. }
  20349. if (source.checkReadyOnlyOnce) {
  20350. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20351. }
  20352. return material;
  20353. };
  20354. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  20355. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  20356. // Statics
  20357. // Flags used to enable or disable a type of texture for all Standard Materials
  20358. StandardMaterial.DiffuseTextureEnabled = true;
  20359. StandardMaterial.AmbientTextureEnabled = true;
  20360. StandardMaterial.OpacityTextureEnabled = true;
  20361. StandardMaterial.ReflectionTextureEnabled = true;
  20362. StandardMaterial.EmissiveTextureEnabled = true;
  20363. StandardMaterial.SpecularTextureEnabled = true;
  20364. StandardMaterial.BumpTextureEnabled = true;
  20365. StandardMaterial.FresnelEnabled = true;
  20366. StandardMaterial.LightmapTextureEnabled = true;
  20367. StandardMaterial.RefractionTextureEnabled = true;
  20368. return StandardMaterial;
  20369. })(BABYLON.Material);
  20370. BABYLON.StandardMaterial = StandardMaterial;
  20371. })(BABYLON || (BABYLON = {}));
  20372. var BABYLON;
  20373. (function (BABYLON) {
  20374. var MultiMaterial = (function (_super) {
  20375. __extends(MultiMaterial, _super);
  20376. function MultiMaterial(name, scene) {
  20377. _super.call(this, name, scene, true);
  20378. this.subMaterials = new Array();
  20379. scene.multiMaterials.push(this);
  20380. }
  20381. // Properties
  20382. MultiMaterial.prototype.getSubMaterial = function (index) {
  20383. if (index < 0 || index >= this.subMaterials.length) {
  20384. return this.getScene().defaultMaterial;
  20385. }
  20386. return this.subMaterials[index];
  20387. };
  20388. // Methods
  20389. MultiMaterial.prototype.isReady = function (mesh) {
  20390. for (var index = 0; index < this.subMaterials.length; index++) {
  20391. var subMaterial = this.subMaterials[index];
  20392. if (subMaterial) {
  20393. if (!this.subMaterials[index].isReady(mesh)) {
  20394. return false;
  20395. }
  20396. }
  20397. }
  20398. return true;
  20399. };
  20400. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20401. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20402. for (var index = 0; index < this.subMaterials.length; index++) {
  20403. var subMaterial = null;
  20404. if (cloneChildren) {
  20405. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20406. }
  20407. else {
  20408. subMaterial = this.subMaterials[index];
  20409. }
  20410. newMultiMaterial.subMaterials.push(subMaterial);
  20411. }
  20412. return newMultiMaterial;
  20413. };
  20414. MultiMaterial.prototype.serialize = function () {
  20415. var serializationObject = {};
  20416. serializationObject.name = this.name;
  20417. serializationObject.id = this.id;
  20418. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20419. serializationObject.materials = [];
  20420. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20421. var subMat = this.subMaterials[matIndex];
  20422. if (subMat) {
  20423. serializationObject.materials.push(subMat.id);
  20424. }
  20425. else {
  20426. serializationObject.materials.push(null);
  20427. }
  20428. }
  20429. return serializationObject;
  20430. };
  20431. return MultiMaterial;
  20432. })(BABYLON.Material);
  20433. BABYLON.MultiMaterial = MultiMaterial;
  20434. })(BABYLON || (BABYLON = {}));
  20435. var BABYLON;
  20436. (function (BABYLON) {
  20437. var SceneLoader = (function () {
  20438. function SceneLoader() {
  20439. }
  20440. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20441. get: function () {
  20442. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20443. },
  20444. set: function (value) {
  20445. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20446. },
  20447. enumerable: true,
  20448. configurable: true
  20449. });
  20450. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20451. get: function () {
  20452. return SceneLoader._ShowLoadingScreen;
  20453. },
  20454. set: function (value) {
  20455. SceneLoader._ShowLoadingScreen = value;
  20456. },
  20457. enumerable: true,
  20458. configurable: true
  20459. });
  20460. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20461. var dotPosition = sceneFilename.lastIndexOf(".");
  20462. var queryStringPosition = sceneFilename.indexOf("?");
  20463. if (queryStringPosition === -1) {
  20464. queryStringPosition = sceneFilename.length;
  20465. }
  20466. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20467. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20468. var plugin = this._registeredPlugins[index];
  20469. if (plugin.extensions.indexOf(extension) !== -1) {
  20470. return plugin;
  20471. }
  20472. }
  20473. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20474. };
  20475. // Public functions
  20476. SceneLoader.GetPluginForExtension = function (extension) {
  20477. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20478. var plugin = this._registeredPlugins[index];
  20479. if (plugin.extensions.indexOf(extension) !== -1) {
  20480. return plugin;
  20481. }
  20482. }
  20483. return null;
  20484. };
  20485. SceneLoader.RegisterPlugin = function (plugin) {
  20486. plugin.extensions = plugin.extensions.toLowerCase();
  20487. SceneLoader._registeredPlugins.push(plugin);
  20488. };
  20489. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20490. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20491. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20492. return;
  20493. }
  20494. var loadingToken = {};
  20495. scene._addPendingData(loadingToken);
  20496. var manifestChecked = function (success) {
  20497. scene.database = database;
  20498. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20499. var importMeshFromData = function (data) {
  20500. var meshes = [];
  20501. var particleSystems = [];
  20502. var skeletons = [];
  20503. try {
  20504. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20505. if (onerror) {
  20506. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20507. }
  20508. scene._removePendingData(loadingToken);
  20509. return;
  20510. }
  20511. }
  20512. catch (e) {
  20513. if (onerror) {
  20514. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20515. }
  20516. scene._removePendingData(loadingToken);
  20517. return;
  20518. }
  20519. if (onsuccess) {
  20520. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20521. onsuccess(meshes, particleSystems, skeletons);
  20522. scene._removePendingData(loadingToken);
  20523. }
  20524. };
  20525. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20526. // Direct load
  20527. importMeshFromData(sceneFilename.substr(5));
  20528. return;
  20529. }
  20530. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20531. importMeshFromData(data);
  20532. }, progressCallBack, database);
  20533. };
  20534. if (scene.getEngine().enableOfflineSupport) {
  20535. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20536. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20537. }
  20538. else {
  20539. manifestChecked(true);
  20540. }
  20541. };
  20542. /**
  20543. * Load a scene
  20544. * @param rootUrl a string that defines the root url for scene and resources
  20545. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20546. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20547. */
  20548. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20549. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20550. };
  20551. /**
  20552. * Append a scene
  20553. * @param rootUrl a string that defines the root url for scene and resources
  20554. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20555. * @param scene is the instance of BABYLON.Scene to append to
  20556. */
  20557. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20558. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20559. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20560. return;
  20561. }
  20562. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20563. var database;
  20564. var loadingToken = {};
  20565. scene._addPendingData(loadingToken);
  20566. if (SceneLoader.ShowLoadingScreen) {
  20567. scene.getEngine().displayLoadingUI();
  20568. }
  20569. var loadSceneFromData = function (data) {
  20570. scene.database = database;
  20571. if (!plugin.load(scene, data, rootUrl)) {
  20572. if (onerror) {
  20573. onerror(scene);
  20574. }
  20575. scene._removePendingData(loadingToken);
  20576. scene.getEngine().hideLoadingUI();
  20577. return;
  20578. }
  20579. if (onsuccess) {
  20580. onsuccess(scene);
  20581. }
  20582. scene._removePendingData(loadingToken);
  20583. if (SceneLoader.ShowLoadingScreen) {
  20584. scene.executeWhenReady(function () {
  20585. scene.getEngine().hideLoadingUI();
  20586. });
  20587. }
  20588. };
  20589. var manifestChecked = function (success) {
  20590. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20591. };
  20592. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20593. // Direct load
  20594. loadSceneFromData(sceneFilename.substr(5));
  20595. return;
  20596. }
  20597. if (rootUrl.indexOf("file:") === -1) {
  20598. if (scene.getEngine().enableOfflineSupport) {
  20599. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20600. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20601. }
  20602. else {
  20603. manifestChecked(true);
  20604. }
  20605. }
  20606. else {
  20607. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20608. }
  20609. };
  20610. // Flags
  20611. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20612. SceneLoader._ShowLoadingScreen = true;
  20613. // Members
  20614. SceneLoader._registeredPlugins = new Array();
  20615. return SceneLoader;
  20616. })();
  20617. BABYLON.SceneLoader = SceneLoader;
  20618. ;
  20619. })(BABYLON || (BABYLON = {}));
  20620. var BABYLON;
  20621. (function (BABYLON) {
  20622. var Internals;
  20623. (function (Internals) {
  20624. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20625. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20626. var parsedMaterial = parsedData.materials[index];
  20627. if (parsedMaterial.id === id) {
  20628. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20629. }
  20630. }
  20631. return null;
  20632. };
  20633. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20634. names = (names instanceof Array) ? names : [names];
  20635. for (var i in names) {
  20636. if (mesh.name === names[i]) {
  20637. hierarchyIds.push(mesh.id);
  20638. return true;
  20639. }
  20640. }
  20641. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20642. hierarchyIds.push(mesh.id);
  20643. return true;
  20644. }
  20645. return false;
  20646. };
  20647. BABYLON.SceneLoader.RegisterPlugin({
  20648. extensions: ".babylon",
  20649. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20650. var parsedData = JSON.parse(data);
  20651. var loadedSkeletonsIds = [];
  20652. var loadedMaterialsIds = [];
  20653. var hierarchyIds = [];
  20654. var index;
  20655. var cache;
  20656. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20657. var parsedMesh = parsedData.meshes[index];
  20658. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20659. if (meshesNames instanceof Array) {
  20660. // Remove found mesh name from list.
  20661. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20662. }
  20663. //Geometry?
  20664. if (parsedMesh.geometryId) {
  20665. //does the file contain geometries?
  20666. if (parsedData.geometries) {
  20667. //find the correct geometry and add it to the scene
  20668. var found = false;
  20669. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20670. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20671. return;
  20672. }
  20673. else {
  20674. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20675. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20676. switch (geometryType) {
  20677. case "boxes":
  20678. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20679. break;
  20680. case "spheres":
  20681. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20682. break;
  20683. case "cylinders":
  20684. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20685. break;
  20686. case "toruses":
  20687. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20688. break;
  20689. case "grounds":
  20690. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20691. break;
  20692. case "planes":
  20693. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20694. break;
  20695. case "torusKnots":
  20696. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20697. break;
  20698. case "vertexData":
  20699. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20700. break;
  20701. }
  20702. found = true;
  20703. }
  20704. });
  20705. }
  20706. });
  20707. if (!found) {
  20708. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20709. }
  20710. }
  20711. }
  20712. // Material ?
  20713. if (parsedMesh.materialId) {
  20714. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20715. if (!materialFound && parsedData.multiMaterials) {
  20716. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20717. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20718. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20719. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20720. var subMatId = parsedMultiMaterial.materials[matIndex];
  20721. loadedMaterialsIds.push(subMatId);
  20722. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20723. }
  20724. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20725. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20726. materialFound = true;
  20727. break;
  20728. }
  20729. }
  20730. }
  20731. if (!materialFound) {
  20732. loadedMaterialsIds.push(parsedMesh.materialId);
  20733. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20734. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20735. }
  20736. }
  20737. }
  20738. // Skeleton ?
  20739. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20740. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20741. if (!skeletonAlreadyLoaded) {
  20742. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20743. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20744. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20745. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20746. loadedSkeletonsIds.push(parsedSkeleton.id);
  20747. }
  20748. }
  20749. }
  20750. }
  20751. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20752. meshes.push(mesh);
  20753. }
  20754. }
  20755. // Connecting parents
  20756. var currentMesh;
  20757. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20758. currentMesh = scene.meshes[index];
  20759. if (currentMesh._waitingParentId) {
  20760. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20761. currentMesh._waitingParentId = undefined;
  20762. }
  20763. }
  20764. // freeze and compute world matrix application
  20765. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20766. currentMesh = scene.meshes[index];
  20767. if (currentMesh._waitingFreezeWorldMatrix) {
  20768. currentMesh.freezeWorldMatrix();
  20769. currentMesh._waitingFreezeWorldMatrix = undefined;
  20770. }
  20771. else {
  20772. currentMesh.computeWorldMatrix(true);
  20773. }
  20774. }
  20775. // Particles
  20776. if (parsedData.particleSystems) {
  20777. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20778. var parsedParticleSystem = parsedData.particleSystems[index];
  20779. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20780. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20781. }
  20782. }
  20783. }
  20784. return true;
  20785. },
  20786. load: function (scene, data, rootUrl) {
  20787. var parsedData = JSON.parse(data);
  20788. // Scene
  20789. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20790. scene.autoClear = parsedData.autoClear;
  20791. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20792. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20793. if (parsedData.gravity) {
  20794. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20795. }
  20796. // Fog
  20797. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20798. scene.fogMode = parsedData.fogMode;
  20799. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20800. scene.fogStart = parsedData.fogStart;
  20801. scene.fogEnd = parsedData.fogEnd;
  20802. scene.fogDensity = parsedData.fogDensity;
  20803. }
  20804. //Physics
  20805. if (parsedData.physicsEnabled) {
  20806. var physicsPlugin;
  20807. if (parsedData.physicsEngine === "cannon") {
  20808. physicsPlugin = new BABYLON.CannonJSPlugin();
  20809. }
  20810. else if (parsedData.physicsEngine === "oimo") {
  20811. physicsPlugin = new BABYLON.OimoJSPlugin();
  20812. }
  20813. //else - default engine, which is currently oimo
  20814. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20815. scene.enablePhysics(physicsGravity, physicsPlugin);
  20816. }
  20817. //collisions, if defined. otherwise, default is true
  20818. if (parsedData.collisionsEnabled != undefined) {
  20819. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20820. }
  20821. scene.workerCollisions = !!parsedData.workerCollisions;
  20822. var index;
  20823. var cache;
  20824. // Lights
  20825. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20826. var parsedLight = parsedData.lights[index];
  20827. BABYLON.Light.Parse(parsedLight, scene);
  20828. }
  20829. // Materials
  20830. if (parsedData.materials) {
  20831. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20832. var parsedMaterial = parsedData.materials[index];
  20833. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20834. }
  20835. }
  20836. if (parsedData.multiMaterials) {
  20837. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20838. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20839. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20840. }
  20841. }
  20842. // Skeletons
  20843. if (parsedData.skeletons) {
  20844. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20845. var parsedSkeleton = parsedData.skeletons[index];
  20846. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20847. }
  20848. }
  20849. // Geometries
  20850. var geometries = parsedData.geometries;
  20851. if (geometries) {
  20852. // Boxes
  20853. var boxes = geometries.boxes;
  20854. if (boxes) {
  20855. for (index = 0, cache = boxes.length; index < cache; index++) {
  20856. var parsedBox = boxes[index];
  20857. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20858. }
  20859. }
  20860. // Spheres
  20861. var spheres = geometries.spheres;
  20862. if (spheres) {
  20863. for (index = 0, cache = spheres.length; index < cache; index++) {
  20864. var parsedSphere = spheres[index];
  20865. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20866. }
  20867. }
  20868. // Cylinders
  20869. var cylinders = geometries.cylinders;
  20870. if (cylinders) {
  20871. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20872. var parsedCylinder = cylinders[index];
  20873. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20874. }
  20875. }
  20876. // Toruses
  20877. var toruses = geometries.toruses;
  20878. if (toruses) {
  20879. for (index = 0, cache = toruses.length; index < cache; index++) {
  20880. var parsedTorus = toruses[index];
  20881. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20882. }
  20883. }
  20884. // Grounds
  20885. var grounds = geometries.grounds;
  20886. if (grounds) {
  20887. for (index = 0, cache = grounds.length; index < cache; index++) {
  20888. var parsedGround = grounds[index];
  20889. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20890. }
  20891. }
  20892. // Planes
  20893. var planes = geometries.planes;
  20894. if (planes) {
  20895. for (index = 0, cache = planes.length; index < cache; index++) {
  20896. var parsedPlane = planes[index];
  20897. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20898. }
  20899. }
  20900. // TorusKnots
  20901. var torusKnots = geometries.torusKnots;
  20902. if (torusKnots) {
  20903. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20904. var parsedTorusKnot = torusKnots[index];
  20905. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20906. }
  20907. }
  20908. // VertexData
  20909. var vertexData = geometries.vertexData;
  20910. if (vertexData) {
  20911. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20912. var parsedVertexData = vertexData[index];
  20913. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20914. }
  20915. }
  20916. }
  20917. // Meshes
  20918. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20919. var parsedMesh = parsedData.meshes[index];
  20920. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20921. }
  20922. // Cameras
  20923. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20924. var parsedCamera = parsedData.cameras[index];
  20925. BABYLON.Camera.Parse(parsedCamera, scene);
  20926. }
  20927. if (parsedData.activeCameraID) {
  20928. scene.setActiveCameraByID(parsedData.activeCameraID);
  20929. }
  20930. // Browsing all the graph to connect the dots
  20931. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20932. var camera = scene.cameras[index];
  20933. if (camera._waitingParentId) {
  20934. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20935. camera._waitingParentId = undefined;
  20936. }
  20937. }
  20938. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20939. var light = scene.lights[index];
  20940. if (light._waitingParentId) {
  20941. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20942. light._waitingParentId = undefined;
  20943. }
  20944. }
  20945. // Sounds
  20946. var loadedSounds = [];
  20947. var loadedSound;
  20948. if (BABYLON.AudioEngine && parsedData.sounds) {
  20949. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20950. var parsedSound = parsedData.sounds[index];
  20951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20952. if (!parsedSound.url)
  20953. parsedSound.url = parsedSound.name;
  20954. if (!loadedSounds[parsedSound.url]) {
  20955. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20956. loadedSounds[parsedSound.url] = loadedSound;
  20957. }
  20958. else {
  20959. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20960. }
  20961. }
  20962. else {
  20963. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20964. }
  20965. }
  20966. }
  20967. loadedSounds = [];
  20968. // Connect parents & children and parse actions
  20969. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20970. var mesh = scene.meshes[index];
  20971. if (mesh._waitingParentId) {
  20972. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20973. mesh._waitingParentId = undefined;
  20974. }
  20975. if (mesh._waitingActions) {
  20976. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20977. mesh._waitingActions = undefined;
  20978. }
  20979. }
  20980. // freeze world matrix application
  20981. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20982. var currentMesh = scene.meshes[index];
  20983. if (currentMesh._waitingFreezeWorldMatrix) {
  20984. currentMesh.freezeWorldMatrix();
  20985. currentMesh._waitingFreezeWorldMatrix = undefined;
  20986. }
  20987. else {
  20988. currentMesh.computeWorldMatrix(true);
  20989. }
  20990. }
  20991. // Particles Systems
  20992. if (parsedData.particleSystems) {
  20993. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20994. var parsedParticleSystem = parsedData.particleSystems[index];
  20995. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20996. }
  20997. }
  20998. // Lens flares
  20999. if (parsedData.lensFlareSystems) {
  21000. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21001. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21002. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21003. }
  21004. }
  21005. // Shadows
  21006. if (parsedData.shadowGenerators) {
  21007. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21008. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21009. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21010. }
  21011. }
  21012. // Actions (scene)
  21013. if (parsedData.actions) {
  21014. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21015. }
  21016. // Finish
  21017. return true;
  21018. }
  21019. });
  21020. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21021. })(BABYLON || (BABYLON = {}));
  21022. var BABYLON;
  21023. (function (BABYLON) {
  21024. var SpriteManager = (function () {
  21025. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21027. this.name = name;
  21028. this.cellSize = cellSize;
  21029. this.sprites = new Array();
  21030. this.renderingGroupId = 0;
  21031. this.layerMask = 0x0FFFFFFF;
  21032. this.fogEnabled = true;
  21033. this.isPickable = false;
  21034. this._vertexDeclaration = [4, 4, 4, 4];
  21035. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21036. this._capacity = capacity;
  21037. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21038. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21039. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21040. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21041. this._scene = scene;
  21042. this._scene.spriteManagers.push(this);
  21043. // VBO
  21044. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21045. var indices = [];
  21046. var index = 0;
  21047. for (var count = 0; count < capacity; count++) {
  21048. indices.push(index);
  21049. indices.push(index + 1);
  21050. indices.push(index + 2);
  21051. indices.push(index);
  21052. indices.push(index + 2);
  21053. indices.push(index + 3);
  21054. index += 4;
  21055. }
  21056. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21057. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21058. // Effects
  21059. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21060. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21061. }
  21062. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21063. var arrayOffset = index * 16;
  21064. if (offsetX === 0)
  21065. offsetX = this._epsilon;
  21066. else if (offsetX === 1)
  21067. offsetX = 1 - this._epsilon;
  21068. if (offsetY === 0)
  21069. offsetY = this._epsilon;
  21070. else if (offsetY === 1)
  21071. offsetY = 1 - this._epsilon;
  21072. this._vertices[arrayOffset] = sprite.position.x;
  21073. this._vertices[arrayOffset + 1] = sprite.position.y;
  21074. this._vertices[arrayOffset + 2] = sprite.position.z;
  21075. this._vertices[arrayOffset + 3] = sprite.angle;
  21076. this._vertices[arrayOffset + 4] = sprite.width;
  21077. this._vertices[arrayOffset + 5] = sprite.height;
  21078. this._vertices[arrayOffset + 6] = offsetX;
  21079. this._vertices[arrayOffset + 7] = offsetY;
  21080. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21081. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21082. var offset = (sprite.cellIndex / rowSize) >> 0;
  21083. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21084. this._vertices[arrayOffset + 11] = offset;
  21085. // Color
  21086. this._vertices[arrayOffset + 12] = sprite.color.r;
  21087. this._vertices[arrayOffset + 13] = sprite.color.g;
  21088. this._vertices[arrayOffset + 14] = sprite.color.b;
  21089. this._vertices[arrayOffset + 15] = sprite.color.a;
  21090. };
  21091. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21092. var count = Math.min(this._capacity, this.sprites.length);
  21093. var min = BABYLON.Vector3.Zero();
  21094. var max = BABYLON.Vector3.Zero();
  21095. var distance = Number.MAX_VALUE;
  21096. var currentSprite;
  21097. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21098. var cameraView = camera.getViewMatrix();
  21099. for (var index = 0; index < count; index++) {
  21100. var sprite = this.sprites[index];
  21101. if (!sprite) {
  21102. continue;
  21103. }
  21104. if (predicate) {
  21105. if (!predicate(sprite)) {
  21106. continue;
  21107. }
  21108. }
  21109. else if (!sprite.isPickable) {
  21110. continue;
  21111. }
  21112. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21113. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21114. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21115. if (ray.intersectsBoxMinMax(min, max)) {
  21116. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21117. if (distance > currentDistance) {
  21118. distance = currentDistance;
  21119. currentSprite = sprite;
  21120. if (fastCheck) {
  21121. break;
  21122. }
  21123. }
  21124. }
  21125. }
  21126. if (currentSprite) {
  21127. var result = new BABYLON.PickingInfo();
  21128. result.hit = true;
  21129. result.pickedSprite = currentSprite;
  21130. result.distance = distance;
  21131. return result;
  21132. }
  21133. return null;
  21134. };
  21135. SpriteManager.prototype.render = function () {
  21136. // Check
  21137. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21138. return;
  21139. var engine = this._scene.getEngine();
  21140. var baseSize = this._spriteTexture.getBaseSize();
  21141. // Sprites
  21142. var deltaTime = engine.getDeltaTime();
  21143. var max = Math.min(this._capacity, this.sprites.length);
  21144. var rowSize = baseSize.width / this.cellSize;
  21145. var offset = 0;
  21146. for (var index = 0; index < max; index++) {
  21147. var sprite = this.sprites[index];
  21148. if (!sprite) {
  21149. continue;
  21150. }
  21151. sprite._animate(deltaTime);
  21152. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21153. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21154. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21155. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21156. }
  21157. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21158. // Render
  21159. var effect = this._effectBase;
  21160. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21161. effect = this._effectFog;
  21162. }
  21163. engine.enableEffect(effect);
  21164. var viewMatrix = this._scene.getViewMatrix();
  21165. effect.setTexture("diffuseSampler", this._spriteTexture);
  21166. effect.setMatrix("view", viewMatrix);
  21167. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21168. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21169. // Fog
  21170. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21171. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21172. effect.setColor3("vFogColor", this._scene.fogColor);
  21173. }
  21174. // VBOs
  21175. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21176. // Draw order
  21177. engine.setDepthFunctionToLessOrEqual();
  21178. effect.setBool("alphaTest", true);
  21179. engine.setColorWrite(false);
  21180. engine.draw(true, 0, max * 6);
  21181. engine.setColorWrite(true);
  21182. effect.setBool("alphaTest", false);
  21183. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21184. engine.draw(true, 0, max * 6);
  21185. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21186. };
  21187. SpriteManager.prototype.dispose = function () {
  21188. if (this._vertexBuffer) {
  21189. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21190. this._vertexBuffer = null;
  21191. }
  21192. if (this._indexBuffer) {
  21193. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21194. this._indexBuffer = null;
  21195. }
  21196. if (this._spriteTexture) {
  21197. this._spriteTexture.dispose();
  21198. this._spriteTexture = null;
  21199. }
  21200. // Remove from scene
  21201. var index = this._scene.spriteManagers.indexOf(this);
  21202. this._scene.spriteManagers.splice(index, 1);
  21203. // Callback
  21204. if (this.onDispose) {
  21205. this.onDispose();
  21206. }
  21207. };
  21208. return SpriteManager;
  21209. })();
  21210. BABYLON.SpriteManager = SpriteManager;
  21211. })(BABYLON || (BABYLON = {}));
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var Sprite = (function () {
  21215. function Sprite(name, manager) {
  21216. this.name = name;
  21217. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21218. this.width = 1.0;
  21219. this.height = 1.0;
  21220. this.angle = 0;
  21221. this.cellIndex = 0;
  21222. this.invertU = 0;
  21223. this.invertV = 0;
  21224. this.animations = new Array();
  21225. this.isPickable = false;
  21226. this._animationStarted = false;
  21227. this._loopAnimation = false;
  21228. this._fromIndex = 0;
  21229. this._toIndex = 0;
  21230. this._delay = 0;
  21231. this._direction = 1;
  21232. this._frameCount = 0;
  21233. this._time = 0;
  21234. this._manager = manager;
  21235. this._manager.sprites.push(this);
  21236. this.position = BABYLON.Vector3.Zero();
  21237. }
  21238. Object.defineProperty(Sprite.prototype, "size", {
  21239. get: function () {
  21240. return this.width;
  21241. },
  21242. set: function (value) {
  21243. this.width = value;
  21244. this.height = value;
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21250. this._fromIndex = from;
  21251. this._toIndex = to;
  21252. this._loopAnimation = loop;
  21253. this._delay = delay;
  21254. this._animationStarted = true;
  21255. this._direction = from < to ? 1 : -1;
  21256. this.cellIndex = from;
  21257. this._time = 0;
  21258. };
  21259. Sprite.prototype.stopAnimation = function () {
  21260. this._animationStarted = false;
  21261. };
  21262. Sprite.prototype._animate = function (deltaTime) {
  21263. if (!this._animationStarted)
  21264. return;
  21265. this._time += deltaTime;
  21266. if (this._time > this._delay) {
  21267. this._time = this._time % this._delay;
  21268. this.cellIndex += this._direction;
  21269. if (this.cellIndex == this._toIndex) {
  21270. if (this._loopAnimation) {
  21271. this.cellIndex = this._fromIndex;
  21272. }
  21273. else {
  21274. this._animationStarted = false;
  21275. if (this.disposeWhenFinishedAnimating) {
  21276. this.dispose();
  21277. }
  21278. }
  21279. }
  21280. }
  21281. };
  21282. Sprite.prototype.dispose = function () {
  21283. for (var i = 0; i < this._manager.sprites.length; i++) {
  21284. if (this._manager.sprites[i] == this) {
  21285. this._manager.sprites.splice(i, 1);
  21286. }
  21287. }
  21288. };
  21289. return Sprite;
  21290. })();
  21291. BABYLON.Sprite = Sprite;
  21292. })(BABYLON || (BABYLON = {}));
  21293. var BABYLON;
  21294. (function (BABYLON) {
  21295. var Layer = (function () {
  21296. function Layer(name, imgUrl, scene, isBackground, color) {
  21297. this.name = name;
  21298. this.scale = new BABYLON.Vector2(1, 1);
  21299. this.offset = new BABYLON.Vector2(0, 0);
  21300. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21301. this._vertexDeclaration = [2];
  21302. this._vertexStrideSize = 2 * 4;
  21303. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21304. this.isBackground = isBackground === undefined ? true : isBackground;
  21305. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21306. this._scene = scene;
  21307. this._scene.layers.push(this);
  21308. // VBO
  21309. var vertices = [];
  21310. vertices.push(1, 1);
  21311. vertices.push(-1, 1);
  21312. vertices.push(-1, -1);
  21313. vertices.push(1, -1);
  21314. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21315. // Indices
  21316. var indices = [];
  21317. indices.push(0);
  21318. indices.push(1);
  21319. indices.push(2);
  21320. indices.push(0);
  21321. indices.push(2);
  21322. indices.push(3);
  21323. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21324. // Effects
  21325. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21326. }
  21327. Layer.prototype.render = function () {
  21328. // Check
  21329. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21330. return;
  21331. var engine = this._scene.getEngine();
  21332. // Render
  21333. engine.enableEffect(this._effect);
  21334. engine.setState(false);
  21335. // Texture
  21336. this._effect.setTexture("textureSampler", this.texture);
  21337. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21338. // Color
  21339. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21340. // Scale / offset
  21341. this._effect.setVector2("offset", this.offset);
  21342. this._effect.setVector2("scale", this.scale);
  21343. // VBOs
  21344. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21345. // Draw order
  21346. engine.setAlphaMode(this.alphaBlendingMode);
  21347. engine.draw(true, 0, 6);
  21348. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21349. };
  21350. Layer.prototype.dispose = function () {
  21351. if (this._vertexBuffer) {
  21352. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21353. this._vertexBuffer = null;
  21354. }
  21355. if (this._indexBuffer) {
  21356. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21357. this._indexBuffer = null;
  21358. }
  21359. if (this.texture) {
  21360. this.texture.dispose();
  21361. this.texture = null;
  21362. }
  21363. // Remove from scene
  21364. var index = this._scene.layers.indexOf(this);
  21365. this._scene.layers.splice(index, 1);
  21366. // Callback
  21367. if (this.onDispose) {
  21368. this.onDispose();
  21369. }
  21370. };
  21371. return Layer;
  21372. })();
  21373. BABYLON.Layer = Layer;
  21374. })(BABYLON || (BABYLON = {}));
  21375. var BABYLON;
  21376. (function (BABYLON) {
  21377. var Particle = (function () {
  21378. function Particle() {
  21379. this.position = BABYLON.Vector3.Zero();
  21380. this.direction = BABYLON.Vector3.Zero();
  21381. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21382. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21383. this.lifeTime = 1.0;
  21384. this.age = 0;
  21385. this.size = 0;
  21386. this.angle = 0;
  21387. this.angularSpeed = 0;
  21388. }
  21389. Particle.prototype.copyTo = function (other) {
  21390. other.position.copyFrom(this.position);
  21391. other.direction.copyFrom(this.direction);
  21392. other.color.copyFrom(this.color);
  21393. other.colorStep.copyFrom(this.colorStep);
  21394. other.lifeTime = this.lifeTime;
  21395. other.age = this.age;
  21396. other.size = this.size;
  21397. other.angle = this.angle;
  21398. other.angularSpeed = this.angularSpeed;
  21399. };
  21400. return Particle;
  21401. })();
  21402. BABYLON.Particle = Particle;
  21403. })(BABYLON || (BABYLON = {}));
  21404. var BABYLON;
  21405. (function (BABYLON) {
  21406. var randomNumber = function (min, max) {
  21407. if (min === max) {
  21408. return (min);
  21409. }
  21410. var random = Math.random();
  21411. return ((random * (max - min)) + min);
  21412. };
  21413. var ParticleSystem = (function () {
  21414. function ParticleSystem(name, capacity, scene, customEffect) {
  21415. var _this = this;
  21416. this.name = name;
  21417. this.renderingGroupId = 0;
  21418. this.emitter = null;
  21419. this.emitRate = 10;
  21420. this.manualEmitCount = -1;
  21421. this.updateSpeed = 0.01;
  21422. this.targetStopDuration = 0;
  21423. this.disposeOnStop = false;
  21424. this.minEmitPower = 1;
  21425. this.maxEmitPower = 1;
  21426. this.minLifeTime = 1;
  21427. this.maxLifeTime = 1;
  21428. this.minSize = 1;
  21429. this.maxSize = 1;
  21430. this.minAngularSpeed = 0;
  21431. this.maxAngularSpeed = 0;
  21432. this.layerMask = 0x0FFFFFFF;
  21433. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21434. this.forceDepthWrite = false;
  21435. this.gravity = BABYLON.Vector3.Zero();
  21436. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21437. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21438. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21439. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21440. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21441. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21442. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21443. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21444. this.particles = new Array();
  21445. this._vertexDeclaration = [3, 4, 4];
  21446. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21447. this._stockParticles = new Array();
  21448. this._newPartsExcess = 0;
  21449. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21450. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21451. this._scaledDirection = BABYLON.Vector3.Zero();
  21452. this._scaledGravity = BABYLON.Vector3.Zero();
  21453. this._currentRenderId = -1;
  21454. this._started = false;
  21455. this._stopped = false;
  21456. this._actualFrame = 0;
  21457. this.id = name;
  21458. this._capacity = capacity;
  21459. this._scene = scene;
  21460. this._customEffect = customEffect;
  21461. scene.particleSystems.push(this);
  21462. // VBO
  21463. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21464. var indices = [];
  21465. var index = 0;
  21466. for (var count = 0; count < capacity; count++) {
  21467. indices.push(index);
  21468. indices.push(index + 1);
  21469. indices.push(index + 2);
  21470. indices.push(index);
  21471. indices.push(index + 2);
  21472. indices.push(index + 3);
  21473. index += 4;
  21474. }
  21475. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21476. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21477. // Default behaviors
  21478. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21479. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21480. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21481. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21482. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21483. };
  21484. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21485. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21486. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21487. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21488. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21489. };
  21490. this.updateFunction = function (particles) {
  21491. for (var index = 0; index < particles.length; index++) {
  21492. var particle = particles[index];
  21493. particle.age += _this._scaledUpdateSpeed;
  21494. if (particle.age >= particle.lifeTime) {
  21495. _this.recycleParticle(particle);
  21496. index--;
  21497. continue;
  21498. }
  21499. else {
  21500. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21501. particle.color.addInPlace(_this._scaledColorStep);
  21502. if (particle.color.a < 0)
  21503. particle.color.a = 0;
  21504. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21505. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21506. particle.position.addInPlace(_this._scaledDirection);
  21507. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21508. particle.direction.addInPlace(_this._scaledGravity);
  21509. }
  21510. }
  21511. };
  21512. }
  21513. ParticleSystem.prototype.recycleParticle = function (particle) {
  21514. var lastParticle = this.particles.pop();
  21515. if (lastParticle !== particle) {
  21516. lastParticle.copyTo(particle);
  21517. this._stockParticles.push(lastParticle);
  21518. }
  21519. };
  21520. ParticleSystem.prototype.getCapacity = function () {
  21521. return this._capacity;
  21522. };
  21523. ParticleSystem.prototype.isAlive = function () {
  21524. return this._alive;
  21525. };
  21526. ParticleSystem.prototype.isStarted = function () {
  21527. return this._started;
  21528. };
  21529. ParticleSystem.prototype.start = function () {
  21530. this._started = true;
  21531. this._stopped = false;
  21532. this._actualFrame = 0;
  21533. };
  21534. ParticleSystem.prototype.stop = function () {
  21535. this._stopped = true;
  21536. };
  21537. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21538. var offset = index * 11;
  21539. this._vertices[offset] = particle.position.x;
  21540. this._vertices[offset + 1] = particle.position.y;
  21541. this._vertices[offset + 2] = particle.position.z;
  21542. this._vertices[offset + 3] = particle.color.r;
  21543. this._vertices[offset + 4] = particle.color.g;
  21544. this._vertices[offset + 5] = particle.color.b;
  21545. this._vertices[offset + 6] = particle.color.a;
  21546. this._vertices[offset + 7] = particle.angle;
  21547. this._vertices[offset + 8] = particle.size;
  21548. this._vertices[offset + 9] = offsetX;
  21549. this._vertices[offset + 10] = offsetY;
  21550. };
  21551. ParticleSystem.prototype._update = function (newParticles) {
  21552. // Update current
  21553. this._alive = this.particles.length > 0;
  21554. this.updateFunction(this.particles);
  21555. // Add new ones
  21556. var worldMatrix;
  21557. if (this.emitter.position) {
  21558. worldMatrix = this.emitter.getWorldMatrix();
  21559. }
  21560. else {
  21561. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21562. }
  21563. var particle;
  21564. for (var index = 0; index < newParticles; index++) {
  21565. if (this.particles.length === this._capacity) {
  21566. break;
  21567. }
  21568. if (this._stockParticles.length !== 0) {
  21569. particle = this._stockParticles.pop();
  21570. particle.age = 0;
  21571. }
  21572. else {
  21573. particle = new BABYLON.Particle();
  21574. }
  21575. this.particles.push(particle);
  21576. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21577. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21578. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21579. particle.size = randomNumber(this.minSize, this.maxSize);
  21580. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21581. this.startPositionFunction(worldMatrix, particle.position, particle);
  21582. var step = randomNumber(0, 1.0);
  21583. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21584. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21585. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21586. }
  21587. };
  21588. ParticleSystem.prototype._getEffect = function () {
  21589. if (this._customEffect) {
  21590. return this._customEffect;
  21591. }
  21592. ;
  21593. var defines = [];
  21594. if (this._scene.clipPlane) {
  21595. defines.push("#define CLIPPLANE");
  21596. }
  21597. // Effect
  21598. var join = defines.join("\n");
  21599. if (this._cachedDefines !== join) {
  21600. this._cachedDefines = join;
  21601. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21602. }
  21603. return this._effect;
  21604. };
  21605. ParticleSystem.prototype.animate = function () {
  21606. if (!this._started)
  21607. return;
  21608. var effect = this._getEffect();
  21609. // Check
  21610. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21611. return;
  21612. if (this._currentRenderId === this._scene.getRenderId()) {
  21613. return;
  21614. }
  21615. this._currentRenderId = this._scene.getRenderId();
  21616. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21617. // determine the number of particles we need to create
  21618. var newParticles;
  21619. if (this.manualEmitCount > -1) {
  21620. newParticles = this.manualEmitCount;
  21621. this._newPartsExcess = 0;
  21622. this.manualEmitCount = 0;
  21623. }
  21624. else {
  21625. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21626. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21627. }
  21628. if (this._newPartsExcess > 1.0) {
  21629. newParticles += this._newPartsExcess >> 0;
  21630. this._newPartsExcess -= this._newPartsExcess >> 0;
  21631. }
  21632. this._alive = false;
  21633. if (!this._stopped) {
  21634. this._actualFrame += this._scaledUpdateSpeed;
  21635. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21636. this.stop();
  21637. }
  21638. else {
  21639. newParticles = 0;
  21640. }
  21641. this._update(newParticles);
  21642. // Stopped?
  21643. if (this._stopped) {
  21644. if (!this._alive) {
  21645. this._started = false;
  21646. if (this.disposeOnStop) {
  21647. this._scene._toBeDisposed.push(this);
  21648. }
  21649. }
  21650. }
  21651. // Update VBO
  21652. var offset = 0;
  21653. for (var index = 0; index < this.particles.length; index++) {
  21654. var particle = this.particles[index];
  21655. this._appendParticleVertex(offset++, particle, 0, 0);
  21656. this._appendParticleVertex(offset++, particle, 1, 0);
  21657. this._appendParticleVertex(offset++, particle, 1, 1);
  21658. this._appendParticleVertex(offset++, particle, 0, 1);
  21659. }
  21660. var engine = this._scene.getEngine();
  21661. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21662. };
  21663. ParticleSystem.prototype.render = function () {
  21664. var effect = this._getEffect();
  21665. // Check
  21666. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21667. return 0;
  21668. var engine = this._scene.getEngine();
  21669. // Render
  21670. engine.enableEffect(effect);
  21671. engine.setState(false);
  21672. var viewMatrix = this._scene.getViewMatrix();
  21673. effect.setTexture("diffuseSampler", this.particleTexture);
  21674. effect.setMatrix("view", viewMatrix);
  21675. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21676. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21677. if (this._scene.clipPlane) {
  21678. var clipPlane = this._scene.clipPlane;
  21679. var invView = viewMatrix.clone();
  21680. invView.invert();
  21681. effect.setMatrix("invView", invView);
  21682. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21683. }
  21684. // VBOs
  21685. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21686. // Draw order
  21687. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21688. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21689. }
  21690. else {
  21691. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21692. }
  21693. if (this.forceDepthWrite) {
  21694. engine.setDepthWrite(true);
  21695. }
  21696. engine.draw(true, 0, this.particles.length * 6);
  21697. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21698. return this.particles.length;
  21699. };
  21700. ParticleSystem.prototype.dispose = function () {
  21701. if (this._vertexBuffer) {
  21702. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21703. this._vertexBuffer = null;
  21704. }
  21705. if (this._indexBuffer) {
  21706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21707. this._indexBuffer = null;
  21708. }
  21709. if (this.particleTexture) {
  21710. this.particleTexture.dispose();
  21711. this.particleTexture = null;
  21712. }
  21713. // Remove from scene
  21714. var index = this._scene.particleSystems.indexOf(this);
  21715. this._scene.particleSystems.splice(index, 1);
  21716. // Callback
  21717. if (this.onDispose) {
  21718. this.onDispose();
  21719. }
  21720. };
  21721. // Clone
  21722. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21723. var result = new ParticleSystem(name, this._capacity, this._scene);
  21724. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21725. if (newEmitter === undefined) {
  21726. newEmitter = this.emitter;
  21727. }
  21728. result.emitter = newEmitter;
  21729. if (this.particleTexture) {
  21730. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21731. }
  21732. result.start();
  21733. return result;
  21734. };
  21735. ParticleSystem.prototype.serialize = function () {
  21736. var serializationObject = {};
  21737. serializationObject.name = this.name;
  21738. if (this.emitter.position) {
  21739. serializationObject.emitterId = this.emitter.id;
  21740. }
  21741. else {
  21742. serializationObject.emitter = this.emitter.asArray();
  21743. ;
  21744. }
  21745. serializationObject.capacity = this.getCapacity();
  21746. if (this.particleTexture) {
  21747. serializationObject.textureName = this.particleTexture.name;
  21748. }
  21749. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21750. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21751. serializationObject.minSize = this.minSize;
  21752. serializationObject.maxSize = this.maxSize;
  21753. serializationObject.minEmitPower = this.minEmitPower;
  21754. serializationObject.maxEmitPower = this.maxEmitPower;
  21755. serializationObject.minLifeTime = this.minLifeTime;
  21756. serializationObject.maxLifeTime = this.maxLifeTime;
  21757. serializationObject.emitRate = this.emitRate;
  21758. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21759. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21760. serializationObject.gravity = this.gravity.asArray();
  21761. serializationObject.direction1 = this.direction1.asArray();
  21762. serializationObject.direction2 = this.direction2.asArray();
  21763. serializationObject.color1 = this.color1.asArray();
  21764. serializationObject.color2 = this.color2.asArray();
  21765. serializationObject.colorDead = this.colorDead.asArray();
  21766. serializationObject.updateSpeed = this.updateSpeed;
  21767. serializationObject.targetStopDuration = this.targetStopDuration;
  21768. serializationObject.textureMask = this.textureMask.asArray();
  21769. serializationObject.blendMode = this.blendMode;
  21770. return serializationObject;
  21771. };
  21772. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21773. var name = parsedParticleSystem.name;
  21774. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21775. if (parsedParticleSystem.textureName) {
  21776. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21777. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21778. }
  21779. if (parsedParticleSystem.emitterId) {
  21780. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21781. }
  21782. else {
  21783. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21784. }
  21785. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21786. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21787. particleSystem.minSize = parsedParticleSystem.minSize;
  21788. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21789. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21790. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21791. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21792. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21793. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21794. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21795. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21796. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21797. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21798. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21799. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21800. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21801. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21802. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21803. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21804. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21805. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21806. particleSystem.start();
  21807. return particleSystem;
  21808. };
  21809. // Statics
  21810. ParticleSystem.BLENDMODE_ONEONE = 0;
  21811. ParticleSystem.BLENDMODE_STANDARD = 1;
  21812. return ParticleSystem;
  21813. })();
  21814. BABYLON.ParticleSystem = ParticleSystem;
  21815. })(BABYLON || (BABYLON = {}));
  21816. var BABYLON;
  21817. (function (BABYLON) {
  21818. var AnimationRange = (function () {
  21819. function AnimationRange(name, from, to) {
  21820. this.name = name;
  21821. this.from = from;
  21822. this.to = to;
  21823. }
  21824. return AnimationRange;
  21825. })();
  21826. BABYLON.AnimationRange = AnimationRange;
  21827. /**
  21828. * Composed of a frame, and an action function
  21829. */
  21830. var AnimationEvent = (function () {
  21831. function AnimationEvent(frame, action, onlyOnce) {
  21832. this.frame = frame;
  21833. this.action = action;
  21834. this.onlyOnce = onlyOnce;
  21835. this.isDone = false;
  21836. }
  21837. return AnimationEvent;
  21838. })();
  21839. BABYLON.AnimationEvent = AnimationEvent;
  21840. var Animation = (function () {
  21841. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21842. this.name = name;
  21843. this.targetProperty = targetProperty;
  21844. this.framePerSecond = framePerSecond;
  21845. this.dataType = dataType;
  21846. this.loopMode = loopMode;
  21847. this._offsetsCache = {};
  21848. this._highLimitsCache = {};
  21849. this._stopped = false;
  21850. // The set of event that will be linked to this animation
  21851. this._events = new Array();
  21852. this.allowMatricesInterpolation = false;
  21853. this._ranges = {};
  21854. this.targetPropertyPath = targetProperty.split(".");
  21855. this.dataType = dataType;
  21856. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21857. }
  21858. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21859. var dataType = undefined;
  21860. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21861. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21862. }
  21863. else if (from instanceof BABYLON.Quaternion) {
  21864. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21865. }
  21866. else if (from instanceof BABYLON.Vector3) {
  21867. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21868. }
  21869. else if (from instanceof BABYLON.Vector2) {
  21870. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21871. }
  21872. else if (from instanceof BABYLON.Color3) {
  21873. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21874. }
  21875. if (dataType == undefined) {
  21876. return null;
  21877. }
  21878. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21879. var keys = [];
  21880. keys.push({ frame: 0, value: from });
  21881. keys.push({ frame: totalFrame, value: to });
  21882. animation.setKeys(keys);
  21883. if (easingFunction !== undefined) {
  21884. animation.setEasingFunction(easingFunction);
  21885. }
  21886. return animation;
  21887. };
  21888. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21889. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21890. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21891. };
  21892. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21893. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21894. node.animations.push(animation);
  21895. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21896. };
  21897. // Methods
  21898. /**
  21899. * Add an event to this animation.
  21900. */
  21901. Animation.prototype.addEvent = function (event) {
  21902. this._events.push(event);
  21903. };
  21904. /**
  21905. * Remove all events found at the given frame
  21906. * @param frame
  21907. */
  21908. Animation.prototype.removeEvents = function (frame) {
  21909. for (var index = 0; index < this._events.length; index++) {
  21910. if (this._events[index].frame === frame) {
  21911. this._events.splice(index, 1);
  21912. index--;
  21913. }
  21914. }
  21915. };
  21916. Animation.prototype.createRange = function (name, from, to) {
  21917. // check name not already in use; could happen for bones after serialized
  21918. if (!this._ranges[name]) {
  21919. this._ranges[name] = new AnimationRange(name, from, to);
  21920. }
  21921. };
  21922. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21923. if (deleteFrames === void 0) { deleteFrames = true; }
  21924. if (this._ranges[name]) {
  21925. if (deleteFrames) {
  21926. var from = this._ranges[name].from;
  21927. var to = this._ranges[name].to;
  21928. // this loop MUST go high to low for multiple splices to work
  21929. for (var key = this._keys.length - 1; key >= 0; key--) {
  21930. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21931. this._keys.splice(key, 1);
  21932. }
  21933. }
  21934. }
  21935. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21936. }
  21937. };
  21938. Animation.prototype.getRange = function (name) {
  21939. return this._ranges[name];
  21940. };
  21941. Animation.prototype.reset = function () {
  21942. this._offsetsCache = {};
  21943. this._highLimitsCache = {};
  21944. this.currentFrame = 0;
  21945. };
  21946. Animation.prototype.isStopped = function () {
  21947. return this._stopped;
  21948. };
  21949. Animation.prototype.getKeys = function () {
  21950. return this._keys;
  21951. };
  21952. Animation.prototype.getHighestFrame = function () {
  21953. var ret = 0;
  21954. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21955. if (ret < this._keys[key].frame) {
  21956. ret = this._keys[key].frame;
  21957. }
  21958. }
  21959. return ret;
  21960. };
  21961. Animation.prototype.getEasingFunction = function () {
  21962. return this._easingFunction;
  21963. };
  21964. Animation.prototype.setEasingFunction = function (easingFunction) {
  21965. this._easingFunction = easingFunction;
  21966. };
  21967. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21968. return startValue + (endValue - startValue) * gradient;
  21969. };
  21970. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21971. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21972. };
  21973. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21974. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21975. };
  21976. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21977. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21978. };
  21979. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21980. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21981. };
  21982. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21983. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21984. };
  21985. Animation.prototype.clone = function () {
  21986. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21987. if (this._keys) {
  21988. clone.setKeys(this._keys);
  21989. }
  21990. return clone;
  21991. };
  21992. Animation.prototype.setKeys = function (values) {
  21993. this._keys = values.slice(0);
  21994. this._offsetsCache = {};
  21995. this._highLimitsCache = {};
  21996. };
  21997. Animation.prototype._getKeyValue = function (value) {
  21998. if (typeof value === "function") {
  21999. return value();
  22000. }
  22001. return value;
  22002. };
  22003. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22004. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22005. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22006. }
  22007. this.currentFrame = currentFrame;
  22008. // Try to get a hash to find the right key
  22009. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  22010. if (this._keys[startKey].frame >= currentFrame) {
  22011. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22012. startKey--;
  22013. }
  22014. }
  22015. for (var key = startKey; key < this._keys.length; key++) {
  22016. if (this._keys[key + 1].frame >= currentFrame) {
  22017. var startValue = this._getKeyValue(this._keys[key].value);
  22018. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22019. // gradient : percent of currentFrame between the frame inf and the frame sup
  22020. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22021. // check for easingFunction and correction of gradient
  22022. if (this._easingFunction != null) {
  22023. gradient = this._easingFunction.ease(gradient);
  22024. }
  22025. switch (this.dataType) {
  22026. // Float
  22027. case Animation.ANIMATIONTYPE_FLOAT:
  22028. switch (loopMode) {
  22029. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22030. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22031. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22032. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22033. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22034. }
  22035. break;
  22036. // Quaternion
  22037. case Animation.ANIMATIONTYPE_QUATERNION:
  22038. var quaternion = null;
  22039. switch (loopMode) {
  22040. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22041. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22042. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22043. break;
  22044. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22045. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22046. break;
  22047. }
  22048. return quaternion;
  22049. // Vector3
  22050. case Animation.ANIMATIONTYPE_VECTOR3:
  22051. switch (loopMode) {
  22052. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22053. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22054. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22055. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22056. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22057. }
  22058. // Vector2
  22059. case Animation.ANIMATIONTYPE_VECTOR2:
  22060. switch (loopMode) {
  22061. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22062. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22063. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22064. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22065. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22066. }
  22067. // Color3
  22068. case Animation.ANIMATIONTYPE_COLOR3:
  22069. switch (loopMode) {
  22070. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22071. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22072. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22073. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22074. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22075. }
  22076. // Matrix
  22077. case Animation.ANIMATIONTYPE_MATRIX:
  22078. switch (loopMode) {
  22079. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22080. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22081. if (this.allowMatricesInterpolation) {
  22082. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22083. }
  22084. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22085. return startValue;
  22086. }
  22087. default:
  22088. break;
  22089. }
  22090. break;
  22091. }
  22092. }
  22093. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22094. };
  22095. Animation.prototype.setValue = function (currentValue) {
  22096. // Set value
  22097. if (this.targetPropertyPath.length > 1) {
  22098. var property = this._target[this.targetPropertyPath[0]];
  22099. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22100. property = property[this.targetPropertyPath[index]];
  22101. }
  22102. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22103. }
  22104. else {
  22105. this._target[this.targetPropertyPath[0]] = currentValue;
  22106. }
  22107. if (this._target.markAsDirty) {
  22108. this._target.markAsDirty(this.targetProperty);
  22109. }
  22110. };
  22111. Animation.prototype.goToFrame = function (frame) {
  22112. if (frame < this._keys[0].frame) {
  22113. frame = this._keys[0].frame;
  22114. }
  22115. else if (frame > this._keys[this._keys.length - 1].frame) {
  22116. frame = this._keys[this._keys.length - 1].frame;
  22117. }
  22118. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22119. this.setValue(currentValue);
  22120. };
  22121. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22122. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22123. this._stopped = true;
  22124. return false;
  22125. }
  22126. var returnValue = true;
  22127. // Adding a start key at frame 0 if missing
  22128. if (this._keys[0].frame !== 0) {
  22129. var newKey = { frame: 0, value: this._keys[0].value };
  22130. this._keys.splice(0, 0, newKey);
  22131. }
  22132. // Check limits
  22133. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22134. from = this._keys[0].frame;
  22135. }
  22136. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22137. to = this._keys[this._keys.length - 1].frame;
  22138. }
  22139. // Compute ratio
  22140. var range = to - from;
  22141. var offsetValue;
  22142. // ratio represents the frame delta between from and to
  22143. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22144. var highLimitValue = 0;
  22145. if (ratio > range && !loop) {
  22146. returnValue = false;
  22147. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22148. }
  22149. else {
  22150. // Get max value if required
  22151. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22152. var keyOffset = to.toString() + from.toString();
  22153. if (!this._offsetsCache[keyOffset]) {
  22154. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22155. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22156. switch (this.dataType) {
  22157. // Float
  22158. case Animation.ANIMATIONTYPE_FLOAT:
  22159. this._offsetsCache[keyOffset] = toValue - fromValue;
  22160. break;
  22161. // Quaternion
  22162. case Animation.ANIMATIONTYPE_QUATERNION:
  22163. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22164. break;
  22165. // Vector3
  22166. case Animation.ANIMATIONTYPE_VECTOR3:
  22167. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22168. // Vector2
  22169. case Animation.ANIMATIONTYPE_VECTOR2:
  22170. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22171. // Color3
  22172. case Animation.ANIMATIONTYPE_COLOR3:
  22173. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22174. default:
  22175. break;
  22176. }
  22177. this._highLimitsCache[keyOffset] = toValue;
  22178. }
  22179. highLimitValue = this._highLimitsCache[keyOffset];
  22180. offsetValue = this._offsetsCache[keyOffset];
  22181. }
  22182. }
  22183. if (offsetValue === undefined) {
  22184. switch (this.dataType) {
  22185. // Float
  22186. case Animation.ANIMATIONTYPE_FLOAT:
  22187. offsetValue = 0;
  22188. break;
  22189. // Quaternion
  22190. case Animation.ANIMATIONTYPE_QUATERNION:
  22191. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22192. break;
  22193. // Vector3
  22194. case Animation.ANIMATIONTYPE_VECTOR3:
  22195. offsetValue = BABYLON.Vector3.Zero();
  22196. break;
  22197. // Vector2
  22198. case Animation.ANIMATIONTYPE_VECTOR2:
  22199. offsetValue = BABYLON.Vector2.Zero();
  22200. break;
  22201. // Color3
  22202. case Animation.ANIMATIONTYPE_COLOR3:
  22203. offsetValue = BABYLON.Color3.Black();
  22204. }
  22205. }
  22206. // Compute value
  22207. var repeatCount = (ratio / range) >> 0;
  22208. var currentFrame = returnValue ? from + ratio % range : to;
  22209. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22210. // Set value
  22211. this.setValue(currentValue);
  22212. // Check events
  22213. for (var index = 0; index < this._events.length; index++) {
  22214. if (currentFrame >= this._events[index].frame) {
  22215. var event = this._events[index];
  22216. if (!event.isDone) {
  22217. // If event should be done only once, remove it.
  22218. if (event.onlyOnce) {
  22219. this._events.splice(index, 1);
  22220. index--;
  22221. }
  22222. event.isDone = true;
  22223. event.action();
  22224. } // Don't do anything if the event has already be done.
  22225. }
  22226. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22227. // reset event, the animation is looping
  22228. this._events[index].isDone = false;
  22229. }
  22230. }
  22231. if (!returnValue) {
  22232. this._stopped = true;
  22233. }
  22234. return returnValue;
  22235. };
  22236. Animation.prototype.serialize = function () {
  22237. var serializationObject = {};
  22238. serializationObject.name = this.name;
  22239. serializationObject.property = this.targetProperty;
  22240. serializationObject.framePerSecond = this.framePerSecond;
  22241. serializationObject.dataType = this.dataType;
  22242. serializationObject.loopBehavior = this.loopMode;
  22243. var dataType = this.dataType;
  22244. serializationObject.keys = [];
  22245. var keys = this.getKeys();
  22246. for (var index = 0; index < keys.length; index++) {
  22247. var animationKey = keys[index];
  22248. var key = {};
  22249. key.frame = animationKey.frame;
  22250. switch (dataType) {
  22251. case Animation.ANIMATIONTYPE_FLOAT:
  22252. key.values = [animationKey.value];
  22253. break;
  22254. case Animation.ANIMATIONTYPE_QUATERNION:
  22255. case Animation.ANIMATIONTYPE_MATRIX:
  22256. case Animation.ANIMATIONTYPE_VECTOR3:
  22257. case Animation.ANIMATIONTYPE_COLOR3:
  22258. key.values = animationKey.value.asArray();
  22259. break;
  22260. }
  22261. serializationObject.keys.push(key);
  22262. }
  22263. serializationObject.ranges = [];
  22264. for (var name in this._ranges) {
  22265. var range = {};
  22266. range.name = name;
  22267. range.from = this._ranges[name].from;
  22268. range.to = this._ranges[name].to;
  22269. serializationObject.ranges.push(range);
  22270. }
  22271. return serializationObject;
  22272. };
  22273. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22274. get: function () {
  22275. return Animation._ANIMATIONTYPE_FLOAT;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22281. get: function () {
  22282. return Animation._ANIMATIONTYPE_VECTOR3;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22288. get: function () {
  22289. return Animation._ANIMATIONTYPE_VECTOR2;
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22295. get: function () {
  22296. return Animation._ANIMATIONTYPE_QUATERNION;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22302. get: function () {
  22303. return Animation._ANIMATIONTYPE_MATRIX;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22309. get: function () {
  22310. return Animation._ANIMATIONTYPE_COLOR3;
  22311. },
  22312. enumerable: true,
  22313. configurable: true
  22314. });
  22315. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22316. get: function () {
  22317. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22323. get: function () {
  22324. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22330. get: function () {
  22331. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Animation.Parse = function (parsedAnimation) {
  22337. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22338. var dataType = parsedAnimation.dataType;
  22339. var keys = [];
  22340. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22341. var key = parsedAnimation.keys[index];
  22342. var data;
  22343. switch (dataType) {
  22344. case Animation.ANIMATIONTYPE_FLOAT:
  22345. data = key.values[0];
  22346. break;
  22347. case Animation.ANIMATIONTYPE_QUATERNION:
  22348. data = BABYLON.Quaternion.FromArray(key.values);
  22349. break;
  22350. case Animation.ANIMATIONTYPE_MATRIX:
  22351. data = BABYLON.Matrix.FromArray(key.values);
  22352. break;
  22353. case Animation.ANIMATIONTYPE_COLOR3:
  22354. data = BABYLON.Color3.FromArray(key.values);
  22355. break;
  22356. case Animation.ANIMATIONTYPE_VECTOR3:
  22357. default:
  22358. data = BABYLON.Vector3.FromArray(key.values);
  22359. break;
  22360. }
  22361. keys.push({
  22362. frame: key.frame,
  22363. value: data
  22364. });
  22365. }
  22366. animation.setKeys(keys);
  22367. if (parsedAnimation.ranges) {
  22368. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22369. data = parsedAnimation.ranges[index];
  22370. animation.createRange(data.name, data.from, data.to);
  22371. }
  22372. }
  22373. return animation;
  22374. };
  22375. Animation.AppendSerializedAnimations = function (source, destination) {
  22376. if (source.animations) {
  22377. destination.animations = [];
  22378. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22379. var animation = source.animations[animationIndex];
  22380. destination.animations.push(animation.serialize());
  22381. }
  22382. }
  22383. };
  22384. // Statics
  22385. Animation._ANIMATIONTYPE_FLOAT = 0;
  22386. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22387. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22388. Animation._ANIMATIONTYPE_MATRIX = 3;
  22389. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22390. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22391. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22392. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22393. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22394. return Animation;
  22395. })();
  22396. BABYLON.Animation = Animation;
  22397. })(BABYLON || (BABYLON = {}));
  22398. var BABYLON;
  22399. (function (BABYLON) {
  22400. var Animatable = (function () {
  22401. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22402. if (fromFrame === void 0) { fromFrame = 0; }
  22403. if (toFrame === void 0) { toFrame = 100; }
  22404. if (loopAnimation === void 0) { loopAnimation = false; }
  22405. if (speedRatio === void 0) { speedRatio = 1.0; }
  22406. this.target = target;
  22407. this.fromFrame = fromFrame;
  22408. this.toFrame = toFrame;
  22409. this.loopAnimation = loopAnimation;
  22410. this.speedRatio = speedRatio;
  22411. this.onAnimationEnd = onAnimationEnd;
  22412. this._animations = new Array();
  22413. this._paused = false;
  22414. this.animationStarted = false;
  22415. if (animations) {
  22416. this.appendAnimations(target, animations);
  22417. }
  22418. this._scene = scene;
  22419. scene._activeAnimatables.push(this);
  22420. }
  22421. // Methods
  22422. Animatable.prototype.getAnimations = function () {
  22423. return this._animations;
  22424. };
  22425. Animatable.prototype.appendAnimations = function (target, animations) {
  22426. for (var index = 0; index < animations.length; index++) {
  22427. var animation = animations[index];
  22428. animation._target = target;
  22429. this._animations.push(animation);
  22430. }
  22431. };
  22432. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22433. var animations = this._animations;
  22434. for (var index = 0; index < animations.length; index++) {
  22435. if (animations[index].targetProperty === property) {
  22436. return animations[index];
  22437. }
  22438. }
  22439. return null;
  22440. };
  22441. Animatable.prototype.reset = function () {
  22442. var animations = this._animations;
  22443. for (var index = 0; index < animations.length; index++) {
  22444. animations[index].reset();
  22445. }
  22446. this._localDelayOffset = null;
  22447. this._pausedDelay = null;
  22448. };
  22449. Animatable.prototype.goToFrame = function (frame) {
  22450. var animations = this._animations;
  22451. for (var index = 0; index < animations.length; index++) {
  22452. animations[index].goToFrame(frame);
  22453. }
  22454. };
  22455. Animatable.prototype.pause = function () {
  22456. if (this._paused) {
  22457. return;
  22458. }
  22459. this._paused = true;
  22460. };
  22461. Animatable.prototype.restart = function () {
  22462. this._paused = false;
  22463. };
  22464. Animatable.prototype.stop = function () {
  22465. var index = this._scene._activeAnimatables.indexOf(this);
  22466. if (index > -1) {
  22467. this._scene._activeAnimatables.splice(index, 1);
  22468. }
  22469. if (this.onAnimationEnd) {
  22470. this.onAnimationEnd();
  22471. }
  22472. };
  22473. Animatable.prototype._animate = function (delay) {
  22474. if (this._paused) {
  22475. this.animationStarted = false;
  22476. if (!this._pausedDelay) {
  22477. this._pausedDelay = delay;
  22478. }
  22479. return true;
  22480. }
  22481. if (!this._localDelayOffset) {
  22482. this._localDelayOffset = delay;
  22483. }
  22484. else if (this._pausedDelay) {
  22485. this._localDelayOffset += delay - this._pausedDelay;
  22486. this._pausedDelay = null;
  22487. }
  22488. // Animating
  22489. var running = false;
  22490. var animations = this._animations;
  22491. var index;
  22492. for (index = 0; index < animations.length; index++) {
  22493. var animation = animations[index];
  22494. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22495. running = running || isRunning;
  22496. }
  22497. this.animationStarted = running;
  22498. if (!running) {
  22499. // Remove from active animatables
  22500. index = this._scene._activeAnimatables.indexOf(this);
  22501. this._scene._activeAnimatables.splice(index, 1);
  22502. }
  22503. if (!running && this.onAnimationEnd) {
  22504. this.onAnimationEnd();
  22505. }
  22506. return running;
  22507. };
  22508. return Animatable;
  22509. })();
  22510. BABYLON.Animatable = Animatable;
  22511. })(BABYLON || (BABYLON = {}));
  22512. var BABYLON;
  22513. (function (BABYLON) {
  22514. var EasingFunction = (function () {
  22515. function EasingFunction() {
  22516. // Properties
  22517. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22518. }
  22519. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22520. get: function () {
  22521. return EasingFunction._EASINGMODE_EASEIN;
  22522. },
  22523. enumerable: true,
  22524. configurable: true
  22525. });
  22526. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22527. get: function () {
  22528. return EasingFunction._EASINGMODE_EASEOUT;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22534. get: function () {
  22535. return EasingFunction._EASINGMODE_EASEINOUT;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22541. var n = Math.min(Math.max(easingMode, 0), 2);
  22542. this._easingMode = n;
  22543. };
  22544. EasingFunction.prototype.getEasingMode = function () {
  22545. return this._easingMode;
  22546. };
  22547. EasingFunction.prototype.easeInCore = function (gradient) {
  22548. throw new Error('You must implement this method');
  22549. };
  22550. EasingFunction.prototype.ease = function (gradient) {
  22551. switch (this._easingMode) {
  22552. case EasingFunction.EASINGMODE_EASEIN:
  22553. return this.easeInCore(gradient);
  22554. case EasingFunction.EASINGMODE_EASEOUT:
  22555. return (1 - this.easeInCore(1 - gradient));
  22556. }
  22557. if (gradient >= 0.5) {
  22558. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22559. }
  22560. return (this.easeInCore(gradient * 2) * 0.5);
  22561. };
  22562. //Statics
  22563. EasingFunction._EASINGMODE_EASEIN = 0;
  22564. EasingFunction._EASINGMODE_EASEOUT = 1;
  22565. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22566. return EasingFunction;
  22567. })();
  22568. BABYLON.EasingFunction = EasingFunction;
  22569. var CircleEase = (function (_super) {
  22570. __extends(CircleEase, _super);
  22571. function CircleEase() {
  22572. _super.apply(this, arguments);
  22573. }
  22574. CircleEase.prototype.easeInCore = function (gradient) {
  22575. gradient = Math.max(0, Math.min(1, gradient));
  22576. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22577. };
  22578. return CircleEase;
  22579. })(EasingFunction);
  22580. BABYLON.CircleEase = CircleEase;
  22581. var BackEase = (function (_super) {
  22582. __extends(BackEase, _super);
  22583. function BackEase(amplitude) {
  22584. if (amplitude === void 0) { amplitude = 1; }
  22585. _super.call(this);
  22586. this.amplitude = amplitude;
  22587. }
  22588. BackEase.prototype.easeInCore = function (gradient) {
  22589. var num = Math.max(0, this.amplitude);
  22590. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22591. };
  22592. return BackEase;
  22593. })(EasingFunction);
  22594. BABYLON.BackEase = BackEase;
  22595. var BounceEase = (function (_super) {
  22596. __extends(BounceEase, _super);
  22597. function BounceEase(bounces, bounciness) {
  22598. if (bounces === void 0) { bounces = 3; }
  22599. if (bounciness === void 0) { bounciness = 2; }
  22600. _super.call(this);
  22601. this.bounces = bounces;
  22602. this.bounciness = bounciness;
  22603. }
  22604. BounceEase.prototype.easeInCore = function (gradient) {
  22605. var y = Math.max(0.0, this.bounces);
  22606. var bounciness = this.bounciness;
  22607. if (bounciness <= 1.0) {
  22608. bounciness = 1.001;
  22609. }
  22610. var num9 = Math.pow(bounciness, y);
  22611. var num5 = 1.0 - bounciness;
  22612. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22613. var num15 = gradient * num4;
  22614. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22615. var num3 = Math.floor(num65);
  22616. var num13 = num3 + 1.0;
  22617. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22618. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22619. var num7 = (num8 + num12) * 0.5;
  22620. var num6 = gradient - num7;
  22621. var num2 = num7 - num8;
  22622. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22623. };
  22624. return BounceEase;
  22625. })(EasingFunction);
  22626. BABYLON.BounceEase = BounceEase;
  22627. var CubicEase = (function (_super) {
  22628. __extends(CubicEase, _super);
  22629. function CubicEase() {
  22630. _super.apply(this, arguments);
  22631. }
  22632. CubicEase.prototype.easeInCore = function (gradient) {
  22633. return (gradient * gradient * gradient);
  22634. };
  22635. return CubicEase;
  22636. })(EasingFunction);
  22637. BABYLON.CubicEase = CubicEase;
  22638. var ElasticEase = (function (_super) {
  22639. __extends(ElasticEase, _super);
  22640. function ElasticEase(oscillations, springiness) {
  22641. if (oscillations === void 0) { oscillations = 3; }
  22642. if (springiness === void 0) { springiness = 3; }
  22643. _super.call(this);
  22644. this.oscillations = oscillations;
  22645. this.springiness = springiness;
  22646. }
  22647. ElasticEase.prototype.easeInCore = function (gradient) {
  22648. var num2;
  22649. var num3 = Math.max(0.0, this.oscillations);
  22650. var num = Math.max(0.0, this.springiness);
  22651. if (num == 0) {
  22652. num2 = gradient;
  22653. }
  22654. else {
  22655. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22656. }
  22657. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22658. };
  22659. return ElasticEase;
  22660. })(EasingFunction);
  22661. BABYLON.ElasticEase = ElasticEase;
  22662. var ExponentialEase = (function (_super) {
  22663. __extends(ExponentialEase, _super);
  22664. function ExponentialEase(exponent) {
  22665. if (exponent === void 0) { exponent = 2; }
  22666. _super.call(this);
  22667. this.exponent = exponent;
  22668. }
  22669. ExponentialEase.prototype.easeInCore = function (gradient) {
  22670. if (this.exponent <= 0) {
  22671. return gradient;
  22672. }
  22673. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22674. };
  22675. return ExponentialEase;
  22676. })(EasingFunction);
  22677. BABYLON.ExponentialEase = ExponentialEase;
  22678. var PowerEase = (function (_super) {
  22679. __extends(PowerEase, _super);
  22680. function PowerEase(power) {
  22681. if (power === void 0) { power = 2; }
  22682. _super.call(this);
  22683. this.power = power;
  22684. }
  22685. PowerEase.prototype.easeInCore = function (gradient) {
  22686. var y = Math.max(0.0, this.power);
  22687. return Math.pow(gradient, y);
  22688. };
  22689. return PowerEase;
  22690. })(EasingFunction);
  22691. BABYLON.PowerEase = PowerEase;
  22692. var QuadraticEase = (function (_super) {
  22693. __extends(QuadraticEase, _super);
  22694. function QuadraticEase() {
  22695. _super.apply(this, arguments);
  22696. }
  22697. QuadraticEase.prototype.easeInCore = function (gradient) {
  22698. return (gradient * gradient);
  22699. };
  22700. return QuadraticEase;
  22701. })(EasingFunction);
  22702. BABYLON.QuadraticEase = QuadraticEase;
  22703. var QuarticEase = (function (_super) {
  22704. __extends(QuarticEase, _super);
  22705. function QuarticEase() {
  22706. _super.apply(this, arguments);
  22707. }
  22708. QuarticEase.prototype.easeInCore = function (gradient) {
  22709. return (gradient * gradient * gradient * gradient);
  22710. };
  22711. return QuarticEase;
  22712. })(EasingFunction);
  22713. BABYLON.QuarticEase = QuarticEase;
  22714. var QuinticEase = (function (_super) {
  22715. __extends(QuinticEase, _super);
  22716. function QuinticEase() {
  22717. _super.apply(this, arguments);
  22718. }
  22719. QuinticEase.prototype.easeInCore = function (gradient) {
  22720. return (gradient * gradient * gradient * gradient * gradient);
  22721. };
  22722. return QuinticEase;
  22723. })(EasingFunction);
  22724. BABYLON.QuinticEase = QuinticEase;
  22725. var SineEase = (function (_super) {
  22726. __extends(SineEase, _super);
  22727. function SineEase() {
  22728. _super.apply(this, arguments);
  22729. }
  22730. SineEase.prototype.easeInCore = function (gradient) {
  22731. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22732. };
  22733. return SineEase;
  22734. })(EasingFunction);
  22735. BABYLON.SineEase = SineEase;
  22736. var BezierCurveEase = (function (_super) {
  22737. __extends(BezierCurveEase, _super);
  22738. function BezierCurveEase(x1, y1, x2, y2) {
  22739. if (x1 === void 0) { x1 = 0; }
  22740. if (y1 === void 0) { y1 = 0; }
  22741. if (x2 === void 0) { x2 = 1; }
  22742. if (y2 === void 0) { y2 = 1; }
  22743. _super.call(this);
  22744. this.x1 = x1;
  22745. this.y1 = y1;
  22746. this.x2 = x2;
  22747. this.y2 = y2;
  22748. }
  22749. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22750. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22751. };
  22752. return BezierCurveEase;
  22753. })(EasingFunction);
  22754. BABYLON.BezierCurveEase = BezierCurveEase;
  22755. })(BABYLON || (BABYLON = {}));
  22756. var BABYLON;
  22757. (function (BABYLON) {
  22758. var Bone = (function (_super) {
  22759. __extends(Bone, _super);
  22760. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22761. _super.call(this, name, skeleton.getScene());
  22762. this.name = name;
  22763. this.children = new Array();
  22764. this.animations = new Array();
  22765. this._worldTransform = new BABYLON.Matrix();
  22766. this._absoluteTransform = new BABYLON.Matrix();
  22767. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22768. this._skeleton = skeleton;
  22769. this._matrix = matrix;
  22770. this._baseMatrix = matrix;
  22771. this._restPose = restPose ? restPose : matrix.clone();
  22772. skeleton.bones.push(this);
  22773. if (parentBone) {
  22774. this._parent = parentBone;
  22775. parentBone.children.push(this);
  22776. }
  22777. else {
  22778. this._parent = null;
  22779. }
  22780. this._updateDifferenceMatrix();
  22781. }
  22782. // Members
  22783. Bone.prototype.getParent = function () {
  22784. return this._parent;
  22785. };
  22786. Bone.prototype.getLocalMatrix = function () {
  22787. return this._matrix;
  22788. };
  22789. Bone.prototype.getBaseMatrix = function () {
  22790. return this._baseMatrix;
  22791. };
  22792. Bone.prototype.getRestPose = function () {
  22793. return this._restPose;
  22794. };
  22795. Bone.prototype.returnToRest = function () {
  22796. this.updateMatrix(this._restPose.clone());
  22797. };
  22798. Bone.prototype.getWorldMatrix = function () {
  22799. return this._worldTransform;
  22800. };
  22801. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22802. return this._invertedAbsoluteTransform;
  22803. };
  22804. Bone.prototype.getAbsoluteTransform = function () {
  22805. return this._absoluteTransform;
  22806. };
  22807. // Methods
  22808. Bone.prototype.updateMatrix = function (matrix) {
  22809. this._baseMatrix = matrix.clone();
  22810. this._matrix = matrix.clone();
  22811. this._skeleton._markAsDirty();
  22812. this._updateDifferenceMatrix();
  22813. };
  22814. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  22815. if (!rootMatrix) {
  22816. rootMatrix = this._baseMatrix;
  22817. }
  22818. if (this._parent) {
  22819. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22820. }
  22821. else {
  22822. this._absoluteTransform.copyFrom(rootMatrix);
  22823. }
  22824. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22825. for (var index = 0; index < this.children.length; index++) {
  22826. this.children[index]._updateDifferenceMatrix();
  22827. }
  22828. };
  22829. Bone.prototype.markAsDirty = function () {
  22830. this._currentRenderId++;
  22831. this._skeleton._markAsDirty();
  22832. };
  22833. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22834. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22835. // all animation may be coming from a library skeleton, so may need to create animation
  22836. if (this.animations.length === 0) {
  22837. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22838. }
  22839. // get animation info / verify there is such a range from the source bone
  22840. var sourceRange = source.animations[0].getRange(rangeName);
  22841. if (!sourceRange) {
  22842. return false;
  22843. }
  22844. var from = sourceRange.from;
  22845. var to = sourceRange.to;
  22846. var sourceKeys = source.animations[0].getKeys();
  22847. // rescaling prep
  22848. var sourceBoneLength = source.length;
  22849. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22850. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22851. var destKeys = this.animations[0].getKeys();
  22852. // loop vars declaration / initialization
  22853. var orig;
  22854. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22855. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22856. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22857. var mat;
  22858. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22859. orig = sourceKeys[key];
  22860. if (orig.frame >= from && orig.frame <= to) {
  22861. if (scalingReqd) {
  22862. orig.value.decompose(origScale, origRotation, origTranslation);
  22863. origTranslation.scaleInPlace(ratio);
  22864. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22865. }
  22866. else {
  22867. mat = orig.value;
  22868. }
  22869. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22870. }
  22871. }
  22872. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22873. return true;
  22874. };
  22875. return Bone;
  22876. })(BABYLON.Node);
  22877. BABYLON.Bone = Bone;
  22878. })(BABYLON || (BABYLON = {}));
  22879. var BABYLON;
  22880. (function (BABYLON) {
  22881. var Skeleton = (function () {
  22882. function Skeleton(name, id, scene) {
  22883. this.name = name;
  22884. this.id = id;
  22885. this.bones = new Array();
  22886. this.needInitialSkinMatrix = false;
  22887. this._isDirty = true;
  22888. this._meshesWithPoseMatrix = new Array();
  22889. this._identity = BABYLON.Matrix.Identity();
  22890. this._ranges = {};
  22891. this.bones = [];
  22892. this._scene = scene;
  22893. scene.skeletons.push(this);
  22894. this.prepare();
  22895. //make sure it will recalculate the matrix next time prepare is called.
  22896. this._isDirty = true;
  22897. }
  22898. // Members
  22899. Skeleton.prototype.getTransformMatrices = function (mesh) {
  22900. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  22901. return mesh._bonesTransformMatrices;
  22902. }
  22903. return this._transformMatrices;
  22904. };
  22905. Skeleton.prototype.getScene = function () {
  22906. return this._scene;
  22907. };
  22908. // Methods
  22909. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22910. // check name not already in use
  22911. if (!this._ranges[name]) {
  22912. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22913. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22914. if (this.bones[i].animations[0]) {
  22915. this.bones[i].animations[0].createRange(name, from, to);
  22916. }
  22917. }
  22918. }
  22919. };
  22920. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22921. if (deleteFrames === void 0) { deleteFrames = true; }
  22922. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22923. if (this.bones[i].animations[0]) {
  22924. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22925. }
  22926. }
  22927. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22928. };
  22929. Skeleton.prototype.getAnimationRange = function (name) {
  22930. return this._ranges[name];
  22931. };
  22932. /**
  22933. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22934. */
  22935. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22936. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22937. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22938. return false;
  22939. }
  22940. var ret = true;
  22941. var frameOffset = this._getHighestAnimationFrame() + 1;
  22942. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22943. var boneDict = {};
  22944. var sourceBones = source.bones;
  22945. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22946. boneDict[sourceBones[i].name] = sourceBones[i];
  22947. }
  22948. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22949. var boneName = this.bones[i].name;
  22950. var sourceBone = boneDict[boneName];
  22951. if (sourceBone) {
  22952. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22953. }
  22954. else {
  22955. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22956. ret = false;
  22957. }
  22958. }
  22959. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22960. var range = source.getAnimationRange(name);
  22961. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22962. return ret;
  22963. };
  22964. Skeleton.prototype.returnToRest = function () {
  22965. for (var index = 0; index < this.bones.length; index++) {
  22966. this.bones[index].returnToRest();
  22967. }
  22968. };
  22969. Skeleton.prototype._getHighestAnimationFrame = function () {
  22970. var ret = 0;
  22971. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22972. if (this.bones[i].animations[0]) {
  22973. var highest = this.bones[i].animations[0].getHighestFrame();
  22974. if (ret < highest) {
  22975. ret = highest;
  22976. }
  22977. }
  22978. }
  22979. return ret;
  22980. };
  22981. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22982. var range = this.getAnimationRange(name);
  22983. if (!range) {
  22984. return null;
  22985. }
  22986. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22987. };
  22988. Skeleton.prototype._markAsDirty = function () {
  22989. this._isDirty = true;
  22990. };
  22991. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  22992. this._meshesWithPoseMatrix.push(mesh);
  22993. };
  22994. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  22995. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  22996. if (index > -1) {
  22997. this._meshesWithPoseMatrix.splice(index, 1);
  22998. }
  22999. };
  23000. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23001. for (var index = 0; index < this.bones.length; index++) {
  23002. var bone = this.bones[index];
  23003. var parentBone = bone.getParent();
  23004. if (parentBone) {
  23005. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23006. }
  23007. else {
  23008. if (initialSkinMatrix) {
  23009. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23010. }
  23011. else {
  23012. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23013. }
  23014. }
  23015. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23016. }
  23017. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23018. };
  23019. Skeleton.prototype.prepare = function () {
  23020. if (!this._isDirty) {
  23021. return;
  23022. }
  23023. if (this.needInitialSkinMatrix) {
  23024. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23025. var mesh = this._meshesWithPoseMatrix[index];
  23026. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23027. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23028. }
  23029. var poseMatrix = mesh.getPoseMatrix();
  23030. // Prepare bones
  23031. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23032. var bone = this.bones[boneIndex];
  23033. if (!bone.getParent()) {
  23034. var matrix = bone.getBaseMatrix();
  23035. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23036. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23037. }
  23038. }
  23039. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23040. }
  23041. }
  23042. else {
  23043. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23044. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23045. }
  23046. this._computeTransformMatrices(this._transformMatrices, null);
  23047. }
  23048. this._isDirty = false;
  23049. this._scene._activeBones += this.bones.length;
  23050. };
  23051. Skeleton.prototype.getAnimatables = function () {
  23052. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23053. this._animatables = [];
  23054. for (var index = 0; index < this.bones.length; index++) {
  23055. this._animatables.push(this.bones[index]);
  23056. }
  23057. }
  23058. return this._animatables;
  23059. };
  23060. Skeleton.prototype.clone = function (name, id) {
  23061. var result = new Skeleton(name, id || name, this._scene);
  23062. for (var index = 0; index < this.bones.length; index++) {
  23063. var source = this.bones[index];
  23064. var parentBone = null;
  23065. if (source.getParent()) {
  23066. var parentIndex = this.bones.indexOf(source.getParent());
  23067. parentBone = result.bones[parentIndex];
  23068. }
  23069. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23070. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23071. }
  23072. return result;
  23073. };
  23074. Skeleton.prototype.dispose = function () {
  23075. this._meshesWithPoseMatrix = [];
  23076. // Animations
  23077. this.getScene().stopAnimation(this);
  23078. // Remove from scene
  23079. this.getScene().removeSkeleton(this);
  23080. };
  23081. Skeleton.prototype.serialize = function () {
  23082. var serializationObject = {};
  23083. serializationObject.name = this.name;
  23084. serializationObject.id = this.id;
  23085. serializationObject.bones = [];
  23086. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23087. for (var index = 0; index < this.bones.length; index++) {
  23088. var bone = this.bones[index];
  23089. var serializedBone = {
  23090. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23091. name: bone.name,
  23092. matrix: bone.getLocalMatrix().toArray(),
  23093. rest: bone.getRestPose().toArray()
  23094. };
  23095. serializationObject.bones.push(serializedBone);
  23096. if (bone.length) {
  23097. serializedBone.length = bone.length;
  23098. }
  23099. if (bone.animations && bone.animations.length > 0) {
  23100. serializedBone.animation = bone.animations[0].serialize();
  23101. }
  23102. serializationObject.ranges = [];
  23103. for (var name in this._ranges) {
  23104. var range = {};
  23105. range.name = name;
  23106. range.from = this._ranges[name].from;
  23107. range.to = this._ranges[name].to;
  23108. serializationObject.ranges.push(range);
  23109. }
  23110. }
  23111. return serializationObject;
  23112. };
  23113. Skeleton.Parse = function (parsedSkeleton, scene) {
  23114. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23115. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23116. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23117. var parsedBone = parsedSkeleton.bones[index];
  23118. var parentBone = null;
  23119. if (parsedBone.parentBoneIndex > -1) {
  23120. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23121. }
  23122. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23123. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23124. if (parsedBone.length) {
  23125. bone.length = parsedBone.length;
  23126. }
  23127. if (parsedBone.animation) {
  23128. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23129. }
  23130. }
  23131. // placed after bones, so createAnimationRange can cascade down
  23132. if (parsedSkeleton.ranges) {
  23133. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23134. var data = parsedSkeleton.ranges[index];
  23135. skeleton.createAnimationRange(data.name, data.from, data.to);
  23136. }
  23137. }
  23138. return skeleton;
  23139. };
  23140. return Skeleton;
  23141. })();
  23142. BABYLON.Skeleton = Skeleton;
  23143. })(BABYLON || (BABYLON = {}));
  23144. var BABYLON;
  23145. (function (BABYLON) {
  23146. var PostProcess = (function () {
  23147. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23149. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23150. this.name = name;
  23151. this.width = -1;
  23152. this.height = -1;
  23153. this._reusable = false;
  23154. this._textures = new BABYLON.SmartArray(2);
  23155. this._currentRenderTextureInd = 0;
  23156. if (camera != null) {
  23157. this._camera = camera;
  23158. this._scene = camera.getScene();
  23159. camera.attachPostProcess(this);
  23160. this._engine = this._scene.getEngine();
  23161. }
  23162. else {
  23163. this._engine = engine;
  23164. }
  23165. this._renderRatio = ratio;
  23166. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23167. this._reusable = reusable || false;
  23168. this._textureType = textureType;
  23169. this._samplers = samplers || [];
  23170. this._samplers.push("textureSampler");
  23171. this._fragmentUrl = fragmentUrl;
  23172. this._parameters = parameters || [];
  23173. this.updateEffect(defines);
  23174. }
  23175. PostProcess.prototype.updateEffect = function (defines) {
  23176. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23177. };
  23178. PostProcess.prototype.isReusable = function () {
  23179. return this._reusable;
  23180. };
  23181. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23182. camera = camera || this._camera;
  23183. var scene = camera.getScene();
  23184. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23185. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23186. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23187. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23188. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23189. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23190. if (this._textures.length > 0) {
  23191. for (var i = 0; i < this._textures.length; i++) {
  23192. this._engine._releaseTexture(this._textures.data[i]);
  23193. }
  23194. this._textures.reset();
  23195. }
  23196. this.width = desiredWidth;
  23197. this.height = desiredHeight;
  23198. 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, type: this._textureType }));
  23199. if (this._reusable) {
  23200. 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, type: this._textureType }));
  23201. }
  23202. if (this.onSizeChanged) {
  23203. this.onSizeChanged();
  23204. }
  23205. }
  23206. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23207. if (this.onActivate) {
  23208. this.onActivate(camera);
  23209. }
  23210. // Clear
  23211. if (this.clearColor) {
  23212. this._engine.clear(this.clearColor, true, true);
  23213. }
  23214. else {
  23215. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23216. }
  23217. if (this._reusable) {
  23218. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23219. }
  23220. };
  23221. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23222. get: function () {
  23223. return this._effect.isSupported;
  23224. },
  23225. enumerable: true,
  23226. configurable: true
  23227. });
  23228. PostProcess.prototype.apply = function () {
  23229. // Check
  23230. if (!this._effect.isReady())
  23231. return null;
  23232. // States
  23233. this._engine.enableEffect(this._effect);
  23234. this._engine.setState(false);
  23235. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23236. this._engine.setDepthBuffer(false);
  23237. this._engine.setDepthWrite(false);
  23238. // Texture
  23239. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23240. // Parameters
  23241. if (this.onApply) {
  23242. this.onApply(this._effect);
  23243. }
  23244. return this._effect;
  23245. };
  23246. PostProcess.prototype.dispose = function (camera) {
  23247. camera = camera || this._camera;
  23248. if (this._textures.length > 0) {
  23249. for (var i = 0; i < this._textures.length; i++) {
  23250. this._engine._releaseTexture(this._textures.data[i]);
  23251. }
  23252. this._textures.reset();
  23253. }
  23254. if (!camera) {
  23255. return;
  23256. }
  23257. camera.detachPostProcess(this);
  23258. var index = camera._postProcesses.indexOf(this);
  23259. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23260. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23261. }
  23262. };
  23263. return PostProcess;
  23264. })();
  23265. BABYLON.PostProcess = PostProcess;
  23266. })(BABYLON || (BABYLON = {}));
  23267. var BABYLON;
  23268. (function (BABYLON) {
  23269. var PostProcessManager = (function () {
  23270. function PostProcessManager(scene) {
  23271. this._vertexDeclaration = [2];
  23272. this._vertexStrideSize = 2 * 4;
  23273. this._scene = scene;
  23274. }
  23275. PostProcessManager.prototype._prepareBuffers = function () {
  23276. if (this._vertexBuffer) {
  23277. return;
  23278. }
  23279. // VBO
  23280. var vertices = [];
  23281. vertices.push(1, 1);
  23282. vertices.push(-1, 1);
  23283. vertices.push(-1, -1);
  23284. vertices.push(1, -1);
  23285. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23286. // Indices
  23287. var indices = [];
  23288. indices.push(0);
  23289. indices.push(1);
  23290. indices.push(2);
  23291. indices.push(0);
  23292. indices.push(2);
  23293. indices.push(3);
  23294. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23295. };
  23296. // Methods
  23297. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23298. var postProcesses = this._scene.activeCamera._postProcesses;
  23299. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23300. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23301. return false;
  23302. }
  23303. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23304. return true;
  23305. };
  23306. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23307. var engine = this._scene.getEngine();
  23308. for (var index = 0; index < postProcesses.length; index++) {
  23309. if (index < postProcesses.length - 1) {
  23310. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23311. }
  23312. else {
  23313. if (targetTexture) {
  23314. engine.bindFramebuffer(targetTexture);
  23315. }
  23316. else {
  23317. engine.restoreDefaultFramebuffer();
  23318. }
  23319. }
  23320. var pp = postProcesses[index];
  23321. var effect = pp.apply();
  23322. if (effect) {
  23323. if (pp.onBeforeRender) {
  23324. pp.onBeforeRender(effect);
  23325. }
  23326. // VBOs
  23327. this._prepareBuffers();
  23328. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23329. // Draw order
  23330. engine.draw(true, 0, 6);
  23331. if (pp.onAfterRender) {
  23332. pp.onAfterRender(effect);
  23333. }
  23334. }
  23335. }
  23336. // Restore depth buffer
  23337. engine.setDepthBuffer(true);
  23338. engine.setDepthWrite(true);
  23339. };
  23340. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23341. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23342. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23343. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23344. return;
  23345. }
  23346. var engine = this._scene.getEngine();
  23347. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23348. if (index < postProcessesTakenIndices.length - 1) {
  23349. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23350. }
  23351. else {
  23352. if (targetTexture) {
  23353. engine.bindFramebuffer(targetTexture, faceIndex);
  23354. }
  23355. else {
  23356. engine.restoreDefaultFramebuffer();
  23357. }
  23358. }
  23359. if (doNotPresent) {
  23360. break;
  23361. }
  23362. var pp = postProcesses[postProcessesTakenIndices[index]];
  23363. var effect = pp.apply();
  23364. if (effect) {
  23365. if (pp.onBeforeRender) {
  23366. pp.onBeforeRender(effect);
  23367. }
  23368. // VBOs
  23369. this._prepareBuffers();
  23370. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23371. // Draw order
  23372. engine.draw(true, 0, 6);
  23373. if (pp.onAfterRender) {
  23374. pp.onAfterRender(effect);
  23375. }
  23376. }
  23377. }
  23378. // Restore depth buffer
  23379. engine.setDepthBuffer(true);
  23380. engine.setDepthWrite(true);
  23381. };
  23382. PostProcessManager.prototype.dispose = function () {
  23383. if (this._vertexBuffer) {
  23384. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23385. this._vertexBuffer = null;
  23386. }
  23387. if (this._indexBuffer) {
  23388. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23389. this._indexBuffer = null;
  23390. }
  23391. };
  23392. return PostProcessManager;
  23393. })();
  23394. BABYLON.PostProcessManager = PostProcessManager;
  23395. })(BABYLON || (BABYLON = {}));
  23396. var BABYLON;
  23397. (function (BABYLON) {
  23398. var PassPostProcess = (function (_super) {
  23399. __extends(PassPostProcess, _super);
  23400. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23401. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23402. }
  23403. return PassPostProcess;
  23404. })(BABYLON.PostProcess);
  23405. BABYLON.PassPostProcess = PassPostProcess;
  23406. })(BABYLON || (BABYLON = {}));
  23407. var BABYLON;
  23408. (function (BABYLON) {
  23409. var PhysicsEngine = (function () {
  23410. function PhysicsEngine(plugin) {
  23411. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23412. }
  23413. PhysicsEngine.prototype._initialize = function (gravity) {
  23414. this._currentPlugin.initialize();
  23415. this._setGravity(gravity);
  23416. };
  23417. PhysicsEngine.prototype._runOneStep = function (delta) {
  23418. if (delta > 0.1) {
  23419. delta = 0.1;
  23420. }
  23421. else if (delta <= 0) {
  23422. delta = 1.0 / 60.0;
  23423. }
  23424. this._currentPlugin.runOneStep(delta);
  23425. };
  23426. PhysicsEngine.prototype._setGravity = function (gravity) {
  23427. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23428. this._currentPlugin.setGravity(this.gravity);
  23429. };
  23430. PhysicsEngine.prototype._getGravity = function () {
  23431. return this._currentPlugin.getGravity();
  23432. };
  23433. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23434. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23435. };
  23436. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23437. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23438. };
  23439. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23440. this._currentPlugin.unregisterMesh(mesh);
  23441. };
  23442. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23443. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23444. };
  23445. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23446. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23447. };
  23448. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23449. this._currentPlugin.updateBodyPosition(mesh);
  23450. };
  23451. PhysicsEngine.prototype.dispose = function () {
  23452. this._currentPlugin.dispose();
  23453. };
  23454. PhysicsEngine.prototype.isSupported = function () {
  23455. return this._currentPlugin.isSupported();
  23456. };
  23457. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23458. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23459. };
  23460. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23461. return this._currentPlugin.name;
  23462. };
  23463. // Statics
  23464. PhysicsEngine.NoImpostor = 0;
  23465. PhysicsEngine.SphereImpostor = 1;
  23466. PhysicsEngine.BoxImpostor = 2;
  23467. PhysicsEngine.PlaneImpostor = 3;
  23468. PhysicsEngine.MeshImpostor = 4;
  23469. PhysicsEngine.CapsuleImpostor = 5;
  23470. PhysicsEngine.ConeImpostor = 6;
  23471. PhysicsEngine.CylinderImpostor = 7;
  23472. PhysicsEngine.ConvexHullImpostor = 8;
  23473. PhysicsEngine.HeightmapImpostor = 9;
  23474. PhysicsEngine.Epsilon = 0.001;
  23475. return PhysicsEngine;
  23476. })();
  23477. BABYLON.PhysicsEngine = PhysicsEngine;
  23478. })(BABYLON || (BABYLON = {}));
  23479. var BABYLON;
  23480. (function (BABYLON) {
  23481. var VertexData = (function () {
  23482. function VertexData() {
  23483. }
  23484. VertexData.prototype.set = function (data, kind) {
  23485. switch (kind) {
  23486. case BABYLON.VertexBuffer.PositionKind:
  23487. this.positions = data;
  23488. break;
  23489. case BABYLON.VertexBuffer.NormalKind:
  23490. this.normals = data;
  23491. break;
  23492. case BABYLON.VertexBuffer.UVKind:
  23493. this.uvs = data;
  23494. break;
  23495. case BABYLON.VertexBuffer.UV2Kind:
  23496. this.uvs2 = data;
  23497. break;
  23498. case BABYLON.VertexBuffer.UV3Kind:
  23499. this.uvs3 = data;
  23500. break;
  23501. case BABYLON.VertexBuffer.UV4Kind:
  23502. this.uvs4 = data;
  23503. break;
  23504. case BABYLON.VertexBuffer.UV5Kind:
  23505. this.uvs5 = data;
  23506. break;
  23507. case BABYLON.VertexBuffer.UV6Kind:
  23508. this.uvs6 = data;
  23509. break;
  23510. case BABYLON.VertexBuffer.ColorKind:
  23511. this.colors = data;
  23512. break;
  23513. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23514. this.matricesIndices = data;
  23515. break;
  23516. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23517. this.matricesWeights = data;
  23518. break;
  23519. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23520. this.matricesIndicesExtra = data;
  23521. break;
  23522. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23523. this.matricesWeightsExtra = data;
  23524. break;
  23525. }
  23526. };
  23527. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23528. this._applyTo(mesh, updatable);
  23529. };
  23530. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23531. this._applyTo(geometry, updatable);
  23532. };
  23533. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23534. this._update(mesh);
  23535. };
  23536. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23537. this._update(geometry);
  23538. };
  23539. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23540. if (this.positions) {
  23541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23542. }
  23543. if (this.normals) {
  23544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23545. }
  23546. if (this.uvs) {
  23547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23548. }
  23549. if (this.uvs2) {
  23550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23551. }
  23552. if (this.uvs3) {
  23553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23554. }
  23555. if (this.uvs4) {
  23556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23557. }
  23558. if (this.uvs5) {
  23559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23560. }
  23561. if (this.uvs6) {
  23562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23563. }
  23564. if (this.colors) {
  23565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23566. }
  23567. if (this.matricesIndices) {
  23568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23569. }
  23570. if (this.matricesWeights) {
  23571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23572. }
  23573. if (this.matricesIndicesExtra) {
  23574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23575. }
  23576. if (this.matricesWeightsExtra) {
  23577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23578. }
  23579. if (this.indices) {
  23580. meshOrGeometry.setIndices(this.indices);
  23581. }
  23582. };
  23583. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23584. if (this.positions) {
  23585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23586. }
  23587. if (this.normals) {
  23588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23589. }
  23590. if (this.uvs) {
  23591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23592. }
  23593. if (this.uvs2) {
  23594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23595. }
  23596. if (this.uvs3) {
  23597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23598. }
  23599. if (this.uvs4) {
  23600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23601. }
  23602. if (this.uvs5) {
  23603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23604. }
  23605. if (this.uvs6) {
  23606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23607. }
  23608. if (this.colors) {
  23609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23610. }
  23611. if (this.matricesIndices) {
  23612. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23613. }
  23614. if (this.matricesWeights) {
  23615. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23616. }
  23617. if (this.matricesIndicesExtra) {
  23618. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23619. }
  23620. if (this.matricesWeightsExtra) {
  23621. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23622. }
  23623. if (this.indices) {
  23624. meshOrGeometry.setIndices(this.indices);
  23625. }
  23626. };
  23627. VertexData.prototype.transform = function (matrix) {
  23628. var transformed = BABYLON.Vector3.Zero();
  23629. var index;
  23630. if (this.positions) {
  23631. var position = BABYLON.Vector3.Zero();
  23632. for (index = 0; index < this.positions.length; index += 3) {
  23633. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23634. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23635. this.positions[index] = transformed.x;
  23636. this.positions[index + 1] = transformed.y;
  23637. this.positions[index + 2] = transformed.z;
  23638. }
  23639. }
  23640. if (this.normals) {
  23641. var normal = BABYLON.Vector3.Zero();
  23642. for (index = 0; index < this.normals.length; index += 3) {
  23643. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23644. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23645. this.normals[index] = transformed.x;
  23646. this.normals[index + 1] = transformed.y;
  23647. this.normals[index + 2] = transformed.z;
  23648. }
  23649. }
  23650. };
  23651. VertexData.prototype.merge = function (other) {
  23652. if (other.indices) {
  23653. if (!this.indices) {
  23654. this.indices = [];
  23655. }
  23656. var offset = this.positions ? this.positions.length / 3 : 0;
  23657. for (var index = 0; index < other.indices.length; index++) {
  23658. //TODO check type - if Int32Array!
  23659. this.indices.push(other.indices[index] + offset);
  23660. }
  23661. }
  23662. this.positions = this._mergeElement(this.positions, other.positions);
  23663. this.normals = this._mergeElement(this.normals, other.normals);
  23664. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23665. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23666. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23667. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23668. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23669. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23670. this.colors = this._mergeElement(this.colors, other.colors);
  23671. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23672. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23673. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23674. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23675. };
  23676. VertexData.prototype._mergeElement = function (source, other) {
  23677. if (!other)
  23678. return source;
  23679. if (!source)
  23680. return other;
  23681. var len = other.length + source.length;
  23682. var isSrcTypedArray = source instanceof Float32Array;
  23683. var isOthTypedArray = other instanceof Float32Array;
  23684. // use non-loop method when the source is Float32Array
  23685. if (isSrcTypedArray) {
  23686. var ret32 = new Float32Array(len);
  23687. ret32.set(source);
  23688. ret32.set(other, source.length);
  23689. return ret32;
  23690. }
  23691. else if (!isOthTypedArray) {
  23692. return source.concat(other);
  23693. }
  23694. else {
  23695. var ret = source.slice(0); // copy source to a separate array
  23696. for (var i = 0, len = other.length; i < len; i++) {
  23697. ret.push(other[i]);
  23698. }
  23699. return ret;
  23700. }
  23701. };
  23702. VertexData.prototype.serialize = function () {
  23703. var serializationObject = this.serialize();
  23704. if (this.positions) {
  23705. serializationObject.positions = this.positions;
  23706. }
  23707. if (this.normals) {
  23708. serializationObject.normals = this.normals;
  23709. }
  23710. if (this.uvs) {
  23711. serializationObject.uvs = this.uvs;
  23712. }
  23713. if (this.uvs2) {
  23714. serializationObject.uvs2 = this.uvs2;
  23715. }
  23716. if (this.uvs3) {
  23717. serializationObject.uvs3 = this.uvs3;
  23718. }
  23719. if (this.uvs4) {
  23720. serializationObject.uvs4 = this.uvs4;
  23721. }
  23722. if (this.uvs5) {
  23723. serializationObject.uvs5 = this.uvs5;
  23724. }
  23725. if (this.uvs6) {
  23726. serializationObject.uvs6 = this.uvs6;
  23727. }
  23728. if (this.colors) {
  23729. serializationObject.colors = this.colors;
  23730. }
  23731. if (this.matricesIndices) {
  23732. serializationObject.matricesIndices = this.matricesIndices;
  23733. serializationObject.matricesIndices._isExpanded = true;
  23734. }
  23735. if (this.matricesWeights) {
  23736. serializationObject.matricesWeights = this.matricesWeights;
  23737. }
  23738. if (this.matricesIndicesExtra) {
  23739. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23740. serializationObject.matricesIndicesExtra._isExpanded = true;
  23741. }
  23742. if (this.matricesWeightsExtra) {
  23743. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23744. }
  23745. serializationObject.indices = this.indices;
  23746. return serializationObject;
  23747. };
  23748. // Statics
  23749. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23750. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23751. };
  23752. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23753. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23754. };
  23755. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23756. var result = new VertexData();
  23757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23758. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23759. }
  23760. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23761. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23762. }
  23763. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23764. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23765. }
  23766. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23767. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23768. }
  23769. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23770. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23771. }
  23772. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23773. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23774. }
  23775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23776. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23777. }
  23778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23779. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23780. }
  23781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23782. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23783. }
  23784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23785. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23786. }
  23787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23788. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23789. }
  23790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23791. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23792. }
  23793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23794. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23795. }
  23796. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23797. return result;
  23798. };
  23799. VertexData.CreateRibbon = function (options) {
  23800. var pathArray = options.pathArray;
  23801. var closeArray = options.closeArray || false;
  23802. var closePath = options.closePath || false;
  23803. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23804. var offset = options.offset || defaultOffset;
  23805. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23806. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23807. var positions = [];
  23808. var indices = [];
  23809. var normals = [];
  23810. var uvs = [];
  23811. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23812. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23813. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23814. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23815. var minlg; // minimal length among all paths from pathArray
  23816. var lg = []; // array of path lengths : nb of vertex per path
  23817. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23818. var p; // path iterator
  23819. var i; // point iterator
  23820. var j; // point iterator
  23821. // if single path in pathArray
  23822. if (pathArray.length < 2) {
  23823. var ar1 = [];
  23824. var ar2 = [];
  23825. for (i = 0; i < pathArray[0].length - offset; i++) {
  23826. ar1.push(pathArray[0][i]);
  23827. ar2.push(pathArray[0][i + offset]);
  23828. }
  23829. pathArray = [ar1, ar2];
  23830. }
  23831. // positions and horizontal distances (u)
  23832. var idc = 0;
  23833. var closePathCorr = (closePath) ? 1 : 0;
  23834. var path;
  23835. var l;
  23836. minlg = pathArray[0].length;
  23837. var vectlg;
  23838. var dist;
  23839. for (p = 0; p < pathArray.length; p++) {
  23840. uTotalDistance[p] = 0;
  23841. us[p] = [0];
  23842. path = pathArray[p];
  23843. l = path.length;
  23844. minlg = (minlg < l) ? minlg : l;
  23845. j = 0;
  23846. while (j < l) {
  23847. positions.push(path[j].x, path[j].y, path[j].z);
  23848. if (j > 0) {
  23849. vectlg = path[j].subtract(path[j - 1]).length();
  23850. dist = vectlg + uTotalDistance[p];
  23851. us[p].push(dist);
  23852. uTotalDistance[p] = dist;
  23853. }
  23854. j++;
  23855. }
  23856. if (closePath) {
  23857. j--;
  23858. positions.push(path[0].x, path[0].y, path[0].z);
  23859. vectlg = path[j].subtract(path[0]).length();
  23860. dist = vectlg + uTotalDistance[p];
  23861. us[p].push(dist);
  23862. uTotalDistance[p] = dist;
  23863. }
  23864. lg[p] = l + closePathCorr;
  23865. idx[p] = idc;
  23866. idc += (l + closePathCorr);
  23867. }
  23868. // vertical distances (v)
  23869. var path1;
  23870. var path2;
  23871. var vertex1;
  23872. var vertex2;
  23873. for (i = 0; i < minlg + closePathCorr; i++) {
  23874. vTotalDistance[i] = 0;
  23875. vs[i] = [0];
  23876. for (p = 0; p < pathArray.length - 1; p++) {
  23877. path1 = pathArray[p];
  23878. path2 = pathArray[p + 1];
  23879. if (i === minlg) {
  23880. vertex1 = path1[0];
  23881. vertex2 = path2[0];
  23882. }
  23883. else {
  23884. vertex1 = path1[i];
  23885. vertex2 = path2[i];
  23886. }
  23887. vectlg = vertex2.subtract(vertex1).length();
  23888. dist = vectlg + vTotalDistance[i];
  23889. vs[i].push(dist);
  23890. vTotalDistance[i] = dist;
  23891. }
  23892. if (closeArray) {
  23893. path1 = pathArray[p];
  23894. path2 = pathArray[0];
  23895. if (i === minlg) {
  23896. vertex2 = path2[0];
  23897. }
  23898. vectlg = vertex2.subtract(vertex1).length();
  23899. dist = vectlg + vTotalDistance[i];
  23900. vTotalDistance[i] = dist;
  23901. }
  23902. }
  23903. // uvs
  23904. var u;
  23905. var v;
  23906. for (p = 0; p < pathArray.length; p++) {
  23907. for (i = 0; i < minlg + closePathCorr; i++) {
  23908. u = us[p][i] / uTotalDistance[p];
  23909. v = vs[i][p] / vTotalDistance[i];
  23910. uvs.push(u, v);
  23911. }
  23912. }
  23913. // indices
  23914. p = 0; // path index
  23915. var pi = 0; // positions array index
  23916. var l1 = lg[p] - 1; // path1 length
  23917. var l2 = lg[p + 1] - 1; // path2 length
  23918. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23919. var shft = idx[1] - idx[0]; // shift
  23920. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23921. while (pi <= min && p < path1nb) {
  23922. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  23923. indices.push(pi, pi + shft, pi + 1);
  23924. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23925. pi += 1;
  23926. if (pi === min) {
  23927. p++;
  23928. if (p === lg.length - 1) {
  23929. shft = idx[0] - idx[p];
  23930. l1 = lg[p] - 1;
  23931. l2 = lg[0] - 1;
  23932. }
  23933. else {
  23934. shft = idx[p + 1] - idx[p];
  23935. l1 = lg[p] - 1;
  23936. l2 = lg[p + 1] - 1;
  23937. }
  23938. pi = idx[p];
  23939. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23940. }
  23941. }
  23942. // normals
  23943. VertexData.ComputeNormals(positions, indices, normals);
  23944. if (closePath) {
  23945. var indexFirst = 0;
  23946. var indexLast = 0;
  23947. for (p = 0; p < pathArray.length; p++) {
  23948. indexFirst = idx[p] * 3;
  23949. if (p + 1 < pathArray.length) {
  23950. indexLast = (idx[p + 1] - 1) * 3;
  23951. }
  23952. else {
  23953. indexLast = normals.length - 3;
  23954. }
  23955. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23956. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23957. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23958. normals[indexLast] = normals[indexFirst];
  23959. normals[indexLast + 1] = normals[indexFirst + 1];
  23960. normals[indexLast + 2] = normals[indexFirst + 2];
  23961. }
  23962. }
  23963. // sides
  23964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23965. // Result
  23966. var vertexData = new VertexData();
  23967. vertexData.indices = indices;
  23968. vertexData.positions = positions;
  23969. vertexData.normals = normals;
  23970. vertexData.uvs = uvs;
  23971. if (closePath) {
  23972. vertexData._idx = idx;
  23973. }
  23974. return vertexData;
  23975. };
  23976. VertexData.CreateBox = function (options) {
  23977. var normalsSource = [
  23978. new BABYLON.Vector3(0, 0, 1),
  23979. new BABYLON.Vector3(0, 0, -1),
  23980. new BABYLON.Vector3(1, 0, 0),
  23981. new BABYLON.Vector3(-1, 0, 0),
  23982. new BABYLON.Vector3(0, 1, 0),
  23983. new BABYLON.Vector3(0, -1, 0)
  23984. ];
  23985. var indices = [];
  23986. var positions = [];
  23987. var normals = [];
  23988. var uvs = [];
  23989. var width = options.width || options.size || 1;
  23990. var height = options.height || options.size || 1;
  23991. var depth = options.depth || options.size || 1;
  23992. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23993. var faceUV = options.faceUV || new Array(6);
  23994. var faceColors = options.faceColors;
  23995. var colors = [];
  23996. // default face colors and UV if undefined
  23997. for (var f = 0; f < 6; f++) {
  23998. if (faceUV[f] === undefined) {
  23999. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24000. }
  24001. if (faceColors && faceColors[f] === undefined) {
  24002. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24003. }
  24004. }
  24005. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24006. // Create each face in turn.
  24007. for (var index = 0; index < normalsSource.length; index++) {
  24008. var normal = normalsSource[index];
  24009. // Get two vectors perpendicular to the face normal and to each other.
  24010. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24011. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24012. // Six indices (two triangles) per face.
  24013. var verticesLength = positions.length / 3;
  24014. indices.push(verticesLength);
  24015. indices.push(verticesLength + 1);
  24016. indices.push(verticesLength + 2);
  24017. indices.push(verticesLength);
  24018. indices.push(verticesLength + 2);
  24019. indices.push(verticesLength + 3);
  24020. // Four vertices per face.
  24021. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24022. positions.push(vertex.x, vertex.y, vertex.z);
  24023. normals.push(normal.x, normal.y, normal.z);
  24024. uvs.push(faceUV[index].z, faceUV[index].w);
  24025. if (faceColors) {
  24026. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24027. }
  24028. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24029. positions.push(vertex.x, vertex.y, vertex.z);
  24030. normals.push(normal.x, normal.y, normal.z);
  24031. uvs.push(faceUV[index].x, faceUV[index].w);
  24032. if (faceColors) {
  24033. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24034. }
  24035. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24036. positions.push(vertex.x, vertex.y, vertex.z);
  24037. normals.push(normal.x, normal.y, normal.z);
  24038. uvs.push(faceUV[index].x, faceUV[index].y);
  24039. if (faceColors) {
  24040. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24041. }
  24042. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24043. positions.push(vertex.x, vertex.y, vertex.z);
  24044. normals.push(normal.x, normal.y, normal.z);
  24045. uvs.push(faceUV[index].z, faceUV[index].y);
  24046. if (faceColors) {
  24047. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24048. }
  24049. }
  24050. // sides
  24051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24052. // Result
  24053. var vertexData = new VertexData();
  24054. vertexData.indices = indices;
  24055. vertexData.positions = positions;
  24056. vertexData.normals = normals;
  24057. vertexData.uvs = uvs;
  24058. if (faceColors) {
  24059. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24060. vertexData.colors = totalColors;
  24061. }
  24062. return vertexData;
  24063. };
  24064. VertexData.CreateSphere = function (options) {
  24065. var segments = options.segments || 32;
  24066. var diameterX = options.diameterX || options.diameter || 1;
  24067. var diameterY = options.diameterY || options.diameter || 1;
  24068. var diameterZ = options.diameterZ || options.diameter || 1;
  24069. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24070. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24071. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24072. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24073. var totalZRotationSteps = 2 + segments;
  24074. var totalYRotationSteps = 2 * totalZRotationSteps;
  24075. var indices = [];
  24076. var positions = [];
  24077. var normals = [];
  24078. var uvs = [];
  24079. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24080. var normalizedZ = zRotationStep / totalZRotationSteps;
  24081. var angleZ = normalizedZ * Math.PI * slice;
  24082. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24083. var normalizedY = yRotationStep / totalYRotationSteps;
  24084. var angleY = normalizedY * Math.PI * 2 * arc;
  24085. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24086. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24087. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24088. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24089. var vertex = complete.multiply(radius);
  24090. var normal = complete.divide(radius).normalize();
  24091. positions.push(vertex.x, vertex.y, vertex.z);
  24092. normals.push(normal.x, normal.y, normal.z);
  24093. uvs.push(normalizedY, normalizedZ);
  24094. }
  24095. if (zRotationStep > 0) {
  24096. var verticesCount = positions.length / 3;
  24097. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24098. indices.push((firstIndex));
  24099. indices.push((firstIndex + 1));
  24100. indices.push(firstIndex + totalYRotationSteps + 1);
  24101. indices.push((firstIndex + totalYRotationSteps + 1));
  24102. indices.push((firstIndex + 1));
  24103. indices.push((firstIndex + totalYRotationSteps + 2));
  24104. }
  24105. }
  24106. }
  24107. // Sides
  24108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24109. // Result
  24110. var vertexData = new VertexData();
  24111. vertexData.indices = indices;
  24112. vertexData.positions = positions;
  24113. vertexData.normals = normals;
  24114. vertexData.uvs = uvs;
  24115. return vertexData;
  24116. };
  24117. // Cylinder and cone
  24118. VertexData.CreateCylinder = function (options) {
  24119. var height = options.height || 2;
  24120. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24121. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24122. var tessellation = options.tessellation || 24;
  24123. var subdivisions = options.subdivisions || 1;
  24124. var hasRings = options.hasRings;
  24125. var enclose = options.enclose;
  24126. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24128. var faceUV = options.faceUV || new Array(3);
  24129. var faceColors = options.faceColors;
  24130. // default face colors and UV if undefined
  24131. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24132. var ringNb = (hasRings) ? subdivisions : 1;
  24133. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24134. var f;
  24135. for (f = 0; f < surfaceNb; f++) {
  24136. if (faceColors && faceColors[f] === undefined) {
  24137. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24138. }
  24139. }
  24140. for (f = 0; f < surfaceNb; f++) {
  24141. if (faceUV && faceUV[f] === undefined) {
  24142. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24143. }
  24144. }
  24145. var indices = [];
  24146. var positions = [];
  24147. var normals = [];
  24148. var uvs = [];
  24149. var colors = [];
  24150. var angle_step = Math.PI * 2 * arc / tessellation;
  24151. var angle;
  24152. var h;
  24153. var radius;
  24154. var tan = (diameterBottom - diameterTop) / 2 / height;
  24155. var ringVertex = BABYLON.Vector3.Zero();
  24156. var ringNormal = BABYLON.Vector3.Zero();
  24157. var ringFirstVertex = BABYLON.Vector3.Zero();
  24158. var ringFirstNormal = BABYLON.Vector3.Zero();
  24159. var quadNormal = BABYLON.Vector3.Zero();
  24160. var Y = BABYLON.Axis.Y;
  24161. // positions, normals, uvs
  24162. var i;
  24163. var j;
  24164. var r;
  24165. var ringIdx = 1;
  24166. var s = 1; // surface index
  24167. var cs = 0;
  24168. var v = 0;
  24169. for (i = 0; i <= subdivisions; i++) {
  24170. h = i / subdivisions;
  24171. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24172. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24173. for (r = 0; r < ringIdx; r++) {
  24174. if (hasRings) {
  24175. s += r;
  24176. }
  24177. if (enclose) {
  24178. s += 2 * r;
  24179. }
  24180. for (j = 0; j <= tessellation; j++) {
  24181. angle = j * angle_step;
  24182. // position
  24183. ringVertex.x = Math.cos(-angle) * radius;
  24184. ringVertex.y = -height / 2 + h * height;
  24185. ringVertex.z = Math.sin(-angle) * radius;
  24186. // normal
  24187. if (diameterTop === 0 && i === subdivisions) {
  24188. // if no top cap, reuse former normals
  24189. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24190. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24191. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24192. }
  24193. else {
  24194. ringNormal.x = ringVertex.x;
  24195. ringNormal.z = ringVertex.z;
  24196. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24197. ringNormal.normalize();
  24198. }
  24199. // keep first ring vertex values for enclose
  24200. if (j === 0) {
  24201. ringFirstVertex.copyFrom(ringVertex);
  24202. ringFirstNormal.copyFrom(ringNormal);
  24203. }
  24204. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24205. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24206. if (hasRings) {
  24207. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24208. }
  24209. else {
  24210. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24211. }
  24212. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24213. if (faceColors) {
  24214. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24215. }
  24216. }
  24217. // if enclose, add four vertices and their dedicated normals
  24218. if (arc !== 1 && enclose) {
  24219. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24220. positions.push(0, ringVertex.y, 0);
  24221. positions.push(0, ringVertex.y, 0);
  24222. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24223. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24224. quadNormal.normalize();
  24225. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24226. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24227. quadNormal.normalize();
  24228. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24229. if (hasRings) {
  24230. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24231. }
  24232. else {
  24233. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24234. }
  24235. uvs.push(faceUV[s + 1].x, v);
  24236. uvs.push(faceUV[s + 1].z, v);
  24237. if (hasRings) {
  24238. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24239. }
  24240. else {
  24241. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24242. }
  24243. uvs.push(faceUV[s + 2].x, v);
  24244. uvs.push(faceUV[s + 2].z, v);
  24245. if (faceColors) {
  24246. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24247. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24248. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24249. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24250. }
  24251. }
  24252. if (cs !== s) {
  24253. cs = s;
  24254. }
  24255. }
  24256. }
  24257. // indices
  24258. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24259. var s;
  24260. i = 0;
  24261. for (s = 0; s < subdivisions; s++) {
  24262. for (j = 0; j < tessellation; j++) {
  24263. var i0 = i * (e + 1) + j;
  24264. var i1 = (i + 1) * (e + 1) + j;
  24265. var i2 = i * (e + 1) + (j + 1);
  24266. var i3 = (i + 1) * (e + 1) + (j + 1);
  24267. indices.push(i0, i1, i2);
  24268. indices.push(i3, i2, i1);
  24269. }
  24270. if (arc !== 1 && enclose) {
  24271. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24272. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24273. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24274. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24275. }
  24276. i = (hasRings) ? (i + 2) : (i + 1);
  24277. }
  24278. // Caps
  24279. var createCylinderCap = function (isTop) {
  24280. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24281. if (radius === 0) {
  24282. return;
  24283. }
  24284. // Cap positions, normals & uvs
  24285. var angle;
  24286. var circleVector;
  24287. var i;
  24288. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24289. var c;
  24290. if (faceColors) {
  24291. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24292. }
  24293. // cap center
  24294. var vbase = positions.length / 3;
  24295. var offset = isTop ? height / 2 : -height / 2;
  24296. var center = new BABYLON.Vector3(0, offset, 0);
  24297. positions.push(center.x, center.y, center.z);
  24298. normals.push(0, isTop ? 1 : -1, 0);
  24299. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24300. if (faceColors) {
  24301. colors.push(c.r, c.g, c.b, c.a);
  24302. }
  24303. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24304. for (i = 0; i <= tessellation; i++) {
  24305. angle = Math.PI * 2 * i * arc / tessellation;
  24306. var cos = Math.cos(-angle);
  24307. var sin = Math.sin(-angle);
  24308. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24309. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24310. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24311. normals.push(0, isTop ? 1 : -1, 0);
  24312. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24313. if (faceColors) {
  24314. colors.push(c.r, c.g, c.b, c.a);
  24315. }
  24316. }
  24317. // Cap indices
  24318. for (i = 0; i < tessellation; i++) {
  24319. if (!isTop) {
  24320. indices.push(vbase);
  24321. indices.push(vbase + (i + 1));
  24322. indices.push(vbase + (i + 2));
  24323. }
  24324. else {
  24325. indices.push(vbase);
  24326. indices.push(vbase + (i + 2));
  24327. indices.push(vbase + (i + 1));
  24328. }
  24329. }
  24330. };
  24331. // add caps to geometry
  24332. createCylinderCap(false);
  24333. createCylinderCap(true);
  24334. // Sides
  24335. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24336. var vertexData = new VertexData();
  24337. vertexData.indices = indices;
  24338. vertexData.positions = positions;
  24339. vertexData.normals = normals;
  24340. vertexData.uvs = uvs;
  24341. if (faceColors) {
  24342. vertexData.colors = colors;
  24343. }
  24344. return vertexData;
  24345. };
  24346. VertexData.CreateTorus = function (options) {
  24347. var indices = [];
  24348. var positions = [];
  24349. var normals = [];
  24350. var uvs = [];
  24351. var diameter = options.diameter || 1;
  24352. var thickness = options.thickness || 0.5;
  24353. var tessellation = options.tessellation || 16;
  24354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24355. var stride = tessellation + 1;
  24356. for (var i = 0; i <= tessellation; i++) {
  24357. var u = i / tessellation;
  24358. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24359. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24360. for (var j = 0; j <= tessellation; j++) {
  24361. var v = 1 - j / tessellation;
  24362. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24363. var dx = Math.cos(innerAngle);
  24364. var dy = Math.sin(innerAngle);
  24365. // Create a vertex.
  24366. var normal = new BABYLON.Vector3(dx, dy, 0);
  24367. var position = normal.scale(thickness / 2);
  24368. var textureCoordinate = new BABYLON.Vector2(u, v);
  24369. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24370. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24371. positions.push(position.x, position.y, position.z);
  24372. normals.push(normal.x, normal.y, normal.z);
  24373. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24374. // And create indices for two triangles.
  24375. var nextI = (i + 1) % stride;
  24376. var nextJ = (j + 1) % stride;
  24377. indices.push(i * stride + j);
  24378. indices.push(i * stride + nextJ);
  24379. indices.push(nextI * stride + j);
  24380. indices.push(i * stride + nextJ);
  24381. indices.push(nextI * stride + nextJ);
  24382. indices.push(nextI * stride + j);
  24383. }
  24384. }
  24385. // Sides
  24386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24387. // Result
  24388. var vertexData = new VertexData();
  24389. vertexData.indices = indices;
  24390. vertexData.positions = positions;
  24391. vertexData.normals = normals;
  24392. vertexData.uvs = uvs;
  24393. return vertexData;
  24394. };
  24395. VertexData.CreateLines = function (options) {
  24396. var indices = [];
  24397. var positions = [];
  24398. var points = options.points;
  24399. for (var index = 0; index < points.length; index++) {
  24400. positions.push(points[index].x, points[index].y, points[index].z);
  24401. if (index > 0) {
  24402. indices.push(index - 1);
  24403. indices.push(index);
  24404. }
  24405. }
  24406. // Result
  24407. var vertexData = new VertexData();
  24408. vertexData.indices = indices;
  24409. vertexData.positions = positions;
  24410. return vertexData;
  24411. };
  24412. VertexData.CreateDashedLines = function (options) {
  24413. var dashSize = options.dashSize || 3;
  24414. var gapSize = options.gapSize || 1;
  24415. var dashNb = options.dashNb || 200;
  24416. var points = options.points;
  24417. var positions = new Array();
  24418. var indices = new Array();
  24419. var curvect = BABYLON.Vector3.Zero();
  24420. var lg = 0;
  24421. var nb = 0;
  24422. var shft = 0;
  24423. var dashshft = 0;
  24424. var curshft = 0;
  24425. var idx = 0;
  24426. var i = 0;
  24427. for (i = 0; i < points.length - 1; i++) {
  24428. points[i + 1].subtractToRef(points[i], curvect);
  24429. lg += curvect.length();
  24430. }
  24431. shft = lg / dashNb;
  24432. dashshft = dashSize * shft / (dashSize + gapSize);
  24433. for (i = 0; i < points.length - 1; i++) {
  24434. points[i + 1].subtractToRef(points[i], curvect);
  24435. nb = Math.floor(curvect.length() / shft);
  24436. curvect.normalize();
  24437. for (var j = 0; j < nb; j++) {
  24438. curshft = shft * j;
  24439. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24440. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24441. indices.push(idx, idx + 1);
  24442. idx += 2;
  24443. }
  24444. }
  24445. // Result
  24446. var vertexData = new VertexData();
  24447. vertexData.positions = positions;
  24448. vertexData.indices = indices;
  24449. return vertexData;
  24450. };
  24451. VertexData.CreateGround = function (options) {
  24452. var indices = [];
  24453. var positions = [];
  24454. var normals = [];
  24455. var uvs = [];
  24456. var row, col;
  24457. var width = options.width || 1;
  24458. var height = options.height || 1;
  24459. var subdivisions = options.subdivisions || 1;
  24460. for (row = 0; row <= subdivisions; row++) {
  24461. for (col = 0; col <= subdivisions; col++) {
  24462. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24463. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24464. positions.push(position.x, position.y, position.z);
  24465. normals.push(normal.x, normal.y, normal.z);
  24466. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24467. }
  24468. }
  24469. for (row = 0; row < subdivisions; row++) {
  24470. for (col = 0; col < subdivisions; col++) {
  24471. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24472. indices.push(col + 1 + row * (subdivisions + 1));
  24473. indices.push(col + row * (subdivisions + 1));
  24474. indices.push(col + (row + 1) * (subdivisions + 1));
  24475. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24476. indices.push(col + row * (subdivisions + 1));
  24477. }
  24478. }
  24479. // Result
  24480. var vertexData = new VertexData();
  24481. vertexData.indices = indices;
  24482. vertexData.positions = positions;
  24483. vertexData.normals = normals;
  24484. vertexData.uvs = uvs;
  24485. return vertexData;
  24486. };
  24487. VertexData.CreateTiledGround = function (options) {
  24488. var xmin = options.xmin;
  24489. var zmin = options.zmin;
  24490. var xmax = options.xmax;
  24491. var zmax = options.zmax;
  24492. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24493. var precision = options.precision || { w: 1, h: 1 };
  24494. var indices = [];
  24495. var positions = [];
  24496. var normals = [];
  24497. var uvs = [];
  24498. var row, col, tileRow, tileCol;
  24499. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24500. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24501. precision.w = (precision.w < 1) ? 1 : precision.w;
  24502. precision.h = (precision.h < 1) ? 1 : precision.h;
  24503. var tileSize = {
  24504. 'w': (xmax - xmin) / subdivisions.w,
  24505. 'h': (zmax - zmin) / subdivisions.h
  24506. };
  24507. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24508. // Indices
  24509. var base = positions.length / 3;
  24510. var rowLength = precision.w + 1;
  24511. for (row = 0; row < precision.h; row++) {
  24512. for (col = 0; col < precision.w; col++) {
  24513. var square = [
  24514. base + col + row * rowLength,
  24515. base + (col + 1) + row * rowLength,
  24516. base + (col + 1) + (row + 1) * rowLength,
  24517. base + col + (row + 1) * rowLength
  24518. ];
  24519. indices.push(square[1]);
  24520. indices.push(square[2]);
  24521. indices.push(square[3]);
  24522. indices.push(square[0]);
  24523. indices.push(square[1]);
  24524. indices.push(square[3]);
  24525. }
  24526. }
  24527. // Position, normals and uvs
  24528. var position = BABYLON.Vector3.Zero();
  24529. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24530. for (row = 0; row <= precision.h; row++) {
  24531. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24532. for (col = 0; col <= precision.w; col++) {
  24533. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24534. position.y = 0;
  24535. positions.push(position.x, position.y, position.z);
  24536. normals.push(normal.x, normal.y, normal.z);
  24537. uvs.push(col / precision.w, row / precision.h);
  24538. }
  24539. }
  24540. }
  24541. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24542. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24543. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24544. }
  24545. }
  24546. // Result
  24547. var vertexData = new VertexData();
  24548. vertexData.indices = indices;
  24549. vertexData.positions = positions;
  24550. vertexData.normals = normals;
  24551. vertexData.uvs = uvs;
  24552. return vertexData;
  24553. };
  24554. VertexData.CreateGroundFromHeightMap = function (options) {
  24555. var indices = [];
  24556. var positions = [];
  24557. var normals = [];
  24558. var uvs = [];
  24559. var row, col;
  24560. // Vertices
  24561. for (row = 0; row <= options.subdivisions; row++) {
  24562. for (col = 0; col <= options.subdivisions; col++) {
  24563. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  24564. // Compute height
  24565. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24566. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24567. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24568. var r = options.buffer[pos] / 255.0;
  24569. var g = options.buffer[pos + 1] / 255.0;
  24570. var b = options.buffer[pos + 2] / 255.0;
  24571. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24572. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24573. // Add vertex
  24574. positions.push(position.x, position.y, position.z);
  24575. normals.push(0, 0, 0);
  24576. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24577. }
  24578. }
  24579. // Indices
  24580. for (row = 0; row < options.subdivisions; row++) {
  24581. for (col = 0; col < options.subdivisions; col++) {
  24582. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24583. indices.push(col + 1 + row * (options.subdivisions + 1));
  24584. indices.push(col + row * (options.subdivisions + 1));
  24585. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24586. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24587. indices.push(col + row * (options.subdivisions + 1));
  24588. }
  24589. }
  24590. // Normals
  24591. VertexData.ComputeNormals(positions, indices, normals);
  24592. // Result
  24593. var vertexData = new VertexData();
  24594. vertexData.indices = indices;
  24595. vertexData.positions = positions;
  24596. vertexData.normals = normals;
  24597. vertexData.uvs = uvs;
  24598. return vertexData;
  24599. };
  24600. VertexData.CreatePlane = function (options) {
  24601. var indices = [];
  24602. var positions = [];
  24603. var normals = [];
  24604. var uvs = [];
  24605. var width = options.width || options.size || 1;
  24606. var height = options.height || options.size || 1;
  24607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24608. // Vertices
  24609. var halfWidth = width / 2.0;
  24610. var halfHeight = height / 2.0;
  24611. positions.push(-halfWidth, -halfHeight, 0);
  24612. normals.push(0, 0, -1.0);
  24613. uvs.push(0.0, 0.0);
  24614. positions.push(halfWidth, -halfHeight, 0);
  24615. normals.push(0, 0, -1.0);
  24616. uvs.push(1.0, 0.0);
  24617. positions.push(halfWidth, halfHeight, 0);
  24618. normals.push(0, 0, -1.0);
  24619. uvs.push(1.0, 1.0);
  24620. positions.push(-halfWidth, halfHeight, 0);
  24621. normals.push(0, 0, -1.0);
  24622. uvs.push(0.0, 1.0);
  24623. // Indices
  24624. indices.push(0);
  24625. indices.push(1);
  24626. indices.push(2);
  24627. indices.push(0);
  24628. indices.push(2);
  24629. indices.push(3);
  24630. // Sides
  24631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24632. // Result
  24633. var vertexData = new VertexData();
  24634. vertexData.indices = indices;
  24635. vertexData.positions = positions;
  24636. vertexData.normals = normals;
  24637. vertexData.uvs = uvs;
  24638. return vertexData;
  24639. };
  24640. VertexData.CreateDisc = function (options) {
  24641. var positions = [];
  24642. var indices = [];
  24643. var normals = [];
  24644. var uvs = [];
  24645. var radius = options.radius || 0.5;
  24646. var tessellation = options.tessellation || 64;
  24647. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24648. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24649. // positions and uvs
  24650. positions.push(0, 0, 0); // disc center first
  24651. uvs.push(0.5, 0.5);
  24652. var theta = Math.PI * 2 * arc;
  24653. var step = theta / tessellation;
  24654. for (var a = 0; a < theta; a += step) {
  24655. var x = Math.cos(a);
  24656. var y = Math.sin(a);
  24657. var u = (x + 1) / 2;
  24658. var v = (1 - y) / 2;
  24659. positions.push(radius * x, radius * y, 0);
  24660. uvs.push(u, v);
  24661. }
  24662. if (arc === 1) {
  24663. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24664. uvs.push(uvs[2], uvs[3]);
  24665. }
  24666. //indices
  24667. var vertexNb = positions.length / 3;
  24668. for (var i = 1; i < vertexNb - 1; i++) {
  24669. indices.push(i + 1, 0, i);
  24670. }
  24671. // result
  24672. VertexData.ComputeNormals(positions, indices, normals);
  24673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24674. var vertexData = new VertexData();
  24675. vertexData.indices = indices;
  24676. vertexData.positions = positions;
  24677. vertexData.normals = normals;
  24678. vertexData.uvs = uvs;
  24679. return vertexData;
  24680. };
  24681. VertexData.CreateIcoSphere = function (options) {
  24682. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24683. var radius = options.radius || 1;
  24684. var flat = (options.flat === undefined) ? true : options.flat;
  24685. var subdivisions = options.subdivisions || 4;
  24686. var radiusX = options.radiusX || radius;
  24687. var radiusY = options.radiusY || radius;
  24688. var radiusZ = options.radiusZ || radius;
  24689. var t = (1 + Math.sqrt(5)) / 2;
  24690. // 12 vertex x,y,z
  24691. var ico_vertices = [
  24692. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24693. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24694. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24695. ];
  24696. // index of 3 vertex makes a face of icopshere
  24697. var ico_indices = [
  24698. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24699. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24700. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24701. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24702. ];
  24703. // vertex for uv have aliased position, not for UV
  24704. var vertices_unalias_id = [
  24705. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24706. // vertex alias
  24707. 0,
  24708. 2,
  24709. 3,
  24710. 3,
  24711. 3,
  24712. 4,
  24713. 7,
  24714. 8,
  24715. 9,
  24716. 9,
  24717. 10,
  24718. 11 // 23: B + 12
  24719. ];
  24720. // uv as integer step (not pixels !)
  24721. var ico_vertexuv = [
  24722. 5, 1, 3, 1, 6, 4, 0, 0,
  24723. 5, 3, 4, 2, 2, 2, 4, 0,
  24724. 2, 0, 1, 1, 6, 0, 6, 2,
  24725. // vertex alias (for same vertex on different faces)
  24726. 0, 4,
  24727. 3, 3,
  24728. 4, 4,
  24729. 3, 1,
  24730. 4, 2,
  24731. 4, 4,
  24732. 0, 2,
  24733. 1, 1,
  24734. 2, 2,
  24735. 3, 3,
  24736. 1, 3,
  24737. 2, 4 // 23: B + 12
  24738. ];
  24739. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24740. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24741. // First island of uv mapping
  24742. // v = 4h 3+ 2
  24743. // v = 3h 9+ 4
  24744. // v = 2h 9+ 5 B
  24745. // v = 1h 9 1 0
  24746. // v = 0h 3 8 7 A
  24747. // u = 0 1 2 3 4 5 6 *a
  24748. // Second island of uv mapping
  24749. // v = 4h 0+ B+ 4+
  24750. // v = 3h A+ 2+
  24751. // v = 2h 7+ 6 3+
  24752. // v = 1h 8+ 3+
  24753. // v = 0h
  24754. // u = 0 1 2 3 4 5 6 *a
  24755. // Face layout on texture UV mapping
  24756. // ============
  24757. // \ 4 /\ 16 / ======
  24758. // \ / \ / /\ 11 /
  24759. // \/ 7 \/ / \ /
  24760. // ======= / 10 \/
  24761. // /\ 17 /\ =======
  24762. // / \ / \ \ 15 /\
  24763. // / 8 \/ 12 \ \ / \
  24764. // ============ \/ 6 \
  24765. // \ 18 /\ ============
  24766. // \ / \ \ 5 /\ 0 /
  24767. // \/ 13 \ \ / \ /
  24768. // ======= \/ 1 \/
  24769. // =============
  24770. // /\ 19 /\ 2 /\
  24771. // / \ / \ / \
  24772. // / 14 \/ 9 \/ 3 \
  24773. // ===================
  24774. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24775. var ustep = 138 / 1024;
  24776. var vstep = 239 / 1024;
  24777. var uoffset = 60 / 1024;
  24778. var voffset = 26 / 1024;
  24779. // Second island should have margin, not to touch the first island
  24780. // avoid any borderline artefact in pixel rounding
  24781. var island_u_offset = -40 / 1024;
  24782. var island_v_offset = +20 / 1024;
  24783. // face is either island 0 or 1 :
  24784. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24785. var island = [
  24786. 0, 0, 0, 0, 1,
  24787. 0, 0, 1, 1, 0,
  24788. 0, 0, 1, 1, 0,
  24789. 0, 1, 1, 1, 0 // 15 - 19
  24790. ];
  24791. var indices = [];
  24792. var positions = [];
  24793. var normals = [];
  24794. var uvs = [];
  24795. var current_indice = 0;
  24796. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24797. var face_vertex_pos = new Array(3);
  24798. var face_vertex_uv = new Array(3);
  24799. var v012;
  24800. for (v012 = 0; v012 < 3; v012++) {
  24801. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24802. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24803. }
  24804. // create all with normals
  24805. for (var face = 0; face < 20; face++) {
  24806. // 3 vertex per face
  24807. for (v012 = 0; v012 < 3; v012++) {
  24808. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24809. var v_id = ico_indices[3 * face + v012];
  24810. // vertex have 3D position (x,y,z)
  24811. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  24812. // Normalize to get normal, then scale to radius
  24813. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24814. // uv Coordinates from vertex ID
  24815. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  24816. }
  24817. // Subdivide the face (interpolate pos, norm, uv)
  24818. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24819. // - norm is linear interpolation of vertex corner normal
  24820. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24821. // - uv is linear interpolation
  24822. //
  24823. // Topology is as below for sub-divide by 2
  24824. // vertex shown as v0,v1,v2
  24825. // interp index is i1 to progress in range [v0,v1[
  24826. // interp index is i2 to progress in range [v0,v2[
  24827. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24828. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24829. //
  24830. //
  24831. // i2 v2
  24832. // ^ ^
  24833. // / / \
  24834. // / / \
  24835. // / / \
  24836. // / / (0,1) \
  24837. // / #---------\
  24838. // / / \ (0,0)'/ \
  24839. // / / \ / \
  24840. // / / \ / \
  24841. // / / (0,0) \ / (1,0) \
  24842. // / #---------#---------\
  24843. // v0 v1
  24844. //
  24845. // --------------------> i1
  24846. //
  24847. // interp of (i1,i2):
  24848. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24849. // along i1 : lerp(x0,x1, i1/(S-i2))
  24850. //
  24851. // centroid of triangle is needed to get help normal computation
  24852. // (c1,c2) are used for centroid location
  24853. var interp_vertex = function (i1, i2, c1, c2) {
  24854. // vertex is interpolated from
  24855. // - face_vertex_pos[0..2]
  24856. // - face_vertex_uv[0..2]
  24857. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24858. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24859. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24860. pos_interp.normalize();
  24861. var vertex_normal;
  24862. if (flat) {
  24863. // in flat mode, recalculate normal as face centroid normal
  24864. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24865. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24866. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24867. }
  24868. else {
  24869. // in smooth mode, recalculate normal from each single vertex position
  24870. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24871. }
  24872. // Vertex normal need correction due to X,Y,Z radius scaling
  24873. vertex_normal.x /= radiusX;
  24874. vertex_normal.y /= radiusY;
  24875. vertex_normal.z /= radiusZ;
  24876. vertex_normal.normalize();
  24877. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24878. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24879. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24880. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24881. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24882. uvs.push(uv_interp.x, uv_interp.y);
  24883. // push each vertex has member of a face
  24884. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24885. indices.push(current_indice);
  24886. current_indice++;
  24887. };
  24888. for (var i2 = 0; i2 < subdivisions; i2++) {
  24889. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24890. // face : (i1,i2) for /\ :
  24891. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24892. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24893. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24894. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24895. if (i1 + i2 + 1 < subdivisions) {
  24896. // face : (i1,i2)' for \/ :
  24897. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24898. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24899. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24900. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24901. }
  24902. }
  24903. }
  24904. }
  24905. // Sides
  24906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24907. // Result
  24908. var vertexData = new VertexData();
  24909. vertexData.indices = indices;
  24910. vertexData.positions = positions;
  24911. vertexData.normals = normals;
  24912. vertexData.uvs = uvs;
  24913. return vertexData;
  24914. };
  24915. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24916. VertexData.CreatePolyhedron = function (options) {
  24917. // provided polyhedron types :
  24918. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24919. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  24920. var polyhedra = [];
  24921. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  24922. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  24923. polyhedra[2] = {
  24924. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  24925. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  24926. };
  24927. polyhedra[3] = {
  24928. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  24929. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  24930. };
  24931. polyhedra[4] = {
  24932. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  24933. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  24934. };
  24935. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  24936. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  24937. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  24938. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  24939. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  24940. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  24941. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  24942. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  24943. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  24944. polyhedra[14] = {
  24945. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  24946. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  24947. };
  24948. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24949. var size = options.size;
  24950. var sizeX = options.sizeX || size || 1;
  24951. var sizeY = options.sizeY || size || 1;
  24952. var sizeZ = options.sizeZ || size || 1;
  24953. var data = options.custom || polyhedra[type];
  24954. var nbfaces = data.face.length;
  24955. var faceUV = options.faceUV || new Array(nbfaces);
  24956. var faceColors = options.faceColors;
  24957. var flat = (options.flat === undefined) ? true : options.flat;
  24958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24959. var positions = [];
  24960. var indices = [];
  24961. var normals = [];
  24962. var uvs = [];
  24963. var colors = [];
  24964. var index = 0;
  24965. var faceIdx = 0; // face cursor in the array "indexes"
  24966. var indexes = [];
  24967. var i = 0;
  24968. var f = 0;
  24969. var u, v, ang, x, y, tmp;
  24970. // default face colors and UV if undefined
  24971. if (flat) {
  24972. for (f = 0; f < nbfaces; f++) {
  24973. if (faceColors && faceColors[f] === undefined) {
  24974. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24975. }
  24976. if (faceUV && faceUV[f] === undefined) {
  24977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24978. }
  24979. }
  24980. }
  24981. if (!flat) {
  24982. for (i = 0; i < data.vertex.length; i++) {
  24983. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24984. uvs.push(0, 0);
  24985. }
  24986. for (f = 0; f < nbfaces; f++) {
  24987. for (i = 0; i < data.face[f].length - 2; i++) {
  24988. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24989. }
  24990. }
  24991. }
  24992. else {
  24993. for (f = 0; f < nbfaces; f++) {
  24994. var fl = data.face[f].length; // number of vertices of the current face
  24995. ang = 2 * Math.PI / fl;
  24996. x = 0.5 * Math.tan(ang / 2);
  24997. y = 0.5;
  24998. // positions, uvs, colors
  24999. for (i = 0; i < fl; i++) {
  25000. // positions
  25001. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  25002. indexes.push(index);
  25003. index++;
  25004. // uvs
  25005. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25006. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25007. uvs.push(u, v);
  25008. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25009. y = x * Math.sin(ang) + y * Math.cos(ang);
  25010. x = tmp;
  25011. // colors
  25012. if (faceColors) {
  25013. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25014. }
  25015. }
  25016. // indices from indexes
  25017. for (i = 0; i < fl - 2; i++) {
  25018. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25019. }
  25020. faceIdx += fl;
  25021. }
  25022. }
  25023. VertexData.ComputeNormals(positions, indices, normals);
  25024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25025. var vertexData = new VertexData();
  25026. vertexData.positions = positions;
  25027. vertexData.indices = indices;
  25028. vertexData.normals = normals;
  25029. vertexData.uvs = uvs;
  25030. if (faceColors && flat) {
  25031. vertexData.colors = colors;
  25032. }
  25033. return vertexData;
  25034. };
  25035. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25036. VertexData.CreateTorusKnot = function (options) {
  25037. var indices = [];
  25038. var positions = [];
  25039. var normals = [];
  25040. var uvs = [];
  25041. var radius = options.radius || 2;
  25042. var tube = options.tube || 0.5;
  25043. var radialSegments = options.radialSegments || 32;
  25044. var tubularSegments = options.tubularSegments || 32;
  25045. var p = options.p || 2;
  25046. var q = options.q || 3;
  25047. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25048. // Helper
  25049. var getPos = function (angle) {
  25050. var cu = Math.cos(angle);
  25051. var su = Math.sin(angle);
  25052. var quOverP = q / p * angle;
  25053. var cs = Math.cos(quOverP);
  25054. var tx = radius * (2 + cs) * 0.5 * cu;
  25055. var ty = radius * (2 + cs) * su * 0.5;
  25056. var tz = radius * Math.sin(quOverP) * 0.5;
  25057. return new BABYLON.Vector3(tx, ty, tz);
  25058. };
  25059. // Vertices
  25060. var i;
  25061. var j;
  25062. for (i = 0; i <= radialSegments; i++) {
  25063. var modI = i % radialSegments;
  25064. var u = modI / radialSegments * 2 * p * Math.PI;
  25065. var p1 = getPos(u);
  25066. var p2 = getPos(u + 0.01);
  25067. var tang = p2.subtract(p1);
  25068. var n = p2.add(p1);
  25069. var bitan = BABYLON.Vector3.Cross(tang, n);
  25070. n = BABYLON.Vector3.Cross(bitan, tang);
  25071. bitan.normalize();
  25072. n.normalize();
  25073. for (j = 0; j < tubularSegments; j++) {
  25074. var modJ = j % tubularSegments;
  25075. var v = modJ / tubularSegments * 2 * Math.PI;
  25076. var cx = -tube * Math.cos(v);
  25077. var cy = tube * Math.sin(v);
  25078. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25079. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25080. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25081. uvs.push(i / radialSegments);
  25082. uvs.push(j / tubularSegments);
  25083. }
  25084. }
  25085. for (i = 0; i < radialSegments; i++) {
  25086. for (j = 0; j < tubularSegments; j++) {
  25087. var jNext = (j + 1) % tubularSegments;
  25088. var a = i * tubularSegments + j;
  25089. var b = (i + 1) * tubularSegments + j;
  25090. var c = (i + 1) * tubularSegments + jNext;
  25091. var d = i * tubularSegments + jNext;
  25092. indices.push(d);
  25093. indices.push(b);
  25094. indices.push(a);
  25095. indices.push(d);
  25096. indices.push(c);
  25097. indices.push(b);
  25098. }
  25099. }
  25100. // Normals
  25101. VertexData.ComputeNormals(positions, indices, normals);
  25102. // Sides
  25103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25104. // Result
  25105. var vertexData = new VertexData();
  25106. vertexData.indices = indices;
  25107. vertexData.positions = positions;
  25108. vertexData.normals = normals;
  25109. vertexData.uvs = uvs;
  25110. return vertexData;
  25111. };
  25112. // Tools
  25113. /**
  25114. * @param {any} - positions (number[] or Float32Array)
  25115. * @param {any} - indices (number[] or Uint16Array)
  25116. * @param {any} - normals (number[] or Float32Array)
  25117. */
  25118. VertexData.ComputeNormals = function (positions, indices, normals) {
  25119. var index = 0;
  25120. var p1p2x = 0.0;
  25121. var p1p2y = 0.0;
  25122. var p1p2z = 0.0;
  25123. var p3p2x = 0.0;
  25124. var p3p2y = 0.0;
  25125. var p3p2z = 0.0;
  25126. var faceNormalx = 0.0;
  25127. var faceNormaly = 0.0;
  25128. var faceNormalz = 0.0;
  25129. var length = 0.0;
  25130. var i1 = 0;
  25131. var i2 = 0;
  25132. var i3 = 0;
  25133. for (index = 0; index < positions.length; index++) {
  25134. normals[index] = 0.0;
  25135. }
  25136. // indice triplet = 1 face
  25137. var nbFaces = indices.length / 3;
  25138. for (index = 0; index < nbFaces; index++) {
  25139. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25140. i2 = indices[index * 3 + 1];
  25141. i3 = indices[index * 3 + 2];
  25142. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25143. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25144. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25145. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25146. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25147. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25148. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25149. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25150. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25151. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25152. length = (length === 0) ? 1.0 : length;
  25153. faceNormalx /= length; // normalize this normal
  25154. faceNormaly /= length;
  25155. faceNormalz /= length;
  25156. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25157. normals[i1 * 3 + 1] += faceNormaly;
  25158. normals[i1 * 3 + 2] += faceNormalz;
  25159. normals[i2 * 3] += faceNormalx;
  25160. normals[i2 * 3 + 1] += faceNormaly;
  25161. normals[i2 * 3 + 2] += faceNormalz;
  25162. normals[i3 * 3] += faceNormalx;
  25163. normals[i3 * 3 + 1] += faceNormaly;
  25164. normals[i3 * 3 + 2] += faceNormalz;
  25165. }
  25166. // last normalization of each normal
  25167. for (index = 0; index < normals.length / 3; index++) {
  25168. faceNormalx = normals[index * 3];
  25169. faceNormaly = normals[index * 3 + 1];
  25170. faceNormalz = normals[index * 3 + 2];
  25171. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25172. length = (length === 0) ? 1.0 : length;
  25173. faceNormalx /= length;
  25174. faceNormaly /= length;
  25175. faceNormalz /= length;
  25176. normals[index * 3] = faceNormalx;
  25177. normals[index * 3 + 1] = faceNormaly;
  25178. normals[index * 3 + 2] = faceNormalz;
  25179. }
  25180. };
  25181. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25182. var li = indices.length;
  25183. var ln = normals.length;
  25184. var i;
  25185. var n;
  25186. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25187. switch (sideOrientation) {
  25188. case BABYLON.Mesh.FRONTSIDE:
  25189. // nothing changed
  25190. break;
  25191. case BABYLON.Mesh.BACKSIDE:
  25192. var tmp;
  25193. // indices
  25194. for (i = 0; i < li; i += 3) {
  25195. tmp = indices[i];
  25196. indices[i] = indices[i + 2];
  25197. indices[i + 2] = tmp;
  25198. }
  25199. // normals
  25200. for (n = 0; n < ln; n++) {
  25201. normals[n] = -normals[n];
  25202. }
  25203. break;
  25204. case BABYLON.Mesh.DOUBLESIDE:
  25205. // positions
  25206. var lp = positions.length;
  25207. var l = lp / 3;
  25208. for (var p = 0; p < lp; p++) {
  25209. positions[lp + p] = positions[p];
  25210. }
  25211. // indices
  25212. for (i = 0; i < li; i += 3) {
  25213. indices[i + li] = indices[i + 2] + l;
  25214. indices[i + 1 + li] = indices[i + 1] + l;
  25215. indices[i + 2 + li] = indices[i] + l;
  25216. }
  25217. // normals
  25218. for (n = 0; n < ln; n++) {
  25219. normals[ln + n] = -normals[n];
  25220. }
  25221. // uvs
  25222. var lu = uvs.length;
  25223. for (var u = 0; u < lu; u++) {
  25224. uvs[u + lu] = uvs[u];
  25225. }
  25226. break;
  25227. }
  25228. };
  25229. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25230. var vertexData = new VertexData();
  25231. // positions
  25232. var positions = parsedVertexData.positions;
  25233. if (positions) {
  25234. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25235. }
  25236. // normals
  25237. var normals = parsedVertexData.normals;
  25238. if (normals) {
  25239. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25240. }
  25241. // uvs
  25242. var uvs = parsedVertexData.uvs;
  25243. if (uvs) {
  25244. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25245. }
  25246. // uv2s
  25247. var uv2s = parsedVertexData.uv2s;
  25248. if (uv2s) {
  25249. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25250. }
  25251. // uv3s
  25252. var uv3s = parsedVertexData.uv3s;
  25253. if (uv3s) {
  25254. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25255. }
  25256. // uv4s
  25257. var uv4s = parsedVertexData.uv4s;
  25258. if (uv4s) {
  25259. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25260. }
  25261. // uv5s
  25262. var uv5s = parsedVertexData.uv5s;
  25263. if (uv5s) {
  25264. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25265. }
  25266. // uv6s
  25267. var uv6s = parsedVertexData.uv6s;
  25268. if (uv6s) {
  25269. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25270. }
  25271. // colors
  25272. var colors = parsedVertexData.colors;
  25273. if (colors) {
  25274. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25275. }
  25276. // matricesIndices
  25277. var matricesIndices = parsedVertexData.matricesIndices;
  25278. if (matricesIndices) {
  25279. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25280. }
  25281. // matricesWeights
  25282. var matricesWeights = parsedVertexData.matricesWeights;
  25283. if (matricesWeights) {
  25284. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25285. }
  25286. // indices
  25287. var indices = parsedVertexData.indices;
  25288. if (indices) {
  25289. vertexData.indices = indices;
  25290. }
  25291. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25292. };
  25293. return VertexData;
  25294. })();
  25295. BABYLON.VertexData = VertexData;
  25296. })(BABYLON || (BABYLON = {}));
  25297. var BABYLON;
  25298. (function (BABYLON) {
  25299. var Tags = (function () {
  25300. function Tags() {
  25301. }
  25302. Tags.EnableFor = function (obj) {
  25303. obj._tags = obj._tags || {};
  25304. obj.hasTags = function () {
  25305. return Tags.HasTags(obj);
  25306. };
  25307. obj.addTags = function (tagsString) {
  25308. return Tags.AddTagsTo(obj, tagsString);
  25309. };
  25310. obj.removeTags = function (tagsString) {
  25311. return Tags.RemoveTagsFrom(obj, tagsString);
  25312. };
  25313. obj.matchesTagsQuery = function (tagsQuery) {
  25314. return Tags.MatchesQuery(obj, tagsQuery);
  25315. };
  25316. };
  25317. Tags.DisableFor = function (obj) {
  25318. delete obj._tags;
  25319. delete obj.hasTags;
  25320. delete obj.addTags;
  25321. delete obj.removeTags;
  25322. delete obj.matchesTagsQuery;
  25323. };
  25324. Tags.HasTags = function (obj) {
  25325. if (!obj._tags) {
  25326. return false;
  25327. }
  25328. return !BABYLON.Tools.IsEmpty(obj._tags);
  25329. };
  25330. Tags.GetTags = function (obj, asString) {
  25331. if (asString === void 0) { asString = true; }
  25332. if (!obj._tags) {
  25333. return null;
  25334. }
  25335. if (asString) {
  25336. var tagsArray = [];
  25337. for (var tag in obj._tags) {
  25338. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25339. tagsArray.push(tag);
  25340. }
  25341. }
  25342. return tagsArray.join(" ");
  25343. }
  25344. else {
  25345. return obj._tags;
  25346. }
  25347. };
  25348. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25349. // a tag cannot start with '||', '&&', and '!'
  25350. // it cannot contain whitespaces
  25351. Tags.AddTagsTo = function (obj, tagsString) {
  25352. if (!tagsString) {
  25353. return;
  25354. }
  25355. if (typeof tagsString !== "string") {
  25356. return;
  25357. }
  25358. var tags = tagsString.split(" ");
  25359. for (var t in tags) {
  25360. Tags._AddTagTo(obj, tags[t]);
  25361. }
  25362. };
  25363. Tags._AddTagTo = function (obj, tag) {
  25364. tag = tag.trim();
  25365. if (tag === "" || tag === "true" || tag === "false") {
  25366. return;
  25367. }
  25368. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25369. return;
  25370. }
  25371. Tags.EnableFor(obj);
  25372. obj._tags[tag] = true;
  25373. };
  25374. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25375. if (!Tags.HasTags(obj)) {
  25376. return;
  25377. }
  25378. var tags = tagsString.split(" ");
  25379. for (var t in tags) {
  25380. Tags._RemoveTagFrom(obj, tags[t]);
  25381. }
  25382. };
  25383. Tags._RemoveTagFrom = function (obj, tag) {
  25384. delete obj._tags[tag];
  25385. };
  25386. Tags.MatchesQuery = function (obj, tagsQuery) {
  25387. if (tagsQuery === undefined) {
  25388. return true;
  25389. }
  25390. if (tagsQuery === "") {
  25391. return Tags.HasTags(obj);
  25392. }
  25393. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25394. };
  25395. return Tags;
  25396. })();
  25397. BABYLON.Tags = Tags;
  25398. })(BABYLON || (BABYLON = {}));
  25399. var BABYLON;
  25400. (function (BABYLON) {
  25401. var Internals;
  25402. (function (Internals) {
  25403. var AndOrNotEvaluator = (function () {
  25404. function AndOrNotEvaluator() {
  25405. }
  25406. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25407. if (!query.match(/\([^\(\)]*\)/g)) {
  25408. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25409. }
  25410. else {
  25411. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25412. // remove parenthesis
  25413. r = r.slice(1, r.length - 1);
  25414. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25415. });
  25416. }
  25417. if (query === "true") {
  25418. return true;
  25419. }
  25420. if (query === "false") {
  25421. return false;
  25422. }
  25423. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25424. };
  25425. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25426. evaluateCallback = evaluateCallback || (function (r) {
  25427. return r === "true" ? true : false;
  25428. });
  25429. var result;
  25430. var or = parenthesisContent.split("||");
  25431. for (var i in or) {
  25432. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25433. var and = ori.split("&&");
  25434. if (and.length > 1) {
  25435. for (var j = 0; j < and.length; ++j) {
  25436. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25437. if (andj !== "true" && andj !== "false") {
  25438. if (andj[0] === "!") {
  25439. result = !evaluateCallback(andj.substring(1));
  25440. }
  25441. else {
  25442. result = evaluateCallback(andj);
  25443. }
  25444. }
  25445. else {
  25446. result = andj === "true" ? true : false;
  25447. }
  25448. if (!result) {
  25449. ori = "false";
  25450. break;
  25451. }
  25452. }
  25453. }
  25454. if (result || ori === "true") {
  25455. result = true;
  25456. break;
  25457. }
  25458. // result equals false (or undefined)
  25459. if (ori !== "true" && ori !== "false") {
  25460. if (ori[0] === "!") {
  25461. result = !evaluateCallback(ori.substring(1));
  25462. }
  25463. else {
  25464. result = evaluateCallback(ori);
  25465. }
  25466. }
  25467. else {
  25468. result = ori === "true" ? true : false;
  25469. }
  25470. }
  25471. // the whole parenthesis scope is replaced by 'true' or 'false'
  25472. return result ? "true" : "false";
  25473. };
  25474. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25475. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25476. // remove whitespaces
  25477. r = r.replace(/[\s]/g, function () { return ""; });
  25478. return r.length % 2 ? "!" : "";
  25479. });
  25480. booleanString = booleanString.trim();
  25481. if (booleanString === "!true") {
  25482. booleanString = "false";
  25483. }
  25484. else if (booleanString === "!false") {
  25485. booleanString = "true";
  25486. }
  25487. return booleanString;
  25488. };
  25489. return AndOrNotEvaluator;
  25490. })();
  25491. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25492. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25493. })(BABYLON || (BABYLON = {}));
  25494. var BABYLON;
  25495. (function (BABYLON) {
  25496. var PostProcessRenderPass = (function () {
  25497. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25498. this._enabled = true;
  25499. this._refCount = 0;
  25500. this._name = name;
  25501. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25502. this.setRenderList(renderList);
  25503. this._renderTexture.onBeforeRender = beforeRender;
  25504. this._renderTexture.onAfterRender = afterRender;
  25505. this._scene = scene;
  25506. this._renderList = renderList;
  25507. }
  25508. // private
  25509. PostProcessRenderPass.prototype._incRefCount = function () {
  25510. if (this._refCount === 0) {
  25511. this._scene.customRenderTargets.push(this._renderTexture);
  25512. }
  25513. return ++this._refCount;
  25514. };
  25515. PostProcessRenderPass.prototype._decRefCount = function () {
  25516. this._refCount--;
  25517. if (this._refCount <= 0) {
  25518. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25519. }
  25520. return this._refCount;
  25521. };
  25522. PostProcessRenderPass.prototype._update = function () {
  25523. this.setRenderList(this._renderList);
  25524. };
  25525. // public
  25526. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25527. this._renderTexture.renderList = renderList;
  25528. };
  25529. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25530. return this._renderTexture;
  25531. };
  25532. return PostProcessRenderPass;
  25533. })();
  25534. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25535. })(BABYLON || (BABYLON = {}));
  25536. var BABYLON;
  25537. (function (BABYLON) {
  25538. var PostProcessRenderEffect = (function () {
  25539. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25540. this._engine = engine;
  25541. this._name = name;
  25542. this._singleInstance = singleInstance || true;
  25543. this._getPostProcess = getPostProcess;
  25544. this._cameras = [];
  25545. this._indicesForCamera = [];
  25546. this._postProcesses = {};
  25547. this._renderPasses = {};
  25548. this._renderEffectAsPasses = {};
  25549. }
  25550. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25551. get: function () {
  25552. for (var index in this._postProcesses) {
  25553. if (!this._postProcesses[index].isSupported) {
  25554. return false;
  25555. }
  25556. }
  25557. return true;
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. PostProcessRenderEffect.prototype._update = function () {
  25563. for (var renderPassName in this._renderPasses) {
  25564. this._renderPasses[renderPassName]._update();
  25565. }
  25566. };
  25567. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25568. this._renderPasses[renderPass._name] = renderPass;
  25569. this._linkParameters();
  25570. };
  25571. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25572. delete this._renderPasses[renderPass._name];
  25573. this._linkParameters();
  25574. };
  25575. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25576. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25577. this._linkParameters();
  25578. };
  25579. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25580. for (var renderPassName in this._renderPasses) {
  25581. if (renderPassName === passName) {
  25582. return this._renderPasses[passName];
  25583. }
  25584. }
  25585. };
  25586. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25587. this._renderPasses = {};
  25588. this._linkParameters();
  25589. };
  25590. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25591. var cameraKey;
  25592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25593. for (var i = 0; i < _cam.length; i++) {
  25594. var camera = _cam[i];
  25595. var cameraName = camera.name;
  25596. if (this._singleInstance) {
  25597. cameraKey = 0;
  25598. }
  25599. else {
  25600. cameraKey = cameraName;
  25601. }
  25602. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25603. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25604. if (!this._indicesForCamera[cameraName]) {
  25605. this._indicesForCamera[cameraName] = [];
  25606. }
  25607. this._indicesForCamera[cameraName].push(index);
  25608. if (this._cameras.indexOf(camera) === -1) {
  25609. this._cameras[cameraName] = camera;
  25610. }
  25611. for (var passName in this._renderPasses) {
  25612. this._renderPasses[passName]._incRefCount();
  25613. }
  25614. }
  25615. this._linkParameters();
  25616. };
  25617. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25618. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25619. for (var i = 0; i < _cam.length; i++) {
  25620. var camera = _cam[i];
  25621. var cameraName = camera.name;
  25622. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25623. var index = this._cameras.indexOf(cameraName);
  25624. this._indicesForCamera.splice(index, 1);
  25625. this._cameras.splice(index, 1);
  25626. for (var passName in this._renderPasses) {
  25627. this._renderPasses[passName]._decRefCount();
  25628. }
  25629. }
  25630. };
  25631. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25632. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25633. for (var i = 0; i < _cam.length; i++) {
  25634. var camera = _cam[i];
  25635. var cameraName = camera.name;
  25636. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25637. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25638. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25639. }
  25640. }
  25641. for (var passName in this._renderPasses) {
  25642. this._renderPasses[passName]._incRefCount();
  25643. }
  25644. }
  25645. };
  25646. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25647. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25648. for (var i = 0; i < _cam.length; i++) {
  25649. var camera = _cam[i];
  25650. var cameraName = camera.Name;
  25651. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25652. for (var passName in this._renderPasses) {
  25653. this._renderPasses[passName]._decRefCount();
  25654. }
  25655. }
  25656. };
  25657. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25658. if (this._singleInstance) {
  25659. return this._postProcesses[0];
  25660. }
  25661. else {
  25662. return this._postProcesses[camera.name];
  25663. }
  25664. };
  25665. PostProcessRenderEffect.prototype._linkParameters = function () {
  25666. var _this = this;
  25667. for (var index in this._postProcesses) {
  25668. if (this.applyParameters) {
  25669. this.applyParameters(this._postProcesses[index]);
  25670. }
  25671. this._postProcesses[index].onBeforeRender = function (effect) {
  25672. _this._linkTextures(effect);
  25673. };
  25674. }
  25675. };
  25676. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25677. for (var renderPassName in this._renderPasses) {
  25678. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25679. }
  25680. for (var renderEffectName in this._renderEffectAsPasses) {
  25681. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25682. }
  25683. };
  25684. return PostProcessRenderEffect;
  25685. })();
  25686. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25687. })(BABYLON || (BABYLON = {}));
  25688. var BABYLON;
  25689. (function (BABYLON) {
  25690. var PostProcessRenderPipeline = (function () {
  25691. function PostProcessRenderPipeline(engine, name) {
  25692. this._engine = engine;
  25693. this._name = name;
  25694. this._renderEffects = {};
  25695. this._renderEffectsForIsolatedPass = {};
  25696. this._cameras = [];
  25697. }
  25698. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25699. get: function () {
  25700. for (var renderEffectName in this._renderEffects) {
  25701. if (!this._renderEffects[renderEffectName].isSupported) {
  25702. return false;
  25703. }
  25704. }
  25705. return true;
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25711. this._renderEffects[renderEffect._name] = renderEffect;
  25712. };
  25713. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25714. var renderEffects = this._renderEffects[renderEffectName];
  25715. if (!renderEffects) {
  25716. return;
  25717. }
  25718. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25719. };
  25720. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25721. var renderEffects = this._renderEffects[renderEffectName];
  25722. if (!renderEffects) {
  25723. return;
  25724. }
  25725. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25726. };
  25727. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25728. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25729. var indicesToDelete = [];
  25730. var i;
  25731. for (i = 0; i < _cam.length; i++) {
  25732. var camera = _cam[i];
  25733. var cameraName = camera.name;
  25734. if (this._cameras.indexOf(camera) === -1) {
  25735. this._cameras[cameraName] = camera;
  25736. }
  25737. else if (unique) {
  25738. indicesToDelete.push(i);
  25739. }
  25740. }
  25741. for (i = 0; i < indicesToDelete.length; i++) {
  25742. cameras.splice(indicesToDelete[i], 1);
  25743. }
  25744. for (var renderEffectName in this._renderEffects) {
  25745. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25746. }
  25747. };
  25748. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25749. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25750. for (var renderEffectName in this._renderEffects) {
  25751. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25752. }
  25753. for (var i = 0; i < _cam.length; i++) {
  25754. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25755. }
  25756. };
  25757. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25758. var _this = this;
  25759. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25760. var pass = null;
  25761. var renderEffectName;
  25762. for (renderEffectName in this._renderEffects) {
  25763. pass = this._renderEffects[renderEffectName].getPass(passName);
  25764. if (pass != null) {
  25765. break;
  25766. }
  25767. }
  25768. if (pass === null) {
  25769. return;
  25770. }
  25771. for (renderEffectName in this._renderEffects) {
  25772. this._renderEffects[renderEffectName]._disable(_cam);
  25773. }
  25774. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25775. for (var i = 0; i < _cam.length; i++) {
  25776. var camera = _cam[i];
  25777. var cameraName = camera.name;
  25778. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  25779. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25780. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25781. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25782. }
  25783. };
  25784. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25785. var _this = this;
  25786. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25787. for (var i = 0; i < _cam.length; i++) {
  25788. var camera = _cam[i];
  25789. var cameraName = camera.name;
  25790. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  25791. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25792. }
  25793. for (var renderEffectName in this._renderEffects) {
  25794. this._renderEffects[renderEffectName]._enable(_cam);
  25795. }
  25796. };
  25797. PostProcessRenderPipeline.prototype._update = function () {
  25798. for (var renderEffectName in this._renderEffects) {
  25799. this._renderEffects[renderEffectName]._update();
  25800. }
  25801. for (var i = 0; i < this._cameras.length; i++) {
  25802. var cameraName = this._cameras[i].name;
  25803. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25804. this._renderEffectsForIsolatedPass[cameraName]._update();
  25805. }
  25806. }
  25807. };
  25808. PostProcessRenderPipeline.prototype.dispose = function () {
  25809. // Must be implemented by children
  25810. };
  25811. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25812. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25813. return PostProcessRenderPipeline;
  25814. })();
  25815. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25816. })(BABYLON || (BABYLON = {}));
  25817. var BABYLON;
  25818. (function (BABYLON) {
  25819. var PostProcessRenderPipelineManager = (function () {
  25820. function PostProcessRenderPipelineManager() {
  25821. this._renderPipelines = {};
  25822. }
  25823. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25824. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25825. };
  25826. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25827. var renderPipeline = this._renderPipelines[renderPipelineName];
  25828. if (!renderPipeline) {
  25829. return;
  25830. }
  25831. renderPipeline._attachCameras(cameras, unique);
  25832. };
  25833. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25834. var renderPipeline = this._renderPipelines[renderPipelineName];
  25835. if (!renderPipeline) {
  25836. return;
  25837. }
  25838. renderPipeline._detachCameras(cameras);
  25839. };
  25840. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25841. var renderPipeline = this._renderPipelines[renderPipelineName];
  25842. if (!renderPipeline) {
  25843. return;
  25844. }
  25845. renderPipeline._enableEffect(renderEffectName, cameras);
  25846. };
  25847. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25848. var renderPipeline = this._renderPipelines[renderPipelineName];
  25849. if (!renderPipeline) {
  25850. return;
  25851. }
  25852. renderPipeline._disableEffect(renderEffectName, cameras);
  25853. };
  25854. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25855. var renderPipeline = this._renderPipelines[renderPipelineName];
  25856. if (!renderPipeline) {
  25857. return;
  25858. }
  25859. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25860. };
  25861. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25862. var renderPipeline = this._renderPipelines[renderPipelineName];
  25863. if (!renderPipeline) {
  25864. return;
  25865. }
  25866. renderPipeline._disableDisplayOnlyPass(cameras);
  25867. };
  25868. PostProcessRenderPipelineManager.prototype.update = function () {
  25869. for (var renderPipelineName in this._renderPipelines) {
  25870. var pipeline = this._renderPipelines[renderPipelineName];
  25871. if (!pipeline.isSupported) {
  25872. pipeline.dispose();
  25873. delete this._renderPipelines[renderPipelineName];
  25874. }
  25875. else {
  25876. pipeline._update();
  25877. }
  25878. }
  25879. };
  25880. return PostProcessRenderPipelineManager;
  25881. })();
  25882. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25883. })(BABYLON || (BABYLON = {}));
  25884. var BABYLON;
  25885. (function (BABYLON) {
  25886. var BoundingBoxRenderer = (function () {
  25887. function BoundingBoxRenderer(scene) {
  25888. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25889. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25890. this.showBackLines = true;
  25891. this.renderList = new BABYLON.SmartArray(32);
  25892. this._scene = scene;
  25893. }
  25894. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25895. if (this._colorShader) {
  25896. return;
  25897. }
  25898. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25899. attributes: ["position"],
  25900. uniforms: ["worldViewProjection", "color"]
  25901. });
  25902. var engine = this._scene.getEngine();
  25903. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25904. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25905. 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]);
  25906. };
  25907. BoundingBoxRenderer.prototype.reset = function () {
  25908. this.renderList.reset();
  25909. };
  25910. BoundingBoxRenderer.prototype.render = function () {
  25911. if (this.renderList.length === 0) {
  25912. return;
  25913. }
  25914. this._prepareRessources();
  25915. if (!this._colorShader.isReady()) {
  25916. return;
  25917. }
  25918. var engine = this._scene.getEngine();
  25919. engine.setDepthWrite(false);
  25920. this._colorShader._preBind();
  25921. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25922. var boundingBox = this.renderList.data[boundingBoxIndex];
  25923. var min = boundingBox.minimum;
  25924. var max = boundingBox.maximum;
  25925. var diff = max.subtract(min);
  25926. var median = min.add(diff.scale(0.5));
  25927. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25928. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25929. .multiply(boundingBox.getWorldMatrix());
  25930. // VBOs
  25931. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25932. if (this.showBackLines) {
  25933. // Back
  25934. engine.setDepthFunctionToGreaterOrEqual();
  25935. this._scene.resetCachedMaterial();
  25936. this._colorShader.setColor4("color", this.backColor.toColor4());
  25937. this._colorShader.bind(worldMatrix);
  25938. // Draw order
  25939. engine.draw(false, 0, 24);
  25940. }
  25941. // Front
  25942. engine.setDepthFunctionToLess();
  25943. this._scene.resetCachedMaterial();
  25944. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25945. this._colorShader.bind(worldMatrix);
  25946. // Draw order
  25947. engine.draw(false, 0, 24);
  25948. }
  25949. this._colorShader.unbind();
  25950. engine.setDepthFunctionToLessOrEqual();
  25951. engine.setDepthWrite(true);
  25952. };
  25953. BoundingBoxRenderer.prototype.dispose = function () {
  25954. if (!this._colorShader) {
  25955. return;
  25956. }
  25957. this._colorShader.dispose();
  25958. this._vb.dispose();
  25959. this._scene.getEngine()._releaseBuffer(this._ib);
  25960. };
  25961. return BoundingBoxRenderer;
  25962. })();
  25963. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25964. })(BABYLON || (BABYLON = {}));
  25965. var BABYLON;
  25966. (function (BABYLON) {
  25967. var Condition = (function () {
  25968. function Condition(actionManager) {
  25969. this._actionManager = actionManager;
  25970. }
  25971. Condition.prototype.isValid = function () {
  25972. return true;
  25973. };
  25974. Condition.prototype._getProperty = function (propertyPath) {
  25975. return this._actionManager._getProperty(propertyPath);
  25976. };
  25977. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25978. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25979. };
  25980. return Condition;
  25981. })();
  25982. BABYLON.Condition = Condition;
  25983. var ValueCondition = (function (_super) {
  25984. __extends(ValueCondition, _super);
  25985. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25986. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25987. _super.call(this, actionManager);
  25988. this.propertyPath = propertyPath;
  25989. this.value = value;
  25990. this.operator = operator;
  25991. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25992. this._property = this._getProperty(this.propertyPath);
  25993. }
  25994. Object.defineProperty(ValueCondition, "IsEqual", {
  25995. get: function () {
  25996. return ValueCondition._IsEqual;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(ValueCondition, "IsDifferent", {
  26002. get: function () {
  26003. return ValueCondition._IsDifferent;
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. Object.defineProperty(ValueCondition, "IsGreater", {
  26009. get: function () {
  26010. return ValueCondition._IsGreater;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(ValueCondition, "IsLesser", {
  26016. get: function () {
  26017. return ValueCondition._IsLesser;
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. // Methods
  26023. ValueCondition.prototype.isValid = function () {
  26024. switch (this.operator) {
  26025. case ValueCondition.IsGreater:
  26026. return this._target[this._property] > this.value;
  26027. case ValueCondition.IsLesser:
  26028. return this._target[this._property] < this.value;
  26029. case ValueCondition.IsEqual:
  26030. case ValueCondition.IsDifferent:
  26031. var check;
  26032. if (this.value.equals) {
  26033. check = this.value.equals(this._target[this._property]);
  26034. }
  26035. else {
  26036. check = this.value === this._target[this._property];
  26037. }
  26038. return this.operator === ValueCondition.IsEqual ? check : !check;
  26039. }
  26040. return false;
  26041. };
  26042. // Statics
  26043. ValueCondition._IsEqual = 0;
  26044. ValueCondition._IsDifferent = 1;
  26045. ValueCondition._IsGreater = 2;
  26046. ValueCondition._IsLesser = 3;
  26047. return ValueCondition;
  26048. })(Condition);
  26049. BABYLON.ValueCondition = ValueCondition;
  26050. var PredicateCondition = (function (_super) {
  26051. __extends(PredicateCondition, _super);
  26052. function PredicateCondition(actionManager, predicate) {
  26053. _super.call(this, actionManager);
  26054. this.predicate = predicate;
  26055. }
  26056. PredicateCondition.prototype.isValid = function () {
  26057. return this.predicate();
  26058. };
  26059. return PredicateCondition;
  26060. })(Condition);
  26061. BABYLON.PredicateCondition = PredicateCondition;
  26062. var StateCondition = (function (_super) {
  26063. __extends(StateCondition, _super);
  26064. function StateCondition(actionManager, target, value) {
  26065. _super.call(this, actionManager);
  26066. this.value = value;
  26067. this._target = target;
  26068. }
  26069. // Methods
  26070. StateCondition.prototype.isValid = function () {
  26071. return this._target.state === this.value;
  26072. };
  26073. return StateCondition;
  26074. })(Condition);
  26075. BABYLON.StateCondition = StateCondition;
  26076. })(BABYLON || (BABYLON = {}));
  26077. var BABYLON;
  26078. (function (BABYLON) {
  26079. var Action = (function () {
  26080. function Action(triggerOptions, condition) {
  26081. this.triggerOptions = triggerOptions;
  26082. if (triggerOptions.parameter) {
  26083. this.trigger = triggerOptions.trigger;
  26084. this._triggerParameter = triggerOptions.parameter;
  26085. }
  26086. else {
  26087. this.trigger = triggerOptions;
  26088. }
  26089. this._nextActiveAction = this;
  26090. this._condition = condition;
  26091. }
  26092. // Methods
  26093. Action.prototype._prepare = function () {
  26094. };
  26095. Action.prototype.getTriggerParameter = function () {
  26096. return this._triggerParameter;
  26097. };
  26098. Action.prototype._executeCurrent = function (evt) {
  26099. if (this._nextActiveAction._condition) {
  26100. var condition = this._nextActiveAction._condition;
  26101. var currentRenderId = this._actionManager.getScene().getRenderId();
  26102. // We cache the current evaluation for the current frame
  26103. if (condition._evaluationId === currentRenderId) {
  26104. if (!condition._currentResult) {
  26105. return;
  26106. }
  26107. }
  26108. else {
  26109. condition._evaluationId = currentRenderId;
  26110. if (!condition.isValid()) {
  26111. condition._currentResult = false;
  26112. return;
  26113. }
  26114. condition._currentResult = true;
  26115. }
  26116. }
  26117. this._nextActiveAction.execute(evt);
  26118. this.skipToNextActiveAction();
  26119. };
  26120. Action.prototype.execute = function (evt) {
  26121. };
  26122. Action.prototype.skipToNextActiveAction = function () {
  26123. if (this._nextActiveAction._child) {
  26124. if (!this._nextActiveAction._child._actionManager) {
  26125. this._nextActiveAction._child._actionManager = this._actionManager;
  26126. }
  26127. this._nextActiveAction = this._nextActiveAction._child;
  26128. }
  26129. else {
  26130. this._nextActiveAction = this;
  26131. }
  26132. };
  26133. Action.prototype.then = function (action) {
  26134. this._child = action;
  26135. action._actionManager = this._actionManager;
  26136. action._prepare();
  26137. return action;
  26138. };
  26139. Action.prototype._getProperty = function (propertyPath) {
  26140. return this._actionManager._getProperty(propertyPath);
  26141. };
  26142. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26143. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26144. };
  26145. return Action;
  26146. })();
  26147. BABYLON.Action = Action;
  26148. })(BABYLON || (BABYLON = {}));
  26149. var BABYLON;
  26150. (function (BABYLON) {
  26151. /**
  26152. * ActionEvent is the event beint sent when an action is triggered.
  26153. */
  26154. var ActionEvent = (function () {
  26155. /**
  26156. * @constructor
  26157. * @param source The mesh or sprite that triggered the action.
  26158. * @param pointerX The X mouse cursor position at the time of the event
  26159. * @param pointerY The Y mouse cursor position at the time of the event
  26160. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26161. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26162. */
  26163. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26164. this.source = source;
  26165. this.pointerX = pointerX;
  26166. this.pointerY = pointerY;
  26167. this.meshUnderPointer = meshUnderPointer;
  26168. this.sourceEvent = sourceEvent;
  26169. this.additionalData = additionalData;
  26170. }
  26171. /**
  26172. * Helper function to auto-create an ActionEvent from a source mesh.
  26173. * @param source The source mesh that triggered the event
  26174. * @param evt {Event} The original (browser) event
  26175. */
  26176. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26177. var scene = source.getScene();
  26178. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26179. };
  26180. /**
  26181. * Helper function to auto-create an ActionEvent from a source mesh.
  26182. * @param source The source sprite that triggered the event
  26183. * @param scene Scene associated with the sprite
  26184. * @param evt {Event} The original (browser) event
  26185. */
  26186. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26187. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26188. };
  26189. /**
  26190. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26191. * @param scene the scene where the event occurred
  26192. * @param evt {Event} The original (browser) event
  26193. */
  26194. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26195. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26196. };
  26197. return ActionEvent;
  26198. })();
  26199. BABYLON.ActionEvent = ActionEvent;
  26200. /**
  26201. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26202. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26203. */
  26204. var ActionManager = (function () {
  26205. function ActionManager(scene) {
  26206. // Members
  26207. this.actions = new Array();
  26208. this._scene = scene;
  26209. scene._actionManagers.push(this);
  26210. }
  26211. Object.defineProperty(ActionManager, "NothingTrigger", {
  26212. get: function () {
  26213. return ActionManager._NothingTrigger;
  26214. },
  26215. enumerable: true,
  26216. configurable: true
  26217. });
  26218. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26219. get: function () {
  26220. return ActionManager._OnPickTrigger;
  26221. },
  26222. enumerable: true,
  26223. configurable: true
  26224. });
  26225. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26226. get: function () {
  26227. return ActionManager._OnLeftPickTrigger;
  26228. },
  26229. enumerable: true,
  26230. configurable: true
  26231. });
  26232. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26233. get: function () {
  26234. return ActionManager._OnRightPickTrigger;
  26235. },
  26236. enumerable: true,
  26237. configurable: true
  26238. });
  26239. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26240. get: function () {
  26241. return ActionManager._OnCenterPickTrigger;
  26242. },
  26243. enumerable: true,
  26244. configurable: true
  26245. });
  26246. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26247. get: function () {
  26248. return ActionManager._OnPickDownTrigger;
  26249. },
  26250. enumerable: true,
  26251. configurable: true
  26252. });
  26253. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26254. get: function () {
  26255. return ActionManager._OnPickUpTrigger;
  26256. },
  26257. enumerable: true,
  26258. configurable: true
  26259. });
  26260. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26261. /// This trigger will only be raised if you also declared a OnPickDown
  26262. get: function () {
  26263. return ActionManager._OnPickOutTrigger;
  26264. },
  26265. enumerable: true,
  26266. configurable: true
  26267. });
  26268. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26269. get: function () {
  26270. return ActionManager._OnLongPressTrigger;
  26271. },
  26272. enumerable: true,
  26273. configurable: true
  26274. });
  26275. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26276. get: function () {
  26277. return ActionManager._OnPointerOverTrigger;
  26278. },
  26279. enumerable: true,
  26280. configurable: true
  26281. });
  26282. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26283. get: function () {
  26284. return ActionManager._OnPointerOutTrigger;
  26285. },
  26286. enumerable: true,
  26287. configurable: true
  26288. });
  26289. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26290. get: function () {
  26291. return ActionManager._OnEveryFrameTrigger;
  26292. },
  26293. enumerable: true,
  26294. configurable: true
  26295. });
  26296. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26297. get: function () {
  26298. return ActionManager._OnIntersectionEnterTrigger;
  26299. },
  26300. enumerable: true,
  26301. configurable: true
  26302. });
  26303. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26304. get: function () {
  26305. return ActionManager._OnIntersectionExitTrigger;
  26306. },
  26307. enumerable: true,
  26308. configurable: true
  26309. });
  26310. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26311. get: function () {
  26312. return ActionManager._OnKeyDownTrigger;
  26313. },
  26314. enumerable: true,
  26315. configurable: true
  26316. });
  26317. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26318. get: function () {
  26319. return ActionManager._OnKeyUpTrigger;
  26320. },
  26321. enumerable: true,
  26322. configurable: true
  26323. });
  26324. // Methods
  26325. ActionManager.prototype.dispose = function () {
  26326. var index = this._scene._actionManagers.indexOf(this);
  26327. if (index > -1) {
  26328. this._scene._actionManagers.splice(index, 1);
  26329. }
  26330. };
  26331. ActionManager.prototype.getScene = function () {
  26332. return this._scene;
  26333. };
  26334. /**
  26335. * Does this action manager handles actions of any of the given triggers
  26336. * @param {number[]} triggers - the triggers to be tested
  26337. * @return {boolean} whether one (or more) of the triggers is handeled
  26338. */
  26339. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26340. for (var index = 0; index < this.actions.length; index++) {
  26341. var action = this.actions[index];
  26342. if (triggers.indexOf(action.trigger) > -1) {
  26343. return true;
  26344. }
  26345. }
  26346. return false;
  26347. };
  26348. /**
  26349. * Does this action manager handles actions of a given trigger
  26350. * @param {number} trigger - the trigger to be tested
  26351. * @return {boolean} whether the trigger is handeled
  26352. */
  26353. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26354. for (var index = 0; index < this.actions.length; index++) {
  26355. var action = this.actions[index];
  26356. if (action.trigger === trigger) {
  26357. return true;
  26358. }
  26359. }
  26360. return false;
  26361. };
  26362. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26363. /**
  26364. * Does this action manager has pointer triggers
  26365. * @return {boolean} whether or not it has pointer triggers
  26366. */
  26367. get: function () {
  26368. for (var index = 0; index < this.actions.length; index++) {
  26369. var action = this.actions[index];
  26370. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26371. return true;
  26372. }
  26373. }
  26374. return false;
  26375. },
  26376. enumerable: true,
  26377. configurable: true
  26378. });
  26379. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26380. /**
  26381. * Does this action manager has pick triggers
  26382. * @return {boolean} whether or not it has pick triggers
  26383. */
  26384. get: function () {
  26385. for (var index = 0; index < this.actions.length; index++) {
  26386. var action = this.actions[index];
  26387. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26388. return true;
  26389. }
  26390. }
  26391. return false;
  26392. },
  26393. enumerable: true,
  26394. configurable: true
  26395. });
  26396. /**
  26397. * Registers an action to this action manager
  26398. * @param {BABYLON.Action} action - the action to be registered
  26399. * @return {BABYLON.Action} the action amended (prepared) after registration
  26400. */
  26401. ActionManager.prototype.registerAction = function (action) {
  26402. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26403. if (this.getScene().actionManager !== this) {
  26404. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26405. return null;
  26406. }
  26407. }
  26408. this.actions.push(action);
  26409. action._actionManager = this;
  26410. action._prepare();
  26411. return action;
  26412. };
  26413. /**
  26414. * Process a specific trigger
  26415. * @param {number} trigger - the trigger to process
  26416. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26417. */
  26418. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26419. for (var index = 0; index < this.actions.length; index++) {
  26420. var action = this.actions[index];
  26421. if (action.trigger === trigger) {
  26422. if (trigger === ActionManager.OnKeyUpTrigger
  26423. || trigger === ActionManager.OnKeyDownTrigger) {
  26424. var parameter = action.getTriggerParameter();
  26425. if (parameter) {
  26426. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26427. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26428. if (actualkey !== parameter.toLowerCase()) {
  26429. continue;
  26430. }
  26431. }
  26432. }
  26433. action._executeCurrent(evt);
  26434. }
  26435. }
  26436. };
  26437. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26438. var properties = propertyPath.split(".");
  26439. for (var index = 0; index < properties.length - 1; index++) {
  26440. target = target[properties[index]];
  26441. }
  26442. return target;
  26443. };
  26444. ActionManager.prototype._getProperty = function (propertyPath) {
  26445. var properties = propertyPath.split(".");
  26446. return properties[properties.length - 1];
  26447. };
  26448. ActionManager.Parse = function (parsedActions, object, scene) {
  26449. var actionManager = new BABYLON.ActionManager(scene);
  26450. if (object === null)
  26451. scene.actionManager = actionManager;
  26452. else
  26453. object.actionManager = actionManager;
  26454. // instanciate a new object
  26455. var instanciate = function (name, params) {
  26456. var newInstance = Object.create(BABYLON[name].prototype);
  26457. newInstance.constructor.apply(newInstance, params);
  26458. return newInstance;
  26459. };
  26460. var parseParameter = function (name, value, target, propertyPath) {
  26461. if (propertyPath === null) {
  26462. // String, boolean or float
  26463. var floatValue = parseFloat(value);
  26464. if (value === "true" || value === "false")
  26465. return value === "true";
  26466. else
  26467. return isNaN(floatValue) ? value : floatValue;
  26468. }
  26469. var effectiveTarget = propertyPath.split(".");
  26470. var values = value.split(",");
  26471. // Get effective Target
  26472. for (var i = 0; i < effectiveTarget.length; i++) {
  26473. target = target[effectiveTarget[i]];
  26474. }
  26475. // Return appropriate value with its type
  26476. if (typeof (target) === "boolean")
  26477. return values[0] === "true";
  26478. if (typeof (target) === "string")
  26479. return values[0];
  26480. // Parameters with multiple values such as Vector3 etc.
  26481. var split = new Array();
  26482. for (var i = 0; i < values.length; i++)
  26483. split.push(parseFloat(values[i]));
  26484. if (target instanceof BABYLON.Vector3)
  26485. return BABYLON.Vector3.FromArray(split);
  26486. if (target instanceof BABYLON.Vector4)
  26487. return BABYLON.Vector4.FromArray(split);
  26488. if (target instanceof BABYLON.Color3)
  26489. return BABYLON.Color3.FromArray(split);
  26490. if (target instanceof BABYLON.Color4)
  26491. return BABYLON.Color4.FromArray(split);
  26492. return parseFloat(values[0]);
  26493. };
  26494. // traverse graph per trigger
  26495. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26496. if (combineArray === void 0) { combineArray = null; }
  26497. if (parsedAction.detached)
  26498. return;
  26499. var parameters = new Array();
  26500. var target = null;
  26501. var propertyPath = null;
  26502. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26503. // Parameters
  26504. if (parsedAction.type === 2)
  26505. parameters.push(actionManager);
  26506. else
  26507. parameters.push(trigger);
  26508. if (combine) {
  26509. var actions = new Array();
  26510. for (var j = 0; j < parsedAction.combine.length; j++) {
  26511. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26512. }
  26513. parameters.push(actions);
  26514. }
  26515. else {
  26516. for (var i = 0; i < parsedAction.properties.length; i++) {
  26517. var value = parsedAction.properties[i].value;
  26518. var name = parsedAction.properties[i].name;
  26519. var targetType = parsedAction.properties[i].targetType;
  26520. if (name === "target")
  26521. if (targetType !== null && targetType === "SceneProperties")
  26522. value = target = scene;
  26523. else
  26524. value = target = scene.getNodeByName(value);
  26525. else if (name === "parent")
  26526. value = scene.getNodeByName(value);
  26527. else if (name === "sound")
  26528. value = scene.getSoundByName(value);
  26529. else if (name !== "propertyPath") {
  26530. if (parsedAction.type === 2 && name === "operator")
  26531. value = BABYLON.ValueCondition[value];
  26532. else
  26533. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26534. }
  26535. else {
  26536. propertyPath = value;
  26537. }
  26538. parameters.push(value);
  26539. }
  26540. }
  26541. if (combineArray === null) {
  26542. parameters.push(condition);
  26543. }
  26544. else {
  26545. parameters.push(null);
  26546. }
  26547. // If interpolate value action
  26548. if (parsedAction.name === "InterpolateValueAction") {
  26549. var param = parameters[parameters.length - 2];
  26550. parameters[parameters.length - 1] = param;
  26551. parameters[parameters.length - 2] = condition;
  26552. }
  26553. // Action or condition(s) and not CombineAction
  26554. var newAction = instanciate(parsedAction.name, parameters);
  26555. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26556. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26557. if (action)
  26558. action.then(nothing);
  26559. else
  26560. actionManager.registerAction(nothing);
  26561. action = nothing;
  26562. }
  26563. if (combineArray === null) {
  26564. if (newAction instanceof BABYLON.Condition) {
  26565. condition = newAction;
  26566. newAction = action;
  26567. }
  26568. else {
  26569. condition = null;
  26570. if (action)
  26571. action.then(newAction);
  26572. else
  26573. actionManager.registerAction(newAction);
  26574. }
  26575. }
  26576. else {
  26577. combineArray.push(newAction);
  26578. }
  26579. for (var i = 0; i < parsedAction.children.length; i++)
  26580. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26581. };
  26582. // triggers
  26583. for (var i = 0; i < parsedActions.children.length; i++) {
  26584. var triggerParams;
  26585. var trigger = parsedActions.children[i];
  26586. if (trigger.properties.length > 0) {
  26587. var param = trigger.properties[0].value;
  26588. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26589. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26590. }
  26591. else
  26592. triggerParams = BABYLON.ActionManager[trigger.name];
  26593. for (var j = 0; j < trigger.children.length; j++) {
  26594. if (!trigger.detached)
  26595. traverse(trigger.children[j], triggerParams, null, null);
  26596. }
  26597. }
  26598. };
  26599. // Statics
  26600. ActionManager._NothingTrigger = 0;
  26601. ActionManager._OnPickTrigger = 1;
  26602. ActionManager._OnLeftPickTrigger = 2;
  26603. ActionManager._OnRightPickTrigger = 3;
  26604. ActionManager._OnCenterPickTrigger = 4;
  26605. ActionManager._OnPickDownTrigger = 5;
  26606. ActionManager._OnPickUpTrigger = 6;
  26607. ActionManager._OnLongPressTrigger = 7;
  26608. ActionManager._OnPointerOverTrigger = 8;
  26609. ActionManager._OnPointerOutTrigger = 9;
  26610. ActionManager._OnEveryFrameTrigger = 10;
  26611. ActionManager._OnIntersectionEnterTrigger = 11;
  26612. ActionManager._OnIntersectionExitTrigger = 12;
  26613. ActionManager._OnKeyDownTrigger = 13;
  26614. ActionManager._OnKeyUpTrigger = 14;
  26615. ActionManager._OnPickOutTrigger = 15;
  26616. ActionManager.DragMovementThreshold = 10; // in pixels
  26617. ActionManager.LongPressDelay = 500; // in milliseconds
  26618. return ActionManager;
  26619. })();
  26620. BABYLON.ActionManager = ActionManager;
  26621. })(BABYLON || (BABYLON = {}));
  26622. var BABYLON;
  26623. (function (BABYLON) {
  26624. var InterpolateValueAction = (function (_super) {
  26625. __extends(InterpolateValueAction, _super);
  26626. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26627. if (duration === void 0) { duration = 1000; }
  26628. _super.call(this, triggerOptions, condition);
  26629. this.propertyPath = propertyPath;
  26630. this.value = value;
  26631. this.duration = duration;
  26632. this.stopOtherAnimations = stopOtherAnimations;
  26633. this.onInterpolationDone = onInterpolationDone;
  26634. this._target = target;
  26635. }
  26636. InterpolateValueAction.prototype._prepare = function () {
  26637. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26638. this._property = this._getProperty(this.propertyPath);
  26639. };
  26640. InterpolateValueAction.prototype.execute = function () {
  26641. var scene = this._actionManager.getScene();
  26642. var keys = [
  26643. {
  26644. frame: 0,
  26645. value: this._target[this._property]
  26646. }, {
  26647. frame: 100,
  26648. value: this.value
  26649. }
  26650. ];
  26651. var dataType;
  26652. if (typeof this.value === "number") {
  26653. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26654. }
  26655. else if (this.value instanceof BABYLON.Color3) {
  26656. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26657. }
  26658. else if (this.value instanceof BABYLON.Vector3) {
  26659. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26660. }
  26661. else if (this.value instanceof BABYLON.Matrix) {
  26662. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26663. }
  26664. else if (this.value instanceof BABYLON.Quaternion) {
  26665. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26666. }
  26667. else {
  26668. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26669. return;
  26670. }
  26671. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26672. animation.setKeys(keys);
  26673. if (this.stopOtherAnimations) {
  26674. scene.stopAnimation(this._target);
  26675. }
  26676. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26677. };
  26678. return InterpolateValueAction;
  26679. })(BABYLON.Action);
  26680. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26681. })(BABYLON || (BABYLON = {}));
  26682. var BABYLON;
  26683. (function (BABYLON) {
  26684. var SwitchBooleanAction = (function (_super) {
  26685. __extends(SwitchBooleanAction, _super);
  26686. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26687. _super.call(this, triggerOptions, condition);
  26688. this.propertyPath = propertyPath;
  26689. this._target = target;
  26690. }
  26691. SwitchBooleanAction.prototype._prepare = function () {
  26692. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26693. this._property = this._getProperty(this.propertyPath);
  26694. };
  26695. SwitchBooleanAction.prototype.execute = function () {
  26696. this._target[this._property] = !this._target[this._property];
  26697. };
  26698. return SwitchBooleanAction;
  26699. })(BABYLON.Action);
  26700. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26701. var SetStateAction = (function (_super) {
  26702. __extends(SetStateAction, _super);
  26703. function SetStateAction(triggerOptions, target, value, condition) {
  26704. _super.call(this, triggerOptions, condition);
  26705. this.value = value;
  26706. this._target = target;
  26707. }
  26708. SetStateAction.prototype.execute = function () {
  26709. this._target.state = this.value;
  26710. };
  26711. return SetStateAction;
  26712. })(BABYLON.Action);
  26713. BABYLON.SetStateAction = SetStateAction;
  26714. var SetValueAction = (function (_super) {
  26715. __extends(SetValueAction, _super);
  26716. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26717. _super.call(this, triggerOptions, condition);
  26718. this.propertyPath = propertyPath;
  26719. this.value = value;
  26720. this._target = target;
  26721. }
  26722. SetValueAction.prototype._prepare = function () {
  26723. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26724. this._property = this._getProperty(this.propertyPath);
  26725. };
  26726. SetValueAction.prototype.execute = function () {
  26727. this._target[this._property] = this.value;
  26728. };
  26729. return SetValueAction;
  26730. })(BABYLON.Action);
  26731. BABYLON.SetValueAction = SetValueAction;
  26732. var IncrementValueAction = (function (_super) {
  26733. __extends(IncrementValueAction, _super);
  26734. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26735. _super.call(this, triggerOptions, condition);
  26736. this.propertyPath = propertyPath;
  26737. this.value = value;
  26738. this._target = target;
  26739. }
  26740. IncrementValueAction.prototype._prepare = function () {
  26741. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26742. this._property = this._getProperty(this.propertyPath);
  26743. if (typeof this._target[this._property] !== "number") {
  26744. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26745. }
  26746. };
  26747. IncrementValueAction.prototype.execute = function () {
  26748. this._target[this._property] += this.value;
  26749. };
  26750. return IncrementValueAction;
  26751. })(BABYLON.Action);
  26752. BABYLON.IncrementValueAction = IncrementValueAction;
  26753. var PlayAnimationAction = (function (_super) {
  26754. __extends(PlayAnimationAction, _super);
  26755. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26756. _super.call(this, triggerOptions, condition);
  26757. this.from = from;
  26758. this.to = to;
  26759. this.loop = loop;
  26760. this._target = target;
  26761. }
  26762. PlayAnimationAction.prototype._prepare = function () {
  26763. };
  26764. PlayAnimationAction.prototype.execute = function () {
  26765. var scene = this._actionManager.getScene();
  26766. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26767. };
  26768. return PlayAnimationAction;
  26769. })(BABYLON.Action);
  26770. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26771. var StopAnimationAction = (function (_super) {
  26772. __extends(StopAnimationAction, _super);
  26773. function StopAnimationAction(triggerOptions, target, condition) {
  26774. _super.call(this, triggerOptions, condition);
  26775. this._target = target;
  26776. }
  26777. StopAnimationAction.prototype._prepare = function () {
  26778. };
  26779. StopAnimationAction.prototype.execute = function () {
  26780. var scene = this._actionManager.getScene();
  26781. scene.stopAnimation(this._target);
  26782. };
  26783. return StopAnimationAction;
  26784. })(BABYLON.Action);
  26785. BABYLON.StopAnimationAction = StopAnimationAction;
  26786. var DoNothingAction = (function (_super) {
  26787. __extends(DoNothingAction, _super);
  26788. function DoNothingAction(triggerOptions, condition) {
  26789. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26790. _super.call(this, triggerOptions, condition);
  26791. }
  26792. DoNothingAction.prototype.execute = function () {
  26793. };
  26794. return DoNothingAction;
  26795. })(BABYLON.Action);
  26796. BABYLON.DoNothingAction = DoNothingAction;
  26797. var CombineAction = (function (_super) {
  26798. __extends(CombineAction, _super);
  26799. function CombineAction(triggerOptions, children, condition) {
  26800. _super.call(this, triggerOptions, condition);
  26801. this.children = children;
  26802. }
  26803. CombineAction.prototype._prepare = function () {
  26804. for (var index = 0; index < this.children.length; index++) {
  26805. this.children[index]._actionManager = this._actionManager;
  26806. this.children[index]._prepare();
  26807. }
  26808. };
  26809. CombineAction.prototype.execute = function (evt) {
  26810. for (var index = 0; index < this.children.length; index++) {
  26811. this.children[index].execute(evt);
  26812. }
  26813. };
  26814. return CombineAction;
  26815. })(BABYLON.Action);
  26816. BABYLON.CombineAction = CombineAction;
  26817. var ExecuteCodeAction = (function (_super) {
  26818. __extends(ExecuteCodeAction, _super);
  26819. function ExecuteCodeAction(triggerOptions, func, condition) {
  26820. _super.call(this, triggerOptions, condition);
  26821. this.func = func;
  26822. }
  26823. ExecuteCodeAction.prototype.execute = function (evt) {
  26824. this.func(evt);
  26825. };
  26826. return ExecuteCodeAction;
  26827. })(BABYLON.Action);
  26828. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26829. var SetParentAction = (function (_super) {
  26830. __extends(SetParentAction, _super);
  26831. function SetParentAction(triggerOptions, target, parent, condition) {
  26832. _super.call(this, triggerOptions, condition);
  26833. this._target = target;
  26834. this._parent = parent;
  26835. }
  26836. SetParentAction.prototype._prepare = function () {
  26837. };
  26838. SetParentAction.prototype.execute = function () {
  26839. if (this._target.parent === this._parent) {
  26840. return;
  26841. }
  26842. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26843. invertParentWorldMatrix.invert();
  26844. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26845. this._target.parent = this._parent;
  26846. };
  26847. return SetParentAction;
  26848. })(BABYLON.Action);
  26849. BABYLON.SetParentAction = SetParentAction;
  26850. var PlaySoundAction = (function (_super) {
  26851. __extends(PlaySoundAction, _super);
  26852. function PlaySoundAction(triggerOptions, sound, condition) {
  26853. _super.call(this, triggerOptions, condition);
  26854. this._sound = sound;
  26855. }
  26856. PlaySoundAction.prototype._prepare = function () {
  26857. };
  26858. PlaySoundAction.prototype.execute = function () {
  26859. if (this._sound !== undefined)
  26860. this._sound.play();
  26861. };
  26862. return PlaySoundAction;
  26863. })(BABYLON.Action);
  26864. BABYLON.PlaySoundAction = PlaySoundAction;
  26865. var StopSoundAction = (function (_super) {
  26866. __extends(StopSoundAction, _super);
  26867. function StopSoundAction(triggerOptions, sound, condition) {
  26868. _super.call(this, triggerOptions, condition);
  26869. this._sound = sound;
  26870. }
  26871. StopSoundAction.prototype._prepare = function () {
  26872. };
  26873. StopSoundAction.prototype.execute = function () {
  26874. if (this._sound !== undefined)
  26875. this._sound.stop();
  26876. };
  26877. return StopSoundAction;
  26878. })(BABYLON.Action);
  26879. BABYLON.StopSoundAction = StopSoundAction;
  26880. })(BABYLON || (BABYLON = {}));
  26881. var BABYLON;
  26882. (function (BABYLON) {
  26883. var Geometry = (function () {
  26884. function Geometry(id, scene, vertexData, updatable, mesh) {
  26885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26886. this._totalVertices = 0;
  26887. this._isDisposed = false;
  26888. this.id = id;
  26889. this._engine = scene.getEngine();
  26890. this._meshes = [];
  26891. this._scene = scene;
  26892. //Init vertex buffer cache
  26893. this._vertexBuffers = {};
  26894. this._indices = [];
  26895. // vertexData
  26896. if (vertexData) {
  26897. this.setAllVerticesData(vertexData, updatable);
  26898. }
  26899. else {
  26900. this._totalVertices = 0;
  26901. this._indices = [];
  26902. }
  26903. // applyToMesh
  26904. if (mesh) {
  26905. this.applyToMesh(mesh);
  26906. mesh.computeWorldMatrix(true);
  26907. }
  26908. }
  26909. Object.defineProperty(Geometry.prototype, "extend", {
  26910. get: function () {
  26911. return this._extend;
  26912. },
  26913. enumerable: true,
  26914. configurable: true
  26915. });
  26916. Geometry.prototype.getScene = function () {
  26917. return this._scene;
  26918. };
  26919. Geometry.prototype.getEngine = function () {
  26920. return this._engine;
  26921. };
  26922. Geometry.prototype.isReady = function () {
  26923. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26924. };
  26925. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26926. vertexData.applyToGeometry(this, updatable);
  26927. this.notifyUpdate();
  26928. };
  26929. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26930. if (this._vertexBuffers[kind]) {
  26931. this._vertexBuffers[kind].dispose();
  26932. }
  26933. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26934. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26935. stride = this._vertexBuffers[kind].getStrideSize();
  26936. this._totalVertices = data.length / stride;
  26937. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26938. var meshes = this._meshes;
  26939. var numOfMeshes = meshes.length;
  26940. for (var index = 0; index < numOfMeshes; index++) {
  26941. var mesh = meshes[index];
  26942. mesh._resetPointsArrayCache();
  26943. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26944. mesh._createGlobalSubMesh();
  26945. mesh.computeWorldMatrix(true);
  26946. }
  26947. }
  26948. this.notifyUpdate(kind);
  26949. };
  26950. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26951. var vertexBuffer = this.getVertexBuffer(kind);
  26952. if (!vertexBuffer) {
  26953. return;
  26954. }
  26955. vertexBuffer.updateDirectly(data, offset);
  26956. this.notifyUpdate(kind);
  26957. };
  26958. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26959. var vertexBuffer = this.getVertexBuffer(kind);
  26960. if (!vertexBuffer) {
  26961. return;
  26962. }
  26963. vertexBuffer.update(data);
  26964. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26965. var stride = vertexBuffer.getStrideSize();
  26966. this._totalVertices = data.length / stride;
  26967. if (updateExtends) {
  26968. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26969. }
  26970. var meshes = this._meshes;
  26971. var numOfMeshes = meshes.length;
  26972. for (var index = 0; index < numOfMeshes; index++) {
  26973. var mesh = meshes[index];
  26974. mesh._resetPointsArrayCache();
  26975. if (updateExtends) {
  26976. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26977. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26978. var subMesh = mesh.subMeshes[subIndex];
  26979. subMesh.refreshBoundingInfo();
  26980. }
  26981. }
  26982. }
  26983. }
  26984. this.notifyUpdate(kind);
  26985. };
  26986. Geometry.prototype.getTotalVertices = function () {
  26987. if (!this.isReady()) {
  26988. return 0;
  26989. }
  26990. return this._totalVertices;
  26991. };
  26992. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26993. var vertexBuffer = this.getVertexBuffer(kind);
  26994. if (!vertexBuffer) {
  26995. return null;
  26996. }
  26997. var orig = vertexBuffer.getData();
  26998. if (!copyWhenShared || this._meshes.length === 1) {
  26999. return orig;
  27000. }
  27001. else {
  27002. var len = orig.length;
  27003. var copy = [];
  27004. for (var i = 0; i < len; i++) {
  27005. copy.push(orig[i]);
  27006. }
  27007. return copy;
  27008. }
  27009. };
  27010. Geometry.prototype.getVertexBuffer = function (kind) {
  27011. if (!this.isReady()) {
  27012. return null;
  27013. }
  27014. return this._vertexBuffers[kind];
  27015. };
  27016. Geometry.prototype.getVertexBuffers = function () {
  27017. if (!this.isReady()) {
  27018. return null;
  27019. }
  27020. return this._vertexBuffers;
  27021. };
  27022. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27023. if (!this._vertexBuffers) {
  27024. if (this._delayInfo) {
  27025. return this._delayInfo.indexOf(kind) !== -1;
  27026. }
  27027. return false;
  27028. }
  27029. return this._vertexBuffers[kind] !== undefined;
  27030. };
  27031. Geometry.prototype.getVerticesDataKinds = function () {
  27032. var result = [];
  27033. var kind;
  27034. if (!this._vertexBuffers && this._delayInfo) {
  27035. for (kind in this._delayInfo) {
  27036. result.push(kind);
  27037. }
  27038. }
  27039. else {
  27040. for (kind in this._vertexBuffers) {
  27041. result.push(kind);
  27042. }
  27043. }
  27044. return result;
  27045. };
  27046. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27047. if (this._indexBuffer) {
  27048. this._engine._releaseBuffer(this._indexBuffer);
  27049. }
  27050. this._indices = indices;
  27051. if (this._meshes.length !== 0 && this._indices) {
  27052. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27053. }
  27054. if (totalVertices !== undefined) {
  27055. this._totalVertices = totalVertices;
  27056. }
  27057. var meshes = this._meshes;
  27058. var numOfMeshes = meshes.length;
  27059. for (var index = 0; index < numOfMeshes; index++) {
  27060. meshes[index]._createGlobalSubMesh();
  27061. }
  27062. this.notifyUpdate();
  27063. };
  27064. Geometry.prototype.getTotalIndices = function () {
  27065. if (!this.isReady()) {
  27066. return 0;
  27067. }
  27068. return this._indices.length;
  27069. };
  27070. Geometry.prototype.getIndices = function (copyWhenShared) {
  27071. if (!this.isReady()) {
  27072. return null;
  27073. }
  27074. var orig = this._indices;
  27075. if (!copyWhenShared || this._meshes.length === 1) {
  27076. return orig;
  27077. }
  27078. else {
  27079. var len = orig.length;
  27080. var copy = [];
  27081. for (var i = 0; i < len; i++) {
  27082. copy.push(orig[i]);
  27083. }
  27084. return copy;
  27085. }
  27086. };
  27087. Geometry.prototype.getIndexBuffer = function () {
  27088. if (!this.isReady()) {
  27089. return null;
  27090. }
  27091. return this._indexBuffer;
  27092. };
  27093. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27094. var meshes = this._meshes;
  27095. var index = meshes.indexOf(mesh);
  27096. if (index === -1) {
  27097. return;
  27098. }
  27099. for (var kind in this._vertexBuffers) {
  27100. this._vertexBuffers[kind].dispose();
  27101. }
  27102. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27103. this._indexBuffer = null;
  27104. }
  27105. meshes.splice(index, 1);
  27106. mesh._geometry = null;
  27107. if (meshes.length === 0 && shouldDispose) {
  27108. this.dispose();
  27109. }
  27110. };
  27111. Geometry.prototype.applyToMesh = function (mesh) {
  27112. if (mesh._geometry === this) {
  27113. return;
  27114. }
  27115. var previousGeometry = mesh._geometry;
  27116. if (previousGeometry) {
  27117. previousGeometry.releaseForMesh(mesh);
  27118. }
  27119. var meshes = this._meshes;
  27120. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27121. mesh._geometry = this;
  27122. this._scene.pushGeometry(this);
  27123. meshes.push(mesh);
  27124. if (this.isReady()) {
  27125. this._applyToMesh(mesh);
  27126. }
  27127. else {
  27128. mesh._boundingInfo = this._boundingInfo;
  27129. }
  27130. };
  27131. Geometry.prototype._applyToMesh = function (mesh) {
  27132. var numOfMeshes = this._meshes.length;
  27133. // vertexBuffers
  27134. for (var kind in this._vertexBuffers) {
  27135. if (numOfMeshes === 1) {
  27136. this._vertexBuffers[kind].create();
  27137. }
  27138. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27139. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27140. mesh._resetPointsArrayCache();
  27141. if (!this._extend) {
  27142. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27143. }
  27144. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27145. mesh._createGlobalSubMesh();
  27146. //bounding info was just created again, world matrix should be applied again.
  27147. mesh._updateBoundingInfo();
  27148. }
  27149. }
  27150. // indexBuffer
  27151. if (numOfMeshes === 1 && this._indices) {
  27152. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27153. }
  27154. if (this._indexBuffer) {
  27155. this._indexBuffer.references = numOfMeshes;
  27156. }
  27157. };
  27158. Geometry.prototype.notifyUpdate = function (kind) {
  27159. if (this.onGeometryUpdated) {
  27160. this.onGeometryUpdated(this, kind);
  27161. }
  27162. };
  27163. Geometry.prototype.load = function (scene, onLoaded) {
  27164. var _this = this;
  27165. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27166. return;
  27167. }
  27168. if (this.isReady()) {
  27169. if (onLoaded) {
  27170. onLoaded();
  27171. }
  27172. return;
  27173. }
  27174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27175. scene._addPendingData(this);
  27176. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27177. _this._delayLoadingFunction(JSON.parse(data), _this);
  27178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27179. _this._delayInfo = [];
  27180. scene._removePendingData(_this);
  27181. var meshes = _this._meshes;
  27182. var numOfMeshes = meshes.length;
  27183. for (var index = 0; index < numOfMeshes; index++) {
  27184. _this._applyToMesh(meshes[index]);
  27185. }
  27186. if (onLoaded) {
  27187. onLoaded();
  27188. }
  27189. }, function () { }, scene.database);
  27190. };
  27191. Geometry.prototype.isDisposed = function () {
  27192. return this._isDisposed;
  27193. };
  27194. Geometry.prototype.dispose = function () {
  27195. var meshes = this._meshes;
  27196. var numOfMeshes = meshes.length;
  27197. var index;
  27198. for (index = 0; index < numOfMeshes; index++) {
  27199. this.releaseForMesh(meshes[index]);
  27200. }
  27201. this._meshes = [];
  27202. for (var kind in this._vertexBuffers) {
  27203. this._vertexBuffers[kind].dispose();
  27204. }
  27205. this._vertexBuffers = [];
  27206. this._totalVertices = 0;
  27207. if (this._indexBuffer) {
  27208. this._engine._releaseBuffer(this._indexBuffer);
  27209. }
  27210. this._indexBuffer = null;
  27211. this._indices = [];
  27212. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27213. this.delayLoadingFile = null;
  27214. this._delayLoadingFunction = null;
  27215. this._delayInfo = [];
  27216. this._boundingInfo = null;
  27217. this._scene.removeGeometry(this);
  27218. this._isDisposed = true;
  27219. };
  27220. Geometry.prototype.copy = function (id) {
  27221. var vertexData = new BABYLON.VertexData();
  27222. vertexData.indices = [];
  27223. var indices = this.getIndices();
  27224. for (var index = 0; index < indices.length; index++) {
  27225. vertexData.indices.push(indices[index]);
  27226. }
  27227. var updatable = false;
  27228. var stopChecking = false;
  27229. var kind;
  27230. for (kind in this._vertexBuffers) {
  27231. // using slice() to make a copy of the array and not just reference it
  27232. var data = this.getVerticesData(kind);
  27233. if (data instanceof Float32Array) {
  27234. vertexData.set(new Float32Array(data), kind);
  27235. }
  27236. else {
  27237. vertexData.set(data.slice(0), kind);
  27238. }
  27239. if (!stopChecking) {
  27240. updatable = this.getVertexBuffer(kind).isUpdatable();
  27241. stopChecking = !updatable;
  27242. }
  27243. }
  27244. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27245. geometry.delayLoadState = this.delayLoadState;
  27246. geometry.delayLoadingFile = this.delayLoadingFile;
  27247. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27248. for (kind in this._delayInfo) {
  27249. geometry._delayInfo = geometry._delayInfo || [];
  27250. geometry._delayInfo.push(kind);
  27251. }
  27252. // Bounding info
  27253. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27254. return geometry;
  27255. };
  27256. Geometry.prototype.serialize = function () {
  27257. var serializationObject = {};
  27258. serializationObject.id = this.id;
  27259. if (BABYLON.Tags.HasTags(this)) {
  27260. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27261. }
  27262. return serializationObject;
  27263. };
  27264. Geometry.prototype.serializeVerticeData = function () {
  27265. var serializationObject = this.serialize();
  27266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27267. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27268. }
  27269. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27270. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27271. }
  27272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27273. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27274. }
  27275. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27276. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27277. }
  27278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27279. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27280. }
  27281. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27282. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27283. }
  27284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27285. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27286. }
  27287. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27288. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27289. }
  27290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27291. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27292. }
  27293. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27294. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27295. serializationObject.matricesIndices._isExpanded = true;
  27296. }
  27297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27298. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27299. }
  27300. serializationObject.indices = this.getIndices();
  27301. return serializationObject;
  27302. };
  27303. // Statics
  27304. Geometry.ExtractFromMesh = function (mesh, id) {
  27305. var geometry = mesh._geometry;
  27306. if (!geometry) {
  27307. return null;
  27308. }
  27309. return geometry.copy(id);
  27310. };
  27311. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27312. // be aware Math.random() could cause collisions
  27313. Geometry.RandomId = function () {
  27314. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27315. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27316. return v.toString(16);
  27317. });
  27318. };
  27319. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27320. var scene = mesh.getScene();
  27321. // Geometry
  27322. var geometryId = parsedGeometry.geometryId;
  27323. if (geometryId) {
  27324. var geometry = scene.getGeometryByID(geometryId);
  27325. if (geometry) {
  27326. geometry.applyToMesh(mesh);
  27327. }
  27328. }
  27329. else if (parsedGeometry instanceof ArrayBuffer) {
  27330. var binaryInfo = mesh._binaryInfo;
  27331. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27332. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27333. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27334. }
  27335. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27336. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27337. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27338. }
  27339. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27340. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27341. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27342. }
  27343. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27344. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27345. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27346. }
  27347. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27348. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27349. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27350. }
  27351. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27352. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27353. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27354. }
  27355. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27356. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27357. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27358. }
  27359. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27360. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27361. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27362. }
  27363. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27364. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27365. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27366. }
  27367. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27368. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27369. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27370. }
  27371. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27372. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27373. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27374. }
  27375. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27376. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27377. mesh.setIndices(indicesData);
  27378. }
  27379. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27380. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27381. mesh.subMeshes = [];
  27382. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27383. var materialIndex = subMeshesData[(i * 5) + 0];
  27384. var verticesStart = subMeshesData[(i * 5) + 1];
  27385. var verticesCount = subMeshesData[(i * 5) + 2];
  27386. var indexStart = subMeshesData[(i * 5) + 3];
  27387. var indexCount = subMeshesData[(i * 5) + 4];
  27388. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27389. }
  27390. }
  27391. }
  27392. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27393. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27394. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27395. if (parsedGeometry.uvs) {
  27396. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27397. }
  27398. if (parsedGeometry.uvs2) {
  27399. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27400. }
  27401. if (parsedGeometry.uvs3) {
  27402. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27403. }
  27404. if (parsedGeometry.uvs4) {
  27405. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27406. }
  27407. if (parsedGeometry.uvs5) {
  27408. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27409. }
  27410. if (parsedGeometry.uvs6) {
  27411. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27412. }
  27413. if (parsedGeometry.colors) {
  27414. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27415. }
  27416. if (parsedGeometry.matricesIndices) {
  27417. if (!parsedGeometry.matricesIndices._isExpanded) {
  27418. var floatIndices = [];
  27419. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27420. var matricesIndex = parsedGeometry.matricesIndices[i];
  27421. floatIndices.push(matricesIndex & 0x000000FF);
  27422. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27423. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27424. floatIndices.push(matricesIndex >> 24);
  27425. }
  27426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27427. }
  27428. else {
  27429. delete parsedGeometry.matricesIndices._isExpanded;
  27430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27431. }
  27432. }
  27433. if (parsedGeometry.matricesIndicesExtra) {
  27434. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27435. var floatIndices = [];
  27436. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27437. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27438. floatIndices.push(matricesIndex & 0x000000FF);
  27439. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27440. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27441. floatIndices.push(matricesIndex >> 24);
  27442. }
  27443. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27444. }
  27445. else {
  27446. delete parsedGeometry.matricesIndices._isExpanded;
  27447. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27448. }
  27449. }
  27450. if (parsedGeometry.matricesWeights) {
  27451. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27452. }
  27453. if (parsedGeometry.matricesWeightsExtra) {
  27454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27455. }
  27456. mesh.setIndices(parsedGeometry.indices);
  27457. }
  27458. // SubMeshes
  27459. if (parsedGeometry.subMeshes) {
  27460. mesh.subMeshes = [];
  27461. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27462. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27463. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27464. }
  27465. }
  27466. // Flat shading
  27467. if (mesh._shouldGenerateFlatShading) {
  27468. mesh.convertToFlatShadedMesh();
  27469. delete mesh._shouldGenerateFlatShading;
  27470. }
  27471. // Update
  27472. mesh.computeWorldMatrix(true);
  27473. // Octree
  27474. if (scene['_selectionOctree']) {
  27475. scene['_selectionOctree'].addMesh(mesh);
  27476. }
  27477. };
  27478. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27479. if (scene.getGeometryByID(parsedVertexData.id)) {
  27480. return null; // null since geometry could be something else than a box...
  27481. }
  27482. var geometry = new Geometry(parsedVertexData.id, scene);
  27483. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27484. if (parsedVertexData.delayLoadingFile) {
  27485. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27486. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27487. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27488. geometry._delayInfo = [];
  27489. if (parsedVertexData.hasUVs) {
  27490. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27491. }
  27492. if (parsedVertexData.hasUVs2) {
  27493. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27494. }
  27495. if (parsedVertexData.hasUVs3) {
  27496. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27497. }
  27498. if (parsedVertexData.hasUVs4) {
  27499. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27500. }
  27501. if (parsedVertexData.hasUVs5) {
  27502. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27503. }
  27504. if (parsedVertexData.hasUVs6) {
  27505. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27506. }
  27507. if (parsedVertexData.hasColors) {
  27508. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27509. }
  27510. if (parsedVertexData.hasMatricesIndices) {
  27511. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27512. }
  27513. if (parsedVertexData.hasMatricesWeights) {
  27514. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27515. }
  27516. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27517. }
  27518. else {
  27519. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27520. }
  27521. scene.pushGeometry(geometry, true);
  27522. return geometry;
  27523. };
  27524. return Geometry;
  27525. })();
  27526. BABYLON.Geometry = Geometry;
  27527. /////// Primitives //////////////////////////////////////////////
  27528. var Geometry;
  27529. (function (Geometry) {
  27530. var Primitives;
  27531. (function (Primitives) {
  27532. /// Abstract class
  27533. var _Primitive = (function (_super) {
  27534. __extends(_Primitive, _super);
  27535. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27536. this._beingRegenerated = true;
  27537. this._canBeRegenerated = canBeRegenerated;
  27538. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27539. this._beingRegenerated = false;
  27540. }
  27541. _Primitive.prototype.canBeRegenerated = function () {
  27542. return this._canBeRegenerated;
  27543. };
  27544. _Primitive.prototype.regenerate = function () {
  27545. if (!this._canBeRegenerated) {
  27546. return;
  27547. }
  27548. this._beingRegenerated = true;
  27549. this.setAllVerticesData(this._regenerateVertexData(), false);
  27550. this._beingRegenerated = false;
  27551. };
  27552. _Primitive.prototype.asNewGeometry = function (id) {
  27553. return _super.prototype.copy.call(this, id);
  27554. };
  27555. // overrides
  27556. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27557. if (!this._beingRegenerated) {
  27558. return;
  27559. }
  27560. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27561. };
  27562. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27563. if (!this._beingRegenerated) {
  27564. return;
  27565. }
  27566. _super.prototype.setVerticesData.call(this, kind, data, false);
  27567. };
  27568. // to override
  27569. // protected
  27570. _Primitive.prototype._regenerateVertexData = function () {
  27571. throw new Error("Abstract method");
  27572. };
  27573. _Primitive.prototype.copy = function (id) {
  27574. throw new Error("Must be overriden in sub-classes.");
  27575. };
  27576. _Primitive.prototype.serialize = function () {
  27577. var serializationObject = _super.prototype.serialize.call(this);
  27578. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27579. return serializationObject;
  27580. };
  27581. return _Primitive;
  27582. })(Geometry);
  27583. Primitives._Primitive = _Primitive;
  27584. var Ribbon = (function (_super) {
  27585. __extends(Ribbon, _super);
  27586. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27587. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27588. this.pathArray = pathArray;
  27589. this.closeArray = closeArray;
  27590. this.closePath = closePath;
  27591. this.offset = offset;
  27592. this.side = side;
  27593. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27594. }
  27595. Ribbon.prototype._regenerateVertexData = function () {
  27596. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27597. };
  27598. Ribbon.prototype.copy = function (id) {
  27599. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27600. };
  27601. return Ribbon;
  27602. })(_Primitive);
  27603. Primitives.Ribbon = Ribbon;
  27604. var Box = (function (_super) {
  27605. __extends(Box, _super);
  27606. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27607. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27608. this.size = size;
  27609. this.side = side;
  27610. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27611. }
  27612. Box.prototype._regenerateVertexData = function () {
  27613. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27614. };
  27615. Box.prototype.copy = function (id) {
  27616. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27617. };
  27618. Box.prototype.serialize = function () {
  27619. var serializationObject = _super.prototype.serialize.call(this);
  27620. serializationObject.size = this.size;
  27621. return serializationObject;
  27622. };
  27623. Box.Parse = function (parsedBox, scene) {
  27624. if (scene.getGeometryByID(parsedBox.id)) {
  27625. return null; // null since geometry could be something else than a box...
  27626. }
  27627. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27628. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27629. scene.pushGeometry(box, true);
  27630. return box;
  27631. };
  27632. return Box;
  27633. })(_Primitive);
  27634. Primitives.Box = Box;
  27635. var Sphere = (function (_super) {
  27636. __extends(Sphere, _super);
  27637. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27638. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27639. this.segments = segments;
  27640. this.diameter = diameter;
  27641. this.side = side;
  27642. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27643. }
  27644. Sphere.prototype._regenerateVertexData = function () {
  27645. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27646. };
  27647. Sphere.prototype.copy = function (id) {
  27648. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27649. };
  27650. Sphere.prototype.serialize = function () {
  27651. var serializationObject = _super.prototype.serialize.call(this);
  27652. serializationObject.segments = this.segments;
  27653. serializationObject.diameter = this.diameter;
  27654. return serializationObject;
  27655. };
  27656. Sphere.Parse = function (parsedSphere, scene) {
  27657. if (scene.getGeometryByID(parsedSphere.id)) {
  27658. return null; // null since geometry could be something else than a sphere...
  27659. }
  27660. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27661. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27662. scene.pushGeometry(sphere, true);
  27663. return sphere;
  27664. };
  27665. return Sphere;
  27666. })(_Primitive);
  27667. Primitives.Sphere = Sphere;
  27668. var Disc = (function (_super) {
  27669. __extends(Disc, _super);
  27670. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27672. this.radius = radius;
  27673. this.tessellation = tessellation;
  27674. this.side = side;
  27675. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27676. }
  27677. Disc.prototype._regenerateVertexData = function () {
  27678. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27679. };
  27680. Disc.prototype.copy = function (id) {
  27681. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27682. };
  27683. return Disc;
  27684. })(_Primitive);
  27685. Primitives.Disc = Disc;
  27686. var Cylinder = (function (_super) {
  27687. __extends(Cylinder, _super);
  27688. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27689. if (subdivisions === void 0) { subdivisions = 1; }
  27690. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27691. this.height = height;
  27692. this.diameterTop = diameterTop;
  27693. this.diameterBottom = diameterBottom;
  27694. this.tessellation = tessellation;
  27695. this.subdivisions = subdivisions;
  27696. this.side = side;
  27697. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27698. }
  27699. Cylinder.prototype._regenerateVertexData = function () {
  27700. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27701. };
  27702. Cylinder.prototype.copy = function (id) {
  27703. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27704. };
  27705. Cylinder.prototype.serialize = function () {
  27706. var serializationObject = _super.prototype.serialize.call(this);
  27707. serializationObject.height = this.height;
  27708. serializationObject.diameterTop = this.diameterTop;
  27709. serializationObject.diameterBottom = this.diameterBottom;
  27710. serializationObject.tessellation = this.tessellation;
  27711. return serializationObject;
  27712. };
  27713. Cylinder.Parse = function (parsedCylinder, scene) {
  27714. if (scene.getGeometryByID(parsedCylinder.id)) {
  27715. return null; // null since geometry could be something else than a cylinder...
  27716. }
  27717. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27718. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27719. scene.pushGeometry(cylinder, true);
  27720. return cylinder;
  27721. };
  27722. return Cylinder;
  27723. })(_Primitive);
  27724. Primitives.Cylinder = Cylinder;
  27725. var Torus = (function (_super) {
  27726. __extends(Torus, _super);
  27727. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27729. this.diameter = diameter;
  27730. this.thickness = thickness;
  27731. this.tessellation = tessellation;
  27732. this.side = side;
  27733. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27734. }
  27735. Torus.prototype._regenerateVertexData = function () {
  27736. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27737. };
  27738. Torus.prototype.copy = function (id) {
  27739. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27740. };
  27741. Torus.prototype.serialize = function () {
  27742. var serializationObject = _super.prototype.serialize.call(this);
  27743. serializationObject.diameter = this.diameter;
  27744. serializationObject.thickness = this.thickness;
  27745. serializationObject.tessellation = this.tessellation;
  27746. return serializationObject;
  27747. };
  27748. Torus.Parse = function (parsedTorus, scene) {
  27749. if (scene.getGeometryByID(parsedTorus.id)) {
  27750. return null; // null since geometry could be something else than a torus...
  27751. }
  27752. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27753. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27754. scene.pushGeometry(torus, true);
  27755. return torus;
  27756. };
  27757. return Torus;
  27758. })(_Primitive);
  27759. Primitives.Torus = Torus;
  27760. var Ground = (function (_super) {
  27761. __extends(Ground, _super);
  27762. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27763. this.width = width;
  27764. this.height = height;
  27765. this.subdivisions = subdivisions;
  27766. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27767. }
  27768. Ground.prototype._regenerateVertexData = function () {
  27769. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27770. };
  27771. Ground.prototype.copy = function (id) {
  27772. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27773. };
  27774. Ground.prototype.serialize = function () {
  27775. var serializationObject = _super.prototype.serialize.call(this);
  27776. serializationObject.width = this.width;
  27777. serializationObject.height = this.height;
  27778. serializationObject.subdivisions = this.subdivisions;
  27779. return serializationObject;
  27780. };
  27781. Ground.Parse = function (parsedGround, scene) {
  27782. if (scene.getGeometryByID(parsedGround.id)) {
  27783. return null; // null since geometry could be something else than a ground...
  27784. }
  27785. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27786. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27787. scene.pushGeometry(ground, true);
  27788. return ground;
  27789. };
  27790. return Ground;
  27791. })(_Primitive);
  27792. Primitives.Ground = Ground;
  27793. var TiledGround = (function (_super) {
  27794. __extends(TiledGround, _super);
  27795. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27796. this.xmin = xmin;
  27797. this.zmin = zmin;
  27798. this.xmax = xmax;
  27799. this.zmax = zmax;
  27800. this.subdivisions = subdivisions;
  27801. this.precision = precision;
  27802. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27803. }
  27804. TiledGround.prototype._regenerateVertexData = function () {
  27805. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27806. };
  27807. TiledGround.prototype.copy = function (id) {
  27808. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27809. };
  27810. return TiledGround;
  27811. })(_Primitive);
  27812. Primitives.TiledGround = TiledGround;
  27813. var Plane = (function (_super) {
  27814. __extends(Plane, _super);
  27815. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27816. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27817. this.size = size;
  27818. this.side = side;
  27819. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27820. }
  27821. Plane.prototype._regenerateVertexData = function () {
  27822. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27823. };
  27824. Plane.prototype.copy = function (id) {
  27825. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27826. };
  27827. Plane.prototype.serialize = function () {
  27828. var serializationObject = _super.prototype.serialize.call(this);
  27829. serializationObject.size = this.size;
  27830. return serializationObject;
  27831. };
  27832. Plane.Parse = function (parsedPlane, scene) {
  27833. if (scene.getGeometryByID(parsedPlane.id)) {
  27834. return null; // null since geometry could be something else than a ground...
  27835. }
  27836. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27837. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27838. scene.pushGeometry(plane, true);
  27839. return plane;
  27840. };
  27841. return Plane;
  27842. })(_Primitive);
  27843. Primitives.Plane = Plane;
  27844. var TorusKnot = (function (_super) {
  27845. __extends(TorusKnot, _super);
  27846. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27848. this.radius = radius;
  27849. this.tube = tube;
  27850. this.radialSegments = radialSegments;
  27851. this.tubularSegments = tubularSegments;
  27852. this.p = p;
  27853. this.q = q;
  27854. this.side = side;
  27855. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27856. }
  27857. TorusKnot.prototype._regenerateVertexData = function () {
  27858. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  27859. };
  27860. TorusKnot.prototype.copy = function (id) {
  27861. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27862. };
  27863. TorusKnot.prototype.serialize = function () {
  27864. var serializationObject = _super.prototype.serialize.call(this);
  27865. serializationObject.radius = this.radius;
  27866. serializationObject.tube = this.tube;
  27867. serializationObject.radialSegments = this.radialSegments;
  27868. serializationObject.tubularSegments = this.tubularSegments;
  27869. serializationObject.p = this.p;
  27870. serializationObject.q = this.q;
  27871. return serializationObject;
  27872. };
  27873. ;
  27874. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27875. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27876. return null; // null since geometry could be something else than a ground...
  27877. }
  27878. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27879. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27880. scene.pushGeometry(torusKnot, true);
  27881. return torusKnot;
  27882. };
  27883. return TorusKnot;
  27884. })(_Primitive);
  27885. Primitives.TorusKnot = TorusKnot;
  27886. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27887. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27888. })(BABYLON || (BABYLON = {}));
  27889. var BABYLON;
  27890. (function (BABYLON) {
  27891. var GroundMesh = (function (_super) {
  27892. __extends(GroundMesh, _super);
  27893. function GroundMesh(name, scene) {
  27894. _super.call(this, name, scene);
  27895. this.generateOctree = false;
  27896. this._worldInverse = new BABYLON.Matrix();
  27897. }
  27898. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27899. get: function () {
  27900. return this._subdivisions;
  27901. },
  27902. enumerable: true,
  27903. configurable: true
  27904. });
  27905. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27906. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27907. this._subdivisions = chunksCount;
  27908. this.subdivide(this._subdivisions);
  27909. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27910. };
  27911. /**
  27912. * Returns a height (y) value in the Worl system :
  27913. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27914. * Returns the ground y position if (x, z) are outside the ground surface.
  27915. * Not pertinent if the ground is rotated.
  27916. */
  27917. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27918. // express x and y in the ground local system
  27919. x -= this.position.x;
  27920. z -= this.position.z;
  27921. x /= this.scaling.x;
  27922. z /= this.scaling.z;
  27923. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27924. return this.position.y;
  27925. }
  27926. if (!this._heightQuads || this._heightQuads.length == 0) {
  27927. this._computeHeightQuads();
  27928. }
  27929. var facet = this._getFacetAt(x, z);
  27930. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27931. // return y in the World system
  27932. return y * this.scaling.y + this.position.y;
  27933. };
  27934. /**
  27935. * Returns a normalized vector (Vector3) orthogonal to the ground
  27936. * at the ground coordinates (x, z) expressed in the World system.
  27937. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27938. * Not pertinent if the ground is rotated.
  27939. */
  27940. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27941. var normal = new BABYLON.Vector3(0, 1, 0);
  27942. this.getNormalAtCoordinatesToRef(x, z, normal);
  27943. return normal;
  27944. };
  27945. /**
  27946. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27947. * at the ground coordinates (x, z) expressed in the World system.
  27948. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27949. * Not pertinent if the ground is rotated.
  27950. */
  27951. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27952. // express x and y in the ground local system
  27953. x -= this.position.x;
  27954. z -= this.position.z;
  27955. x /= this.scaling.x;
  27956. z /= this.scaling.z;
  27957. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27958. return;
  27959. }
  27960. if (!this._heightQuads || this._heightQuads.length == 0) {
  27961. this._computeHeightQuads();
  27962. }
  27963. var facet = this._getFacetAt(x, z);
  27964. ref.x = facet.x;
  27965. ref.y = facet.y;
  27966. ref.z = facet.z;
  27967. };
  27968. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27969. GroundMesh.prototype._getFacetAt = function (x, z) {
  27970. // retrieve col and row from x, z coordinates in the ground local system
  27971. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27972. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27973. var quad = this._heightQuads[row * this._subdivisions + col];
  27974. var facet;
  27975. if (z < quad.slope.x * x + quad.slope.y) {
  27976. facet = quad.facet1;
  27977. }
  27978. else {
  27979. facet = quad.facet2;
  27980. }
  27981. return facet;
  27982. };
  27983. // Populates the heightMap array with "facet" elements :
  27984. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27985. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27986. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  27987. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  27988. GroundMesh.prototype._computeHeightQuads = function () {
  27989. this._heightQuads = new Array();
  27990. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27991. var v1 = BABYLON.Vector3.Zero();
  27992. var v2 = BABYLON.Vector3.Zero();
  27993. var v3 = BABYLON.Vector3.Zero();
  27994. var v4 = BABYLON.Vector3.Zero();
  27995. var v1v2 = BABYLON.Vector3.Zero();
  27996. var v1v3 = BABYLON.Vector3.Zero();
  27997. var v1v4 = BABYLON.Vector3.Zero();
  27998. var norm1 = BABYLON.Vector3.Zero();
  27999. var norm2 = BABYLON.Vector3.Zero();
  28000. var i = 0;
  28001. var j = 0;
  28002. var k = 0;
  28003. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28004. var h = 0;
  28005. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28006. var d2 = 0;
  28007. for (var row = 0; row < this._subdivisions; row++) {
  28008. for (var col = 0; col < this._subdivisions; col++) {
  28009. i = col * 3;
  28010. j = row * (this._subdivisions + 1) * 3;
  28011. k = (row + 1) * (this._subdivisions + 1) * 3;
  28012. v1.x = positions[j + i];
  28013. v1.y = positions[j + i + 1];
  28014. v1.z = positions[j + i + 2];
  28015. v2.x = positions[j + i + 3];
  28016. v2.y = positions[j + i + 4];
  28017. v2.z = positions[j + i + 5];
  28018. v3.x = positions[k + i];
  28019. v3.y = positions[k + i + 1];
  28020. v3.z = positions[k + i + 2];
  28021. v4.x = positions[k + i + 3];
  28022. v4.y = positions[k + i + 4];
  28023. v4.z = positions[k + i + 5];
  28024. // 2D slope V1V4
  28025. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28026. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28027. var slope = new BABYLON.Vector2(cd, h);
  28028. // facet equations :
  28029. // we compute each facet normal vector
  28030. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28031. // we compute the value d by applying the equation to v1 which belongs to the plane
  28032. // then we store the facet equation in a Vector4
  28033. v2.subtractToRef(v1, v1v2);
  28034. v3.subtractToRef(v1, v1v3);
  28035. v4.subtractToRef(v1, v1v4);
  28036. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28037. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28038. norm1.normalize();
  28039. norm2.normalize();
  28040. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28041. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28042. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  28043. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  28044. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  28045. this._heightQuads.push(quad);
  28046. }
  28047. }
  28048. };
  28049. return GroundMesh;
  28050. })(BABYLON.Mesh);
  28051. BABYLON.GroundMesh = GroundMesh;
  28052. })(BABYLON || (BABYLON = {}));
  28053. var BABYLON;
  28054. (function (BABYLON) {
  28055. var LinesMesh = (function (_super) {
  28056. __extends(LinesMesh, _super);
  28057. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28058. if (parent === void 0) { parent = null; }
  28059. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28060. this.color = new BABYLON.Color3(1, 1, 1);
  28061. this.alpha = 1;
  28062. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28063. attributes: ["position"],
  28064. uniforms: ["worldViewProjection", "color"],
  28065. needAlphaBlending: true
  28066. });
  28067. }
  28068. Object.defineProperty(LinesMesh.prototype, "material", {
  28069. get: function () {
  28070. return this._colorShader;
  28071. },
  28072. enumerable: true,
  28073. configurable: true
  28074. });
  28075. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28076. get: function () {
  28077. return false;
  28078. },
  28079. enumerable: true,
  28080. configurable: true
  28081. });
  28082. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28083. get: function () {
  28084. return false;
  28085. },
  28086. enumerable: true,
  28087. configurable: true
  28088. });
  28089. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28090. var engine = this.getScene().getEngine();
  28091. var indexToBind = this._geometry.getIndexBuffer();
  28092. // VBOs
  28093. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28094. // Color
  28095. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28096. };
  28097. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28098. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28099. return;
  28100. }
  28101. var engine = this.getScene().getEngine();
  28102. // Draw order
  28103. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28104. };
  28105. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28106. return null;
  28107. };
  28108. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28109. this._colorShader.dispose();
  28110. _super.prototype.dispose.call(this, doNotRecurse);
  28111. };
  28112. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28113. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28114. };
  28115. return LinesMesh;
  28116. })(BABYLON.Mesh);
  28117. BABYLON.LinesMesh = LinesMesh;
  28118. })(BABYLON || (BABYLON = {}));
  28119. var BABYLON;
  28120. (function (BABYLON) {
  28121. var DebugLayer = (function () {
  28122. function DebugLayer(scene) {
  28123. var _this = this;
  28124. this._transformationMatrix = BABYLON.Matrix.Identity();
  28125. this._enabled = false;
  28126. this._labelsEnabled = false;
  28127. this._displayStatistics = true;
  28128. this._displayTree = false;
  28129. this._displayLogs = false;
  28130. this._identityMatrix = BABYLON.Matrix.Identity();
  28131. this.axisRatio = 0.02;
  28132. this.accentColor = "orange";
  28133. this._scene = scene;
  28134. this._syncPositions = function () {
  28135. var engine = _this._scene.getEngine();
  28136. var canvasRect = engine.getRenderingCanvasClientRect();
  28137. if (_this._showUI) {
  28138. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28139. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28140. _this._statsDiv.style.width = "400px";
  28141. _this._statsDiv.style.height = "auto";
  28142. _this._statsSubsetDiv.style.maxHeight = "240px";
  28143. _this._optionsDiv.style.left = "0px";
  28144. _this._optionsDiv.style.top = "10px";
  28145. _this._optionsDiv.style.width = "200px";
  28146. _this._optionsDiv.style.height = "auto";
  28147. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28148. _this._logDiv.style.left = "0px";
  28149. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28150. _this._logDiv.style.width = "600px";
  28151. _this._logDiv.style.height = "160px";
  28152. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28153. _this._treeDiv.style.top = "10px";
  28154. _this._treeDiv.style.width = "300px";
  28155. _this._treeDiv.style.height = "auto";
  28156. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28157. }
  28158. _this._globalDiv.style.left = canvasRect.left + "px";
  28159. _this._globalDiv.style.top = canvasRect.top + "px";
  28160. _this._drawingCanvas.style.left = "0px";
  28161. _this._drawingCanvas.style.top = "0px";
  28162. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28163. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28164. var devicePixelRatio = window.devicePixelRatio || 1;
  28165. var context = _this._drawingContext;
  28166. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28167. context.mozBackingStorePixelRatio ||
  28168. context.msBackingStorePixelRatio ||
  28169. context.oBackingStorePixelRatio ||
  28170. context.backingStorePixelRatio || 1;
  28171. _this._ratio = devicePixelRatio / backingStoreRatio;
  28172. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28173. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28174. };
  28175. this._onCanvasClick = function (evt) {
  28176. _this._clickPosition = {
  28177. x: evt.clientX * _this._ratio,
  28178. y: evt.clientY * _this._ratio
  28179. };
  28180. };
  28181. this._syncUI = function () {
  28182. if (_this._showUI) {
  28183. if (_this._displayStatistics) {
  28184. _this._displayStats();
  28185. _this._statsDiv.style.display = "";
  28186. }
  28187. else {
  28188. _this._statsDiv.style.display = "none";
  28189. }
  28190. if (_this._displayLogs) {
  28191. _this._logDiv.style.display = "";
  28192. }
  28193. else {
  28194. _this._logDiv.style.display = "none";
  28195. }
  28196. if (_this._displayTree) {
  28197. _this._treeDiv.style.display = "";
  28198. if (_this._needToRefreshMeshesTree) {
  28199. _this._needToRefreshMeshesTree = false;
  28200. _this._refreshMeshesTreeContent();
  28201. }
  28202. }
  28203. else {
  28204. _this._treeDiv.style.display = "none";
  28205. }
  28206. }
  28207. };
  28208. this._syncData = function () {
  28209. if (_this._labelsEnabled || !_this._showUI) {
  28210. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28211. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28212. var engine = _this._scene.getEngine();
  28213. var viewport = _this._camera.viewport;
  28214. var globalViewport = viewport.toGlobal(engine);
  28215. // Meshes
  28216. var meshes = _this._camera.getActiveMeshes();
  28217. var index;
  28218. var projectedPosition;
  28219. for (index = 0; index < meshes.length; index++) {
  28220. var mesh = meshes.data[index];
  28221. var position = mesh.getBoundingInfo().boundingSphere.center;
  28222. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28223. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28224. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28225. }
  28226. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28227. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28228. }
  28229. }
  28230. // Cameras
  28231. var cameras = _this._scene.cameras;
  28232. for (index = 0; index < cameras.length; index++) {
  28233. var camera = cameras[index];
  28234. if (camera === _this._camera) {
  28235. continue;
  28236. }
  28237. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28238. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28239. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28240. _this._camera.detachControl(engine.getRenderingCanvas());
  28241. _this._camera = camera;
  28242. _this._camera.attachControl(engine.getRenderingCanvas());
  28243. }, function () { return "purple"; });
  28244. }
  28245. }
  28246. // Lights
  28247. var lights = _this._scene.lights;
  28248. for (index = 0; index < lights.length; index++) {
  28249. var light = lights[index];
  28250. if (light.position) {
  28251. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28252. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28253. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28254. light.setEnabled(!light.isEnabled());
  28255. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28256. }
  28257. }
  28258. }
  28259. }
  28260. _this._clickPosition = undefined;
  28261. };
  28262. }
  28263. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28264. while (this._treeSubsetDiv.hasChildNodes()) {
  28265. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28266. }
  28267. // Add meshes
  28268. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28269. sortedArray.sort(function (a, b) {
  28270. if (a.name === b.name) {
  28271. return 0;
  28272. }
  28273. return (a.name > b.name) ? 1 : -1;
  28274. });
  28275. for (var index = 0; index < sortedArray.length; index++) {
  28276. var mesh = sortedArray[index];
  28277. if (!mesh.isEnabled()) {
  28278. continue;
  28279. }
  28280. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28281. m.isVisible = element.checked;
  28282. }, mesh);
  28283. }
  28284. };
  28285. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28286. this._drawingContext.beginPath();
  28287. this._drawingContext.moveTo(zero.x, zero.y);
  28288. this._drawingContext.lineTo(unit.x, unit.y);
  28289. this._drawingContext.strokeStyle = color;
  28290. this._drawingContext.lineWidth = 4;
  28291. this._drawingContext.stroke();
  28292. this._drawingContext.font = "normal 14px Segoe UI";
  28293. this._drawingContext.fillStyle = color;
  28294. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28295. };
  28296. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28297. var position = mesh.getBoundingInfo().boundingSphere.center;
  28298. var worldMatrix = mesh.getWorldMatrix();
  28299. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28300. var unit = (unprojectedVector.subtract(position)).length();
  28301. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28302. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28303. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28304. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28305. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28306. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28307. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28308. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28309. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28310. };
  28311. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28312. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28313. this._drawingContext.font = "normal 12px Segoe UI";
  28314. var textMetrics = this._drawingContext.measureText(text);
  28315. var centerX = projectedPosition.x - textMetrics.width / 2;
  28316. var centerY = projectedPosition.y;
  28317. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28318. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28319. onClick();
  28320. }
  28321. this._drawingContext.beginPath();
  28322. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28323. this._drawingContext.fillStyle = getFillStyle();
  28324. this._drawingContext.globalAlpha = 0.5;
  28325. this._drawingContext.fill();
  28326. this._drawingContext.globalAlpha = 1.0;
  28327. this._drawingContext.strokeStyle = '#FFFFFF';
  28328. this._drawingContext.lineWidth = 1;
  28329. this._drawingContext.stroke();
  28330. this._drawingContext.fillStyle = "#FFFFFF";
  28331. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28332. this._drawingContext.beginPath();
  28333. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28334. this._drawingContext.fill();
  28335. }
  28336. };
  28337. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28338. if (!this._clickPosition) {
  28339. return false;
  28340. }
  28341. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28342. return false;
  28343. }
  28344. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28345. return false;
  28346. }
  28347. return true;
  28348. };
  28349. DebugLayer.prototype.isVisible = function () {
  28350. return this._enabled;
  28351. };
  28352. DebugLayer.prototype.hide = function () {
  28353. if (!this._enabled) {
  28354. return;
  28355. }
  28356. this._enabled = false;
  28357. var engine = this._scene.getEngine();
  28358. this._scene.unregisterBeforeRender(this._syncData);
  28359. this._scene.unregisterAfterRender(this._syncUI);
  28360. this._rootElement.removeChild(this._globalDiv);
  28361. this._scene.forceShowBoundingBoxes = false;
  28362. this._scene.forceWireframe = false;
  28363. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28364. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28365. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28366. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28367. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28368. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28369. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28370. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28371. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28372. this._scene.shadowsEnabled = true;
  28373. this._scene.particlesEnabled = true;
  28374. this._scene.postProcessesEnabled = true;
  28375. this._scene.collisionsEnabled = true;
  28376. this._scene.lightsEnabled = true;
  28377. this._scene.texturesEnabled = true;
  28378. this._scene.lensFlaresEnabled = true;
  28379. this._scene.proceduralTexturesEnabled = true;
  28380. this._scene.renderTargetsEnabled = true;
  28381. this._scene.probesEnabled = true;
  28382. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28383. };
  28384. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28385. if (showUI === void 0) { showUI = true; }
  28386. if (camera === void 0) { camera = null; }
  28387. if (rootElement === void 0) { rootElement = null; }
  28388. if (this._enabled) {
  28389. return;
  28390. }
  28391. this._enabled = true;
  28392. if (camera) {
  28393. this._camera = camera;
  28394. }
  28395. else {
  28396. this._camera = this._scene.activeCamera;
  28397. }
  28398. this._showUI = showUI;
  28399. var engine = this._scene.getEngine();
  28400. this._globalDiv = document.createElement("div");
  28401. this._rootElement = rootElement || document.body;
  28402. this._rootElement.appendChild(this._globalDiv);
  28403. this._generateDOMelements();
  28404. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28405. this._syncPositions();
  28406. this._scene.registerBeforeRender(this._syncData);
  28407. this._scene.registerAfterRender(this._syncUI);
  28408. };
  28409. DebugLayer.prototype._clearLabels = function () {
  28410. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28411. for (var index = 0; index < this._scene.meshes.length; index++) {
  28412. var mesh = this._scene.meshes[index];
  28413. mesh.renderOverlay = false;
  28414. }
  28415. };
  28416. DebugLayer.prototype._generateheader = function (root, text) {
  28417. var header = document.createElement("div");
  28418. header.innerHTML = text + "&nbsp;";
  28419. header.style.textAlign = "right";
  28420. header.style.width = "100%";
  28421. header.style.color = "white";
  28422. header.style.backgroundColor = "Black";
  28423. header.style.padding = "5px 5px 4px 0px";
  28424. header.style.marginLeft = "-5px";
  28425. header.style.fontWeight = "bold";
  28426. root.appendChild(header);
  28427. };
  28428. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28429. var label = document.createElement("label");
  28430. label.innerHTML = title;
  28431. label.style.color = color;
  28432. root.appendChild(label);
  28433. root.appendChild(document.createElement("br"));
  28434. };
  28435. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28436. if (tag === void 0) { tag = null; }
  28437. var label = document.createElement("label");
  28438. var boundingBoxesCheckbox = document.createElement("input");
  28439. boundingBoxesCheckbox.type = "checkbox";
  28440. boundingBoxesCheckbox.checked = initialState;
  28441. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28442. task(evt.target, tag);
  28443. });
  28444. label.appendChild(boundingBoxesCheckbox);
  28445. var container = document.createElement("span");
  28446. var leftPart = document.createElement("span");
  28447. var rightPart = document.createElement("span");
  28448. rightPart.style.cssFloat = "right";
  28449. leftPart.innerHTML = leftTitle;
  28450. rightPart.innerHTML = rightTitle;
  28451. rightPart.style.fontSize = "12px";
  28452. rightPart.style.maxWidth = "200px";
  28453. container.appendChild(leftPart);
  28454. container.appendChild(rightPart);
  28455. label.appendChild(container);
  28456. root.appendChild(label);
  28457. root.appendChild(document.createElement("br"));
  28458. };
  28459. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28460. if (tag === void 0) { tag = null; }
  28461. var label = document.createElement("label");
  28462. var checkBox = document.createElement("input");
  28463. checkBox.type = "checkbox";
  28464. checkBox.checked = initialState;
  28465. checkBox.addEventListener("change", function (evt) {
  28466. task(evt.target, tag);
  28467. });
  28468. label.appendChild(checkBox);
  28469. label.appendChild(document.createTextNode(title));
  28470. root.appendChild(label);
  28471. root.appendChild(document.createElement("br"));
  28472. };
  28473. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28474. if (tag === void 0) { tag = null; }
  28475. var button = document.createElement("button");
  28476. button.innerHTML = title;
  28477. button.style.height = "24px";
  28478. button.style.width = "150px";
  28479. button.style.marginBottom = "5px";
  28480. button.style.color = "#444444";
  28481. button.style.border = "1px solid white";
  28482. button.className = "debugLayerButton";
  28483. button.addEventListener("click", function (evt) {
  28484. task(evt.target, tag);
  28485. });
  28486. root.appendChild(button);
  28487. root.appendChild(document.createElement("br"));
  28488. };
  28489. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28490. if (tag === void 0) { tag = null; }
  28491. var label = document.createElement("label");
  28492. var boundingBoxesRadio = document.createElement("input");
  28493. boundingBoxesRadio.type = "radio";
  28494. boundingBoxesRadio.name = name;
  28495. boundingBoxesRadio.checked = initialState;
  28496. boundingBoxesRadio.addEventListener("change", function (evt) {
  28497. task(evt.target, tag);
  28498. });
  28499. label.appendChild(boundingBoxesRadio);
  28500. label.appendChild(document.createTextNode(title));
  28501. root.appendChild(label);
  28502. root.appendChild(document.createElement("br"));
  28503. };
  28504. DebugLayer.prototype._generateDOMelements = function () {
  28505. var _this = this;
  28506. this._globalDiv.id = "DebugLayer";
  28507. this._globalDiv.style.position = "absolute";
  28508. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28509. this._globalDiv.style.fontSize = "14px";
  28510. this._globalDiv.style.color = "white";
  28511. // Drawing canvas
  28512. this._drawingCanvas = document.createElement("canvas");
  28513. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28514. this._drawingCanvas.style.position = "absolute";
  28515. this._drawingCanvas.style.pointerEvents = "none";
  28516. this._drawingCanvas.style.backgroundColor = "transparent";
  28517. this._drawingContext = this._drawingCanvas.getContext("2d");
  28518. this._globalDiv.appendChild(this._drawingCanvas);
  28519. if (this._showUI) {
  28520. var background = "rgba(128, 128, 128, 0.4)";
  28521. var border = "rgb(180, 180, 180) solid 1px";
  28522. // Stats
  28523. this._statsDiv = document.createElement("div");
  28524. this._statsDiv.id = "DebugLayerStats";
  28525. this._statsDiv.style.border = border;
  28526. this._statsDiv.style.position = "absolute";
  28527. this._statsDiv.style.background = background;
  28528. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28529. this._generateheader(this._statsDiv, "STATISTICS");
  28530. this._statsSubsetDiv = document.createElement("div");
  28531. this._statsSubsetDiv.style.paddingTop = "5px";
  28532. this._statsSubsetDiv.style.paddingBottom = "5px";
  28533. this._statsSubsetDiv.style.overflowY = "auto";
  28534. this._statsDiv.appendChild(this._statsSubsetDiv);
  28535. // Tree
  28536. this._treeDiv = document.createElement("div");
  28537. this._treeDiv.id = "DebugLayerTree";
  28538. this._treeDiv.style.border = border;
  28539. this._treeDiv.style.position = "absolute";
  28540. this._treeDiv.style.background = background;
  28541. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28542. this._treeDiv.style.display = "none";
  28543. this._generateheader(this._treeDiv, "MESHES TREE");
  28544. this._treeSubsetDiv = document.createElement("div");
  28545. this._treeSubsetDiv.style.paddingTop = "5px";
  28546. this._treeSubsetDiv.style.paddingRight = "5px";
  28547. this._treeSubsetDiv.style.overflowY = "auto";
  28548. this._treeSubsetDiv.style.maxHeight = "300px";
  28549. this._treeDiv.appendChild(this._treeSubsetDiv);
  28550. this._needToRefreshMeshesTree = true;
  28551. // Logs
  28552. this._logDiv = document.createElement("div");
  28553. this._logDiv.style.border = border;
  28554. this._logDiv.id = "DebugLayerLogs";
  28555. this._logDiv.style.position = "absolute";
  28556. this._logDiv.style.background = background;
  28557. this._logDiv.style.padding = "0px 0px 0px 5px";
  28558. this._logDiv.style.display = "none";
  28559. this._generateheader(this._logDiv, "LOGS");
  28560. this._logSubsetDiv = document.createElement("div");
  28561. this._logSubsetDiv.style.height = "127px";
  28562. this._logSubsetDiv.style.paddingTop = "5px";
  28563. this._logSubsetDiv.style.overflowY = "auto";
  28564. this._logSubsetDiv.style.fontSize = "12px";
  28565. this._logSubsetDiv.style.fontFamily = "consolas";
  28566. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28567. this._logDiv.appendChild(this._logSubsetDiv);
  28568. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28569. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28570. };
  28571. // Options
  28572. this._optionsDiv = document.createElement("div");
  28573. this._optionsDiv.id = "DebugLayerOptions";
  28574. this._optionsDiv.style.border = border;
  28575. this._optionsDiv.style.position = "absolute";
  28576. this._optionsDiv.style.background = background;
  28577. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28578. this._optionsDiv.style.overflowY = "auto";
  28579. this._generateheader(this._optionsDiv, "OPTIONS");
  28580. this._optionsSubsetDiv = document.createElement("div");
  28581. this._optionsSubsetDiv.style.paddingTop = "5px";
  28582. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28583. this._optionsSubsetDiv.style.overflowY = "auto";
  28584. this._optionsSubsetDiv.style.maxHeight = "200px";
  28585. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28586. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28587. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28588. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28589. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28590. _this._displayTree = element.checked;
  28591. _this._needToRefreshMeshesTree = true;
  28592. });
  28593. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28594. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28595. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28596. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28597. _this._labelsEnabled = element.checked;
  28598. if (!_this._labelsEnabled) {
  28599. _this._clearLabels();
  28600. }
  28601. });
  28602. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28603. if (element.checked) {
  28604. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28605. }
  28606. else {
  28607. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28608. }
  28609. });
  28610. ;
  28611. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28612. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28613. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28614. if (element.checked) {
  28615. _this._scene.forceWireframe = false;
  28616. _this._scene.forcePointsCloud = false;
  28617. }
  28618. });
  28619. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28620. if (element.checked) {
  28621. _this._scene.forceWireframe = true;
  28622. _this._scene.forcePointsCloud = false;
  28623. }
  28624. });
  28625. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28626. if (element.checked) {
  28627. _this._scene.forceWireframe = false;
  28628. _this._scene.forcePointsCloud = true;
  28629. }
  28630. });
  28631. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28632. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28633. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28634. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28635. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28636. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28637. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28638. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28639. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28640. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  28641. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  28642. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28643. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28644. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28645. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28646. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28647. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28648. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28649. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28650. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28651. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28652. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28653. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28654. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28655. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28656. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28657. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28658. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28659. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28660. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28661. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28662. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28663. if (element.checked) {
  28664. _this._scene.headphone = true;
  28665. }
  28666. });
  28667. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28668. if (element.checked) {
  28669. _this._scene.headphone = false;
  28670. }
  28671. });
  28672. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28673. _this._scene.audioEnabled = !element.checked;
  28674. });
  28675. }
  28676. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28677. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28678. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28679. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28680. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28681. if (_this._camera) {
  28682. console.log(_this._camera);
  28683. }
  28684. else {
  28685. console.warn("No camera defined, or debug layer created before camera creation!");
  28686. }
  28687. });
  28688. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28689. this._globalDiv.appendChild(this._statsDiv);
  28690. this._globalDiv.appendChild(this._logDiv);
  28691. this._globalDiv.appendChild(this._optionsDiv);
  28692. this._globalDiv.appendChild(this._treeDiv);
  28693. }
  28694. };
  28695. DebugLayer.prototype._displayStats = function () {
  28696. var scene = this._scene;
  28697. var engine = scene.getEngine();
  28698. var glInfo = engine.getGlInfo();
  28699. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28700. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28701. + "<b>Count</b><br>"
  28702. + "Total meshes: " + scene.meshes.length + "<br>"
  28703. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28704. + "Total materials: " + scene.materials.length + "<br>"
  28705. + "Total textures: " + scene.textures.length + "<br>"
  28706. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28707. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28708. + "Active bones: " + scene.getActiveBones() + "<br>"
  28709. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28710. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  28711. + "<b>Duration</b><br>"
  28712. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28713. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28714. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28715. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28716. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28717. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28718. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  28719. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  28720. + "</div>"
  28721. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28722. + "<b>Extensions</b><br>"
  28723. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28724. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28725. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28726. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  28727. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28728. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28729. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  28730. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  28731. + "</div><br>"
  28732. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28733. + "<b>Caps.</b><br>"
  28734. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28735. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28736. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  28737. + "<b>Info</b><br>"
  28738. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  28739. + glInfo.version + "<br>"
  28740. + "</div><br>"
  28741. + glInfo.renderer + "<br>";
  28742. if (this.customStatsFunction) {
  28743. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28744. }
  28745. };
  28746. return DebugLayer;
  28747. })();
  28748. BABYLON.DebugLayer = DebugLayer;
  28749. })(BABYLON || (BABYLON = {}));
  28750. var BABYLON;
  28751. (function (BABYLON) {
  28752. var DefaultLoadingScreen = (function () {
  28753. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28754. var _this = this;
  28755. if (_loadingText === void 0) { _loadingText = ""; }
  28756. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28757. this._renderingCanvas = _renderingCanvas;
  28758. this._loadingText = _loadingText;
  28759. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28760. // Resize
  28761. this._resizeLoadingUI = function () {
  28762. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28763. _this._loadingDiv.style.position = "absolute";
  28764. _this._loadingDiv.style.left = canvasRect.left + "px";
  28765. _this._loadingDiv.style.top = canvasRect.top + "px";
  28766. _this._loadingDiv.style.width = canvasRect.width + "px";
  28767. _this._loadingDiv.style.height = canvasRect.height + "px";
  28768. };
  28769. }
  28770. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28771. var _this = this;
  28772. if (this._loadingDiv) {
  28773. // Do not add a loading screen if there is already one
  28774. return;
  28775. }
  28776. this._loadingDiv = document.createElement("div");
  28777. this._loadingDiv.id = "babylonjsLoadingDiv";
  28778. this._loadingDiv.style.opacity = "0";
  28779. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28780. // Loading text
  28781. this._loadingTextDiv = document.createElement("div");
  28782. this._loadingTextDiv.style.position = "absolute";
  28783. this._loadingTextDiv.style.left = "0";
  28784. this._loadingTextDiv.style.top = "50%";
  28785. this._loadingTextDiv.style.marginTop = "80px";
  28786. this._loadingTextDiv.style.width = "100%";
  28787. this._loadingTextDiv.style.height = "20px";
  28788. this._loadingTextDiv.style.fontFamily = "Arial";
  28789. this._loadingTextDiv.style.fontSize = "14px";
  28790. this._loadingTextDiv.style.color = "white";
  28791. this._loadingTextDiv.style.textAlign = "center";
  28792. this._loadingTextDiv.innerHTML = "Loading";
  28793. this._loadingDiv.appendChild(this._loadingTextDiv);
  28794. //set the predefined text
  28795. this._loadingTextDiv.innerHTML = this._loadingText;
  28796. // Loading img
  28797. var imgBack = new Image();
  28798. 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==";
  28799. imgBack.style.position = "absolute";
  28800. imgBack.style.left = "50%";
  28801. imgBack.style.top = "50%";
  28802. imgBack.style.marginLeft = "-50px";
  28803. imgBack.style.marginTop = "-50px";
  28804. imgBack.style.transition = "transform 1.0s ease";
  28805. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28806. var deg = 360;
  28807. var onTransitionEnd = function () {
  28808. deg += 360;
  28809. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28810. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28811. };
  28812. imgBack.addEventListener("transitionend", onTransitionEnd);
  28813. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28814. this._loadingDiv.appendChild(imgBack);
  28815. // front image
  28816. var imgFront = new Image();
  28817. 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=";
  28818. imgFront.style.position = "absolute";
  28819. imgFront.style.left = "50%";
  28820. imgFront.style.top = "50%";
  28821. imgFront.style.marginLeft = "-50px";
  28822. imgFront.style.marginTop = "-50px";
  28823. this._loadingDiv.appendChild(imgFront);
  28824. this._resizeLoadingUI();
  28825. window.addEventListener("resize", this._resizeLoadingUI);
  28826. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28827. document.body.appendChild(this._loadingDiv);
  28828. setTimeout(function () {
  28829. _this._loadingDiv.style.opacity = "1";
  28830. imgBack.style.transform = "rotateZ(360deg)";
  28831. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28832. }, 0);
  28833. };
  28834. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28835. var _this = this;
  28836. if (!this._loadingDiv) {
  28837. return;
  28838. }
  28839. var onTransitionEnd = function () {
  28840. if (!_this._loadingDiv) {
  28841. return;
  28842. }
  28843. document.body.removeChild(_this._loadingDiv);
  28844. window.removeEventListener("resize", _this._resizeLoadingUI);
  28845. _this._loadingDiv = null;
  28846. };
  28847. this._loadingDiv.style.opacity = "0";
  28848. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28849. };
  28850. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28851. set: function (text) {
  28852. this._loadingText = text;
  28853. if (this._loadingTextDiv) {
  28854. this._loadingTextDiv.innerHTML = this._loadingText;
  28855. }
  28856. },
  28857. enumerable: true,
  28858. configurable: true
  28859. });
  28860. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28861. get: function () {
  28862. return this._loadingDivBackgroundColor;
  28863. },
  28864. set: function (color) {
  28865. this._loadingDivBackgroundColor = color;
  28866. if (!this._loadingDiv) {
  28867. return;
  28868. }
  28869. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28870. },
  28871. enumerable: true,
  28872. configurable: true
  28873. });
  28874. return DefaultLoadingScreen;
  28875. })();
  28876. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28877. })(BABYLON || (BABYLON = {}));
  28878. var BABYLON;
  28879. (function (BABYLON) {
  28880. var AudioEngine = (function () {
  28881. function AudioEngine() {
  28882. this._audioContext = null;
  28883. this._audioContextInitialized = false;
  28884. this.canUseWebAudio = false;
  28885. this.WarnedWebAudioUnsupported = false;
  28886. this.unlocked = false;
  28887. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  28888. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28889. this.canUseWebAudio = true;
  28890. }
  28891. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  28892. this._unlockiOSaudio();
  28893. }
  28894. else {
  28895. this.unlocked = true;
  28896. }
  28897. }
  28898. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28899. get: function () {
  28900. if (!this._audioContextInitialized) {
  28901. this._initializeAudioContext();
  28902. }
  28903. return this._audioContext;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. AudioEngine.prototype._unlockiOSaudio = function () {
  28909. var _this = this;
  28910. var unlockaudio = function () {
  28911. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  28912. var source = _this.audioContext.createBufferSource();
  28913. source.buffer = buffer;
  28914. source.connect(_this.audioContext.destination);
  28915. source.start(0);
  28916. setTimeout(function () {
  28917. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  28918. _this.unlocked = true;
  28919. window.removeEventListener('touchend', unlockaudio, false);
  28920. if (_this.onAudioUnlocked) {
  28921. _this.onAudioUnlocked();
  28922. }
  28923. }
  28924. }, 0);
  28925. };
  28926. window.addEventListener('touchend', unlockaudio, false);
  28927. };
  28928. AudioEngine.prototype._initializeAudioContext = function () {
  28929. try {
  28930. if (this.canUseWebAudio) {
  28931. this._audioContext = new AudioContext();
  28932. // create a global volume gain node
  28933. this.masterGain = this._audioContext.createGain();
  28934. this.masterGain.gain.value = 1;
  28935. this.masterGain.connect(this._audioContext.destination);
  28936. this._audioContextInitialized = true;
  28937. }
  28938. }
  28939. catch (e) {
  28940. this.canUseWebAudio = false;
  28941. BABYLON.Tools.Error("Web Audio: " + e.message);
  28942. }
  28943. };
  28944. AudioEngine.prototype.dispose = function () {
  28945. if (this.canUseWebAudio && this._audioContextInitialized) {
  28946. if (this._connectedAnalyser) {
  28947. this._connectedAnalyser.stopDebugCanvas();
  28948. this._connectedAnalyser.dispose();
  28949. this.masterGain.disconnect();
  28950. this.masterGain.connect(this._audioContext.destination);
  28951. this._connectedAnalyser = null;
  28952. }
  28953. this.masterGain.gain.value = 1;
  28954. }
  28955. this.WarnedWebAudioUnsupported = false;
  28956. };
  28957. AudioEngine.prototype.getGlobalVolume = function () {
  28958. if (this.canUseWebAudio && this._audioContextInitialized) {
  28959. return this.masterGain.gain.value;
  28960. }
  28961. else {
  28962. return -1;
  28963. }
  28964. };
  28965. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28966. if (this.canUseWebAudio && this._audioContextInitialized) {
  28967. this.masterGain.gain.value = newVolume;
  28968. }
  28969. };
  28970. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28971. if (this._connectedAnalyser) {
  28972. this._connectedAnalyser.stopDebugCanvas();
  28973. }
  28974. if (this.canUseWebAudio && this._audioContextInitialized) {
  28975. this._connectedAnalyser = analyser;
  28976. this.masterGain.disconnect();
  28977. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28978. }
  28979. };
  28980. return AudioEngine;
  28981. })();
  28982. BABYLON.AudioEngine = AudioEngine;
  28983. })(BABYLON || (BABYLON = {}));
  28984. var BABYLON;
  28985. (function (BABYLON) {
  28986. var Sound = (function () {
  28987. /**
  28988. * Create a sound and attach it to a scene
  28989. * @param name Name of your sound
  28990. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28991. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28992. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  28993. */
  28994. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28995. var _this = this;
  28996. this.autoplay = false;
  28997. this.loop = false;
  28998. this.useCustomAttenuation = false;
  28999. this.spatialSound = false;
  29000. this.refDistance = 1;
  29001. this.rolloffFactor = 1;
  29002. this.maxDistance = 100;
  29003. this.distanceModel = "linear";
  29004. this._panningModel = "equalpower";
  29005. this._playbackRate = 1;
  29006. this._streaming = false;
  29007. this._startTime = 0;
  29008. this._startOffset = 0;
  29009. this._position = BABYLON.Vector3.Zero();
  29010. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29011. this._volume = 1;
  29012. this._isLoaded = false;
  29013. this._isReadyToPlay = false;
  29014. this.isPlaying = false;
  29015. this.isPaused = false;
  29016. this._isDirectional = false;
  29017. // Used if you'd like to create a directional sound.
  29018. // If not set, the sound will be omnidirectional
  29019. this._coneInnerAngle = 360;
  29020. this._coneOuterAngle = 360;
  29021. this._coneOuterGain = 0;
  29022. this._isOutputConnected = false;
  29023. this.name = name;
  29024. this._scene = scene;
  29025. this._readyToPlayCallback = readyToPlayCallback;
  29026. // Default custom attenuation function is a linear attenuation
  29027. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29028. if (currentDistance < maxDistance) {
  29029. return currentVolume * (1 - currentDistance / maxDistance);
  29030. }
  29031. else {
  29032. return 0;
  29033. }
  29034. };
  29035. if (options) {
  29036. this.autoplay = options.autoplay || false;
  29037. this.loop = options.loop || false;
  29038. // if volume === 0, we need another way to check this option
  29039. if (options.volume !== undefined) {
  29040. this._volume = options.volume;
  29041. }
  29042. this.spatialSound = options.spatialSound || false;
  29043. this.maxDistance = options.maxDistance || 100;
  29044. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29045. this.rolloffFactor = options.rolloffFactor || 1;
  29046. this.refDistance = options.refDistance || 1;
  29047. this.distanceModel = options.distanceModel || "linear";
  29048. this._playbackRate = options.playbackRate || 1;
  29049. this._streaming = options.streaming || false;
  29050. }
  29051. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29052. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29053. this._soundGain.gain.value = this._volume;
  29054. this._inputAudioNode = this._soundGain;
  29055. this._ouputAudioNode = this._soundGain;
  29056. if (this.spatialSound) {
  29057. this._createSpatialParameters();
  29058. }
  29059. this._scene.mainSoundTrack.AddSound(this);
  29060. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29061. if (urlOrArrayBuffer) {
  29062. // If it's an URL
  29063. if (typeof (urlOrArrayBuffer) === "string") {
  29064. // Loading sound using XHR2
  29065. if (!this._streaming) {
  29066. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  29067. }
  29068. else {
  29069. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  29070. this._htmlAudioElement.controls = false;
  29071. this._htmlAudioElement.loop = this.loop;
  29072. this._htmlAudioElement.crossOrigin = "anonymous";
  29073. this._htmlAudioElement.preload = "auto";
  29074. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  29075. _this._isReadyToPlay = true;
  29076. if (_this.autoplay) {
  29077. _this.play();
  29078. }
  29079. if (_this._readyToPlayCallback) {
  29080. _this._readyToPlayCallback();
  29081. }
  29082. });
  29083. document.body.appendChild(this._htmlAudioElement);
  29084. }
  29085. }
  29086. else {
  29087. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29088. if (urlOrArrayBuffer.byteLength > 0) {
  29089. this._soundLoaded(urlOrArrayBuffer);
  29090. }
  29091. }
  29092. else {
  29093. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29094. }
  29095. }
  29096. }
  29097. }
  29098. else {
  29099. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29100. this._scene.mainSoundTrack.AddSound(this);
  29101. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29102. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29103. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29104. }
  29105. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29106. if (this._readyToPlayCallback) {
  29107. window.setTimeout(function () {
  29108. _this._readyToPlayCallback();
  29109. }, 1000);
  29110. }
  29111. }
  29112. }
  29113. Sound.prototype.dispose = function () {
  29114. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29115. if (this.isPlaying) {
  29116. this.stop();
  29117. }
  29118. this._isReadyToPlay = false;
  29119. if (this.soundTrackId === -1) {
  29120. this._scene.mainSoundTrack.RemoveSound(this);
  29121. }
  29122. else {
  29123. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29124. }
  29125. if (this._soundGain) {
  29126. this._soundGain.disconnect();
  29127. this._soundGain = null;
  29128. }
  29129. if (this._soundPanner) {
  29130. this._soundPanner.disconnect();
  29131. this._soundPanner = null;
  29132. }
  29133. if (this._soundSource) {
  29134. this._soundSource.disconnect();
  29135. this._soundSource = null;
  29136. }
  29137. this._audioBuffer = null;
  29138. if (this._htmlAudioElement) {
  29139. this._htmlAudioElement.pause();
  29140. this._htmlAudioElement.src = "";
  29141. document.body.removeChild(this._htmlAudioElement);
  29142. }
  29143. if (this._connectedMesh) {
  29144. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29145. this._connectedMesh = null;
  29146. }
  29147. }
  29148. };
  29149. Sound.prototype._soundLoaded = function (audioData) {
  29150. var _this = this;
  29151. this._isLoaded = true;
  29152. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29153. _this._audioBuffer = buffer;
  29154. _this._isReadyToPlay = true;
  29155. if (_this.autoplay) {
  29156. _this.play();
  29157. }
  29158. if (_this._readyToPlayCallback) {
  29159. _this._readyToPlayCallback();
  29160. }
  29161. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  29162. };
  29163. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29164. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29165. this._audioBuffer = audioBuffer;
  29166. this._isReadyToPlay = true;
  29167. }
  29168. };
  29169. Sound.prototype.updateOptions = function (options) {
  29170. if (options) {
  29171. this.loop = options.loop || this.loop;
  29172. this.maxDistance = options.maxDistance || this.maxDistance;
  29173. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29174. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29175. this.refDistance = options.refDistance || this.refDistance;
  29176. this.distanceModel = options.distanceModel || this.distanceModel;
  29177. this._playbackRate = options.playbackRate || this._playbackRate;
  29178. this._updateSpatialParameters();
  29179. if (this.isPlaying) {
  29180. if (this._streaming) {
  29181. this._htmlAudioElement.playbackRate = this._playbackRate;
  29182. }
  29183. else {
  29184. this._soundSource.playbackRate.value = this._playbackRate;
  29185. }
  29186. }
  29187. }
  29188. };
  29189. Sound.prototype._createSpatialParameters = function () {
  29190. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29191. if (this._scene.headphone) {
  29192. this._panningModel = "HRTF";
  29193. }
  29194. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29195. this._updateSpatialParameters();
  29196. this._soundPanner.connect(this._ouputAudioNode);
  29197. this._inputAudioNode = this._soundPanner;
  29198. }
  29199. };
  29200. Sound.prototype._updateSpatialParameters = function () {
  29201. if (this.spatialSound) {
  29202. if (this.useCustomAttenuation) {
  29203. // Tricks to disable in a way embedded Web Audio attenuation
  29204. this._soundPanner.distanceModel = "linear";
  29205. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29206. this._soundPanner.refDistance = 1;
  29207. this._soundPanner.rolloffFactor = 1;
  29208. this._soundPanner.panningModel = this._panningModel;
  29209. }
  29210. else {
  29211. this._soundPanner.distanceModel = this.distanceModel;
  29212. this._soundPanner.maxDistance = this.maxDistance;
  29213. this._soundPanner.refDistance = this.refDistance;
  29214. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29215. this._soundPanner.panningModel = this._panningModel;
  29216. }
  29217. }
  29218. };
  29219. Sound.prototype.switchPanningModelToHRTF = function () {
  29220. this._panningModel = "HRTF";
  29221. this._switchPanningModel();
  29222. };
  29223. Sound.prototype.switchPanningModelToEqualPower = function () {
  29224. this._panningModel = "equalpower";
  29225. this._switchPanningModel();
  29226. };
  29227. Sound.prototype._switchPanningModel = function () {
  29228. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29229. this._soundPanner.panningModel = this._panningModel;
  29230. }
  29231. };
  29232. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29233. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29234. if (this._isOutputConnected) {
  29235. this._ouputAudioNode.disconnect();
  29236. }
  29237. this._ouputAudioNode.connect(soundTrackAudioNode);
  29238. this._isOutputConnected = true;
  29239. }
  29240. };
  29241. /**
  29242. * Transform this sound into a directional source
  29243. * @param coneInnerAngle Size of the inner cone in degree
  29244. * @param coneOuterAngle Size of the outer cone in degree
  29245. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29246. */
  29247. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29248. if (coneOuterAngle < coneInnerAngle) {
  29249. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29250. return;
  29251. }
  29252. this._coneInnerAngle = coneInnerAngle;
  29253. this._coneOuterAngle = coneOuterAngle;
  29254. this._coneOuterGain = coneOuterGain;
  29255. this._isDirectional = true;
  29256. if (this.isPlaying && this.loop) {
  29257. this.stop();
  29258. this.play();
  29259. }
  29260. };
  29261. Sound.prototype.setPosition = function (newPosition) {
  29262. this._position = newPosition;
  29263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29264. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29265. }
  29266. };
  29267. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29268. this._localDirection = newLocalDirection;
  29269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29270. this._updateDirection();
  29271. }
  29272. };
  29273. Sound.prototype._updateDirection = function () {
  29274. var mat = this._connectedMesh.getWorldMatrix();
  29275. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29276. direction.normalize();
  29277. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29278. };
  29279. Sound.prototype.updateDistanceFromListener = function () {
  29280. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29281. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29282. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29283. }
  29284. };
  29285. Sound.prototype.setAttenuationFunction = function (callback) {
  29286. this._customAttenuationFunction = callback;
  29287. };
  29288. /**
  29289. * Play the sound
  29290. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29291. */
  29292. Sound.prototype.play = function (time) {
  29293. var _this = this;
  29294. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29295. try {
  29296. if (this._startOffset < 0) {
  29297. time = -this._startOffset;
  29298. this._startOffset = 0;
  29299. }
  29300. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29301. if (!this._soundSource || !this._streamingSource) {
  29302. if (this.spatialSound) {
  29303. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29304. if (this._isDirectional) {
  29305. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29306. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29307. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29308. if (this._connectedMesh) {
  29309. this._updateDirection();
  29310. }
  29311. else {
  29312. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29313. }
  29314. }
  29315. }
  29316. }
  29317. if (this._streaming) {
  29318. if (!this._streamingSource) {
  29319. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  29320. this._htmlAudioElement.onended = function () { _this._onended(); };
  29321. this._htmlAudioElement.playbackRate = this._playbackRate;
  29322. }
  29323. this._streamingSource.disconnect();
  29324. this._streamingSource.connect(this._inputAudioNode);
  29325. this._htmlAudioElement.play();
  29326. }
  29327. else {
  29328. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29329. this._soundSource.buffer = this._audioBuffer;
  29330. this._soundSource.connect(this._inputAudioNode);
  29331. this._soundSource.loop = this.loop;
  29332. this._soundSource.playbackRate.value = this._playbackRate;
  29333. this._soundSource.onended = function () { _this._onended(); };
  29334. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29335. }
  29336. this._startTime = startTime;
  29337. this.isPlaying = true;
  29338. this.isPaused = false;
  29339. }
  29340. catch (ex) {
  29341. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29342. }
  29343. }
  29344. };
  29345. Sound.prototype._onended = function () {
  29346. this.isPlaying = false;
  29347. if (this.onended) {
  29348. this.onended();
  29349. }
  29350. };
  29351. /**
  29352. * Stop the sound
  29353. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29354. */
  29355. Sound.prototype.stop = function (time) {
  29356. if (this.isPlaying) {
  29357. if (this._streaming) {
  29358. this._htmlAudioElement.pause();
  29359. // Test needed for Firefox or it will generate an Invalid State Error
  29360. if (this._htmlAudioElement.currentTime > 0) {
  29361. this._htmlAudioElement.currentTime = 0;
  29362. }
  29363. }
  29364. else {
  29365. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29366. this._soundSource.stop(stopTime);
  29367. if (!this.isPaused) {
  29368. this._startOffset = 0;
  29369. }
  29370. }
  29371. this.isPlaying = false;
  29372. }
  29373. };
  29374. Sound.prototype.pause = function () {
  29375. if (this.isPlaying) {
  29376. this.isPaused = true;
  29377. if (this._streaming) {
  29378. this._htmlAudioElement.pause();
  29379. }
  29380. else {
  29381. this.stop(0);
  29382. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29383. }
  29384. }
  29385. };
  29386. Sound.prototype.setVolume = function (newVolume, time) {
  29387. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29388. if (time) {
  29389. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  29390. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29391. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  29392. }
  29393. else {
  29394. this._soundGain.gain.value = newVolume;
  29395. }
  29396. }
  29397. this._volume = newVolume;
  29398. };
  29399. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29400. this._playbackRate = newPlaybackRate;
  29401. if (this.isPlaying) {
  29402. if (this._streaming) {
  29403. this._htmlAudioElement.playbackRate = this._playbackRate;
  29404. }
  29405. else {
  29406. this._soundSource.playbackRate.value = this._playbackRate;
  29407. }
  29408. }
  29409. };
  29410. Sound.prototype.getVolume = function () {
  29411. return this._volume;
  29412. };
  29413. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29414. var _this = this;
  29415. if (this._connectedMesh) {
  29416. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29417. this._registerFunc = null;
  29418. }
  29419. this._connectedMesh = meshToConnectTo;
  29420. if (!this.spatialSound) {
  29421. this.spatialSound = true;
  29422. this._createSpatialParameters();
  29423. if (this.isPlaying && this.loop) {
  29424. this.stop();
  29425. this.play();
  29426. }
  29427. }
  29428. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29429. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29430. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29431. };
  29432. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29433. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29434. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29435. this._updateDirection();
  29436. }
  29437. };
  29438. Sound.prototype.clone = function () {
  29439. var _this = this;
  29440. if (!this._streaming) {
  29441. var setBufferAndRun = function () {
  29442. if (_this._isReadyToPlay) {
  29443. clonedSound._audioBuffer = _this.getAudioBuffer();
  29444. clonedSound._isReadyToPlay = true;
  29445. if (clonedSound.autoplay) {
  29446. clonedSound.play();
  29447. }
  29448. }
  29449. else {
  29450. window.setTimeout(setBufferAndRun, 300);
  29451. }
  29452. };
  29453. var currentOptions = {
  29454. autoplay: this.autoplay, loop: this.loop,
  29455. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  29456. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  29457. refDistance: this.refDistance, distanceModel: this.distanceModel
  29458. };
  29459. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  29460. if (this.useCustomAttenuation) {
  29461. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  29462. }
  29463. clonedSound.setPosition(this._position);
  29464. clonedSound.setPlaybackRate(this._playbackRate);
  29465. setBufferAndRun();
  29466. return clonedSound;
  29467. }
  29468. else {
  29469. return null;
  29470. }
  29471. };
  29472. Sound.prototype.getAudioBuffer = function () {
  29473. return this._audioBuffer;
  29474. };
  29475. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  29476. var soundName = parsedSound.name;
  29477. var soundUrl;
  29478. if (parsedSound.url) {
  29479. soundUrl = rootUrl + parsedSound.url;
  29480. }
  29481. else {
  29482. soundUrl = rootUrl + soundName;
  29483. }
  29484. var options = {
  29485. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  29486. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  29487. rolloffFactor: parsedSound.rolloffFactor,
  29488. refDistance: parsedSound.refDistance,
  29489. distanceModel: parsedSound.distanceModel,
  29490. playbackRate: parsedSound.playbackRate
  29491. };
  29492. var newSound;
  29493. if (!sourceSound) {
  29494. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  29495. scene._addPendingData(newSound);
  29496. }
  29497. else {
  29498. var setBufferAndRun = function () {
  29499. if (sourceSound._isReadyToPlay) {
  29500. newSound._audioBuffer = sourceSound.getAudioBuffer();
  29501. newSound._isReadyToPlay = true;
  29502. if (newSound.autoplay) {
  29503. newSound.play();
  29504. }
  29505. }
  29506. else {
  29507. window.setTimeout(setBufferAndRun, 300);
  29508. }
  29509. };
  29510. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  29511. setBufferAndRun();
  29512. }
  29513. if (parsedSound.position) {
  29514. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  29515. newSound.setPosition(soundPosition);
  29516. }
  29517. if (parsedSound.isDirectional) {
  29518. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  29519. if (parsedSound.localDirectionToMesh) {
  29520. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  29521. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  29522. }
  29523. }
  29524. if (parsedSound.connectedMeshId) {
  29525. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  29526. if (connectedMesh) {
  29527. newSound.attachToMesh(connectedMesh);
  29528. }
  29529. }
  29530. return newSound;
  29531. };
  29532. return Sound;
  29533. })();
  29534. BABYLON.Sound = Sound;
  29535. })(BABYLON || (BABYLON = {}));
  29536. var BABYLON;
  29537. (function (BABYLON) {
  29538. var SoundTrack = (function () {
  29539. function SoundTrack(scene, options) {
  29540. this.id = -1;
  29541. this._isMainTrack = false;
  29542. this._isInitialized = false;
  29543. this._scene = scene;
  29544. this.soundCollection = new Array();
  29545. this._options = options;
  29546. if (!this._isMainTrack) {
  29547. this._scene.soundTracks.push(this);
  29548. this.id = this._scene.soundTracks.length - 1;
  29549. }
  29550. }
  29551. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  29552. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29553. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  29554. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  29555. if (this._options) {
  29556. if (this._options.volume) {
  29557. this._outputAudioNode.gain.value = this._options.volume;
  29558. }
  29559. if (this._options.mainTrack) {
  29560. this._isMainTrack = this._options.mainTrack;
  29561. }
  29562. }
  29563. this._isInitialized = true;
  29564. }
  29565. };
  29566. SoundTrack.prototype.dispose = function () {
  29567. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29568. if (this._connectedAnalyser) {
  29569. this._connectedAnalyser.stopDebugCanvas();
  29570. }
  29571. while (this.soundCollection.length) {
  29572. this.soundCollection[0].dispose();
  29573. }
  29574. if (this._outputAudioNode) {
  29575. this._outputAudioNode.disconnect();
  29576. }
  29577. this._outputAudioNode = null;
  29578. }
  29579. };
  29580. SoundTrack.prototype.AddSound = function (sound) {
  29581. if (!this._isInitialized) {
  29582. this._initializeSoundTrackAudioGraph();
  29583. }
  29584. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29585. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29586. }
  29587. if (sound.soundTrackId) {
  29588. if (sound.soundTrackId === -1) {
  29589. this._scene.mainSoundTrack.RemoveSound(sound);
  29590. }
  29591. else {
  29592. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29593. }
  29594. }
  29595. this.soundCollection.push(sound);
  29596. sound.soundTrackId = this.id;
  29597. };
  29598. SoundTrack.prototype.RemoveSound = function (sound) {
  29599. var index = this.soundCollection.indexOf(sound);
  29600. if (index !== -1) {
  29601. this.soundCollection.splice(index, 1);
  29602. }
  29603. };
  29604. SoundTrack.prototype.setVolume = function (newVolume) {
  29605. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29606. this._outputAudioNode.gain.value = newVolume;
  29607. }
  29608. };
  29609. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29610. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29611. for (var i = 0; i < this.soundCollection.length; i++) {
  29612. this.soundCollection[i].switchPanningModelToHRTF();
  29613. }
  29614. }
  29615. };
  29616. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29617. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29618. for (var i = 0; i < this.soundCollection.length; i++) {
  29619. this.soundCollection[i].switchPanningModelToEqualPower();
  29620. }
  29621. }
  29622. };
  29623. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29624. if (this._connectedAnalyser) {
  29625. this._connectedAnalyser.stopDebugCanvas();
  29626. }
  29627. this._connectedAnalyser = analyser;
  29628. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29629. this._outputAudioNode.disconnect();
  29630. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  29631. }
  29632. };
  29633. return SoundTrack;
  29634. })();
  29635. BABYLON.SoundTrack = SoundTrack;
  29636. })(BABYLON || (BABYLON = {}));
  29637. var BABYLON;
  29638. (function (BABYLON) {
  29639. var SIMDVector3 = (function () {
  29640. function SIMDVector3() {
  29641. }
  29642. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29643. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29644. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29645. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29646. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29647. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29648. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  29649. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29650. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29651. };
  29652. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29653. var v0 = SIMD.float32x4.splat(x);
  29654. var v1 = SIMD.float32x4.splat(y);
  29655. var v2 = SIMD.float32x4.splat(z);
  29656. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29657. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29658. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29659. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29660. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  29661. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29662. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29663. };
  29664. return SIMDVector3;
  29665. })();
  29666. BABYLON.SIMDVector3 = SIMDVector3;
  29667. var SIMDMatrix = (function () {
  29668. function SIMDMatrix() {
  29669. }
  29670. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29671. if (offset === void 0) { offset = 0; }
  29672. var tm = this.m;
  29673. var om = other.m;
  29674. var om0 = SIMD.float32x4.load(om, 0);
  29675. var om1 = SIMD.float32x4.load(om, 4);
  29676. var om2 = SIMD.float32x4.load(om, 8);
  29677. var om3 = SIMD.float32x4.load(om, 12);
  29678. var tm0 = SIMD.float32x4.load(tm, 0);
  29679. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  29680. var tm1 = SIMD.float32x4.load(tm, 4);
  29681. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  29682. var tm2 = SIMD.float32x4.load(tm, 8);
  29683. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  29684. var tm3 = SIMD.float32x4.load(tm, 12);
  29685. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  29686. };
  29687. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29688. var src = this.m;
  29689. var dest = other.m;
  29690. var row0, row1, row2, row3;
  29691. var tmp1;
  29692. var minor0, minor1, minor2, minor3;
  29693. var det;
  29694. // Load the 4 rows
  29695. var src0 = SIMD.float32x4.load(src, 0);
  29696. var src1 = SIMD.float32x4.load(src, 4);
  29697. var src2 = SIMD.float32x4.load(src, 8);
  29698. var src3 = SIMD.float32x4.load(src, 12);
  29699. // Transpose the source matrix. Sort of. Not a true transpose operation
  29700. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29701. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29702. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29703. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29704. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29705. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29706. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29707. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29708. // This is a true transposition, but it will lead to an incorrect result
  29709. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29710. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29711. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29712. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29713. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29714. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29715. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29716. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29717. // ----
  29718. tmp1 = SIMD.float32x4.mul(row2, row3);
  29719. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29720. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29721. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29722. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29723. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29724. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29725. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29726. // ----
  29727. tmp1 = SIMD.float32x4.mul(row1, row2);
  29728. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29729. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29730. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29731. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29732. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29733. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29734. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29735. // ----
  29736. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29737. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29738. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29739. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29740. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29741. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29742. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29743. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29744. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29745. // ----
  29746. tmp1 = SIMD.float32x4.mul(row0, row1);
  29747. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29748. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29749. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29750. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29751. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29752. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29753. // ----
  29754. tmp1 = SIMD.float32x4.mul(row0, row3);
  29755. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29756. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29757. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29758. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29759. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29760. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29761. // ----
  29762. tmp1 = SIMD.float32x4.mul(row0, row2);
  29763. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29764. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29765. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29766. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29767. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29768. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29769. // Compute determinant
  29770. det = SIMD.float32x4.mul(row0, minor0);
  29771. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29772. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29773. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29774. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29775. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29776. // These shuffles aren't necessary if the faulty transposition is done
  29777. // up at the top of this function.
  29778. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29779. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29780. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29781. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29782. // Compute final values by multiplying with 1/det
  29783. minor0 = SIMD.float32x4.mul(det, minor0);
  29784. minor1 = SIMD.float32x4.mul(det, minor1);
  29785. minor2 = SIMD.float32x4.mul(det, minor2);
  29786. minor3 = SIMD.float32x4.mul(det, minor3);
  29787. SIMD.float32x4.store(dest, 0, minor0);
  29788. SIMD.float32x4.store(dest, 4, minor1);
  29789. SIMD.float32x4.store(dest, 8, minor2);
  29790. SIMD.float32x4.store(dest, 12, minor3);
  29791. return this;
  29792. };
  29793. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29794. var out = result.m;
  29795. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29796. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29797. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29798. // cc.kmVec3Subtract(f, pCenter, pEye);
  29799. var f = SIMD.float32x4.sub(center, eye);
  29800. // cc.kmVec3Normalize(f, f);
  29801. var tmp = SIMD.float32x4.mul(f, f);
  29802. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29803. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29804. // cc.kmVec3Assign(up, pUp);
  29805. // cc.kmVec3Normalize(up, up);
  29806. tmp = SIMD.float32x4.mul(up, up);
  29807. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29808. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29809. // cc.kmVec3Cross(s, f, up);
  29810. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  29811. // cc.kmVec3Normalize(s, s);
  29812. tmp = SIMD.float32x4.mul(s, s);
  29813. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29814. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29815. // cc.kmVec3Cross(u, s, f);
  29816. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  29817. // cc.kmVec3Normalize(s, s);
  29818. tmp = SIMD.float32x4.mul(s, s);
  29819. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29820. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29821. var zero = SIMD.float32x4.splat(0.0);
  29822. s = SIMD.float32x4.neg(s);
  29823. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29824. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29825. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29826. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29827. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29828. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29829. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29830. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29831. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29832. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29833. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29834. var b3 = SIMD.float32x4.neg(eye);
  29835. b3 = SIMD.float32x4.withW(b3, 1.0);
  29836. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  29837. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  29838. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  29839. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  29840. };
  29841. return SIMDMatrix;
  29842. })();
  29843. BABYLON.SIMDMatrix = SIMDMatrix;
  29844. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29845. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29846. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29847. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29848. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29849. var SIMDHelper = (function () {
  29850. function SIMDHelper() {
  29851. }
  29852. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29853. get: function () {
  29854. return SIMDHelper._isEnabled;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. SIMDHelper.DisableSIMD = function () {
  29860. // Replace functions
  29861. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29862. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29863. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29864. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29866. SIMDHelper._isEnabled = false;
  29867. };
  29868. SIMDHelper.EnableSIMD = function () {
  29869. if (window.SIMD === undefined) {
  29870. return;
  29871. }
  29872. // Replace functions
  29873. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29874. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29875. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29876. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29877. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29878. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29879. get: function () { return this._data[0]; },
  29880. set: function (value) {
  29881. if (!this._data) {
  29882. this._data = new Float32Array(3);
  29883. }
  29884. this._data[0] = value;
  29885. }
  29886. });
  29887. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29888. get: function () { return this._data[1]; },
  29889. set: function (value) {
  29890. this._data[1] = value;
  29891. }
  29892. });
  29893. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29894. get: function () { return this._data[2]; },
  29895. set: function (value) {
  29896. this._data[2] = value;
  29897. }
  29898. });
  29899. SIMDHelper._isEnabled = true;
  29900. };
  29901. SIMDHelper._isEnabled = false;
  29902. return SIMDHelper;
  29903. })();
  29904. BABYLON.SIMDHelper = SIMDHelper;
  29905. })(BABYLON || (BABYLON = {}));
  29906. var BABYLON;
  29907. (function (BABYLON) {
  29908. var ShaderMaterial = (function (_super) {
  29909. __extends(ShaderMaterial, _super);
  29910. function ShaderMaterial(name, scene, shaderPath, options) {
  29911. _super.call(this, name, scene);
  29912. this._textures = {};
  29913. this._floats = {};
  29914. this._floatsArrays = {};
  29915. this._colors3 = {};
  29916. this._colors4 = {};
  29917. this._vectors2 = {};
  29918. this._vectors3 = {};
  29919. this._vectors4 = {};
  29920. this._matrices = {};
  29921. this._matrices3x3 = {};
  29922. this._matrices2x2 = {};
  29923. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29924. this._shaderPath = shaderPath;
  29925. options.needAlphaBlending = options.needAlphaBlending || false;
  29926. options.needAlphaTesting = options.needAlphaTesting || false;
  29927. options.attributes = options.attributes || ["position", "normal", "uv"];
  29928. options.uniforms = options.uniforms || ["worldViewProjection"];
  29929. options.samplers = options.samplers || [];
  29930. options.defines = options.defines || [];
  29931. this._options = options;
  29932. }
  29933. ShaderMaterial.prototype.needAlphaBlending = function () {
  29934. return this._options.needAlphaBlending;
  29935. };
  29936. ShaderMaterial.prototype.needAlphaTesting = function () {
  29937. return this._options.needAlphaTesting;
  29938. };
  29939. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29940. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29941. this._options.uniforms.push(uniformName);
  29942. }
  29943. };
  29944. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29945. if (this._options.samplers.indexOf(name) === -1) {
  29946. this._options.samplers.push(name);
  29947. }
  29948. this._textures[name] = texture;
  29949. return this;
  29950. };
  29951. ShaderMaterial.prototype.setFloat = function (name, value) {
  29952. this._checkUniform(name);
  29953. this._floats[name] = value;
  29954. return this;
  29955. };
  29956. ShaderMaterial.prototype.setFloats = function (name, value) {
  29957. this._checkUniform(name);
  29958. this._floatsArrays[name] = value;
  29959. return this;
  29960. };
  29961. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29962. this._checkUniform(name);
  29963. this._colors3[name] = value;
  29964. return this;
  29965. };
  29966. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29967. this._checkUniform(name);
  29968. this._colors4[name] = value;
  29969. return this;
  29970. };
  29971. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29972. this._checkUniform(name);
  29973. this._vectors2[name] = value;
  29974. return this;
  29975. };
  29976. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29977. this._checkUniform(name);
  29978. this._vectors3[name] = value;
  29979. return this;
  29980. };
  29981. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29982. this._checkUniform(name);
  29983. this._vectors4[name] = value;
  29984. return this;
  29985. };
  29986. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29987. this._checkUniform(name);
  29988. this._matrices[name] = value;
  29989. return this;
  29990. };
  29991. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29992. this._checkUniform(name);
  29993. this._matrices3x3[name] = value;
  29994. return this;
  29995. };
  29996. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29997. this._checkUniform(name);
  29998. this._matrices2x2[name] = value;
  29999. return this;
  30000. };
  30001. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30002. var scene = this.getScene();
  30003. var engine = scene.getEngine();
  30004. if (!this.checkReadyOnEveryCall) {
  30005. if (this._renderId === scene.getRenderId()) {
  30006. return true;
  30007. }
  30008. }
  30009. // Instances
  30010. var defines = [];
  30011. var fallbacks = new BABYLON.EffectFallbacks();
  30012. if (useInstances) {
  30013. defines.push("#define INSTANCES");
  30014. }
  30015. for (var index = 0; index < this._options.defines.length; index++) {
  30016. defines.push(this._options.defines[index]);
  30017. }
  30018. // Bones
  30019. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30020. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30021. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30022. fallbacks.addCPUSkinningFallback(0, mesh);
  30023. }
  30024. // Alpha test
  30025. if (engine.getAlphaTesting()) {
  30026. defines.push("#define ALPHATEST");
  30027. }
  30028. var previousEffect = this._effect;
  30029. var join = defines.join("\n");
  30030. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30031. if (!this._effect.isReady()) {
  30032. return false;
  30033. }
  30034. if (previousEffect !== this._effect) {
  30035. scene.resetCachedMaterial();
  30036. }
  30037. this._renderId = scene.getRenderId();
  30038. return true;
  30039. };
  30040. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30041. var scene = this.getScene();
  30042. if (this._options.uniforms.indexOf("world") !== -1) {
  30043. this._effect.setMatrix("world", world);
  30044. }
  30045. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30046. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30047. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30048. }
  30049. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30050. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30051. }
  30052. };
  30053. ShaderMaterial.prototype.bind = function (world, mesh) {
  30054. // Std values
  30055. this.bindOnlyWorldMatrix(world);
  30056. if (this.getScene().getCachedMaterial() !== this) {
  30057. if (this._options.uniforms.indexOf("view") !== -1) {
  30058. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30059. }
  30060. if (this._options.uniforms.indexOf("projection") !== -1) {
  30061. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30062. }
  30063. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30064. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30065. }
  30066. // Bones
  30067. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30068. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30069. }
  30070. // Texture
  30071. for (var name in this._textures) {
  30072. this._effect.setTexture(name, this._textures[name]);
  30073. }
  30074. // Float
  30075. for (name in this._floats) {
  30076. this._effect.setFloat(name, this._floats[name]);
  30077. }
  30078. // Float s
  30079. for (name in this._floatsArrays) {
  30080. this._effect.setArray(name, this._floatsArrays[name]);
  30081. }
  30082. // Color3
  30083. for (name in this._colors3) {
  30084. this._effect.setColor3(name, this._colors3[name]);
  30085. }
  30086. // Color4
  30087. for (name in this._colors4) {
  30088. var color = this._colors4[name];
  30089. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30090. }
  30091. // Vector2
  30092. for (name in this._vectors2) {
  30093. this._effect.setVector2(name, this._vectors2[name]);
  30094. }
  30095. // Vector3
  30096. for (name in this._vectors3) {
  30097. this._effect.setVector3(name, this._vectors3[name]);
  30098. }
  30099. // Vector4
  30100. for (name in this._vectors4) {
  30101. this._effect.setVector4(name, this._vectors4[name]);
  30102. }
  30103. // Matrix
  30104. for (name in this._matrices) {
  30105. this._effect.setMatrix(name, this._matrices[name]);
  30106. }
  30107. // Matrix 3x3
  30108. for (name in this._matrices3x3) {
  30109. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30110. }
  30111. // Matrix 2x2
  30112. for (name in this._matrices2x2) {
  30113. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30114. }
  30115. }
  30116. _super.prototype.bind.call(this, world, mesh);
  30117. };
  30118. ShaderMaterial.prototype.clone = function (name) {
  30119. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30120. return newShaderMaterial;
  30121. };
  30122. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30123. for (var name in this._textures) {
  30124. this._textures[name].dispose();
  30125. }
  30126. this._textures = {};
  30127. _super.prototype.dispose.call(this, forceDisposeEffect);
  30128. };
  30129. ShaderMaterial.prototype.serialize = function () {
  30130. var serializationObject = _super.prototype.serialize.call(this);
  30131. serializationObject.options = this._options;
  30132. serializationObject.shaderPath = this._shaderPath;
  30133. serializationObject.customType = "BABYLON.ShaderMaterial";
  30134. // Texture
  30135. serializationObject.textures = {};
  30136. for (var name in this._textures) {
  30137. serializationObject.textures[name] = this._textures[name].serialize();
  30138. }
  30139. // Float
  30140. serializationObject.floats = {};
  30141. for (name in this._floats) {
  30142. serializationObject.floats[name] = this._floats[name];
  30143. }
  30144. // Float s
  30145. serializationObject.floatArrays = {};
  30146. for (name in this._floatsArrays) {
  30147. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30148. }
  30149. // Color3
  30150. serializationObject.colors3 = {};
  30151. for (name in this._colors3) {
  30152. serializationObject.colors3[name] = this._colors3[name].asArray();
  30153. }
  30154. // Color4
  30155. serializationObject.colors4 = {};
  30156. for (name in this._colors4) {
  30157. serializationObject.colors4[name] = this._colors4[name].asArray();
  30158. }
  30159. // Vector2
  30160. serializationObject.vectors2 = {};
  30161. for (name in this._vectors2) {
  30162. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30163. }
  30164. // Vector3
  30165. serializationObject.vectors3 = {};
  30166. for (name in this._vectors3) {
  30167. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30168. }
  30169. // Vector4
  30170. serializationObject.vectors4 = {};
  30171. for (name in this._vectors4) {
  30172. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30173. }
  30174. // Matrix
  30175. serializationObject.matrices = {};
  30176. for (name in this._matrices) {
  30177. serializationObject.matrices[name] = this._matrices[name].asArray();
  30178. }
  30179. // Matrix 3x3
  30180. serializationObject.matrices3x3 = {};
  30181. for (name in this._matrices3x3) {
  30182. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30183. }
  30184. // Matrix 2x2
  30185. serializationObject.matrices2x2 = {};
  30186. for (name in this._matrices2x2) {
  30187. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30188. }
  30189. return serializationObject;
  30190. };
  30191. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30192. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  30193. // Texture
  30194. for (var name in source.textures) {
  30195. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30196. }
  30197. // Float
  30198. for (name in source.floats) {
  30199. material.setFloat(name, source.floats[name]);
  30200. }
  30201. // Float s
  30202. for (name in source.floatsArrays) {
  30203. material.setFloats(name, source.floatsArrays[name]);
  30204. }
  30205. // Color3
  30206. for (name in source.colors3) {
  30207. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30208. }
  30209. // Color4
  30210. for (name in source.colors4) {
  30211. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30212. }
  30213. // Vector2
  30214. for (name in source.vectors2) {
  30215. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30216. }
  30217. // Vector3
  30218. for (name in source.vectors3) {
  30219. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30220. }
  30221. // Vector4
  30222. for (name in source.vectors4) {
  30223. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30224. }
  30225. // Matrix
  30226. for (name in source.matrices) {
  30227. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30228. }
  30229. // Matrix 3x3
  30230. for (name in source.matrices3x3) {
  30231. material.setMatrix3x3(name, source.matrices3x3[name]);
  30232. }
  30233. // Matrix 2x2
  30234. for (name in source.matrices2x2) {
  30235. material.setMatrix2x2(name, source.matrices2x2[name]);
  30236. }
  30237. return material;
  30238. };
  30239. return ShaderMaterial;
  30240. })(BABYLON.Material);
  30241. BABYLON.ShaderMaterial = ShaderMaterial;
  30242. })(BABYLON || (BABYLON = {}));
  30243. var BABYLON;
  30244. (function (BABYLON) {
  30245. var Internals;
  30246. (function (Internals) {
  30247. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30248. // All values and structures referenced from:
  30249. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30250. var DDS_MAGIC = 0x20534444;
  30251. 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;
  30252. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30253. 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;
  30254. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30255. function FourCCToInt32(value) {
  30256. return value.charCodeAt(0) +
  30257. (value.charCodeAt(1) << 8) +
  30258. (value.charCodeAt(2) << 16) +
  30259. (value.charCodeAt(3) << 24);
  30260. }
  30261. function Int32ToFourCC(value) {
  30262. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30263. }
  30264. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30265. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30266. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30267. var headerLengthInt = 31; // The header length in 32 bit ints
  30268. // Offsets into the header array
  30269. var off_magic = 0;
  30270. var off_size = 1;
  30271. var off_flags = 2;
  30272. var off_height = 3;
  30273. var off_width = 4;
  30274. var off_mipmapCount = 7;
  30275. var off_pfFlags = 20;
  30276. var off_pfFourCC = 21;
  30277. var off_RGBbpp = 22;
  30278. var off_RMask = 23;
  30279. var off_GMask = 24;
  30280. var off_BMask = 25;
  30281. var off_AMask = 26;
  30282. var off_caps1 = 27;
  30283. var off_caps2 = 28;
  30284. ;
  30285. var DDSTools = (function () {
  30286. function DDSTools() {
  30287. }
  30288. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30289. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30290. var mipmapCount = 1;
  30291. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30292. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30293. }
  30294. return {
  30295. width: header[off_width],
  30296. height: header[off_height],
  30297. mipmapCount: mipmapCount,
  30298. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30299. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30300. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30301. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30302. };
  30303. };
  30304. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30305. var byteArray = new Uint8Array(dataLength);
  30306. var srcData = new Uint8Array(arrayBuffer);
  30307. var index = 0;
  30308. for (var y = height - 1; y >= 0; y--) {
  30309. for (var x = 0; x < width; x++) {
  30310. var srcPos = dataOffset + (x + y * width) * 4;
  30311. byteArray[index + 2] = srcData[srcPos];
  30312. byteArray[index + 1] = srcData[srcPos + 1];
  30313. byteArray[index] = srcData[srcPos + 2];
  30314. byteArray[index + 3] = srcData[srcPos + 3];
  30315. index += 4;
  30316. }
  30317. }
  30318. return byteArray;
  30319. };
  30320. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30321. var byteArray = new Uint8Array(dataLength);
  30322. var srcData = new Uint8Array(arrayBuffer);
  30323. var index = 0;
  30324. for (var y = height - 1; y >= 0; y--) {
  30325. for (var x = 0; x < width; x++) {
  30326. var srcPos = dataOffset + (x + y * width) * 3;
  30327. byteArray[index + 2] = srcData[srcPos];
  30328. byteArray[index + 1] = srcData[srcPos + 1];
  30329. byteArray[index] = srcData[srcPos + 2];
  30330. index += 3;
  30331. }
  30332. }
  30333. return byteArray;
  30334. };
  30335. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30336. var byteArray = new Uint8Array(dataLength);
  30337. var srcData = new Uint8Array(arrayBuffer);
  30338. var index = 0;
  30339. for (var y = height - 1; y >= 0; y--) {
  30340. for (var x = 0; x < width; x++) {
  30341. var srcPos = dataOffset + (x + y * width);
  30342. byteArray[index] = srcData[srcPos];
  30343. index++;
  30344. }
  30345. }
  30346. return byteArray;
  30347. };
  30348. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30349. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30350. if (header[off_magic] != DDS_MAGIC) {
  30351. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30352. return;
  30353. }
  30354. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30355. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30356. return;
  30357. }
  30358. if (info.isFourCC) {
  30359. fourCC = header[off_pfFourCC];
  30360. switch (fourCC) {
  30361. case FOURCC_DXT1:
  30362. blockBytes = 8;
  30363. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30364. break;
  30365. case FOURCC_DXT3:
  30366. blockBytes = 16;
  30367. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30368. break;
  30369. case FOURCC_DXT5:
  30370. blockBytes = 16;
  30371. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30372. break;
  30373. default:
  30374. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30375. return;
  30376. }
  30377. }
  30378. mipmapCount = 1;
  30379. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30380. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30381. }
  30382. var bpp = header[off_RGBbpp];
  30383. for (var face = 0; face < faces; face++) {
  30384. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30385. width = header[off_width];
  30386. height = header[off_height];
  30387. dataOffset = header[off_size] + 4;
  30388. for (i = 0; i < mipmapCount; ++i) {
  30389. if (info.isRGB) {
  30390. if (bpp === 24) {
  30391. dataLength = width * height * 3;
  30392. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30393. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30394. }
  30395. else {
  30396. dataLength = width * height * 4;
  30397. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30398. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30399. }
  30400. }
  30401. else if (info.isLuminance) {
  30402. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30403. var unpaddedRowSize = width;
  30404. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30405. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30406. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30407. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30408. }
  30409. else {
  30410. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30411. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30412. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30413. }
  30414. dataOffset += dataLength;
  30415. width *= 0.5;
  30416. height *= 0.5;
  30417. width = Math.max(1.0, width);
  30418. height = Math.max(1.0, height);
  30419. }
  30420. }
  30421. };
  30422. return DDSTools;
  30423. })();
  30424. Internals.DDSTools = DDSTools;
  30425. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30426. })(BABYLON || (BABYLON = {}));
  30427. var BABYLON;
  30428. (function (BABYLON) {
  30429. var CannonJSPlugin = (function () {
  30430. function CannonJSPlugin(_useDeltaForWorldStep) {
  30431. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30432. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30433. this._registeredMeshes = [];
  30434. this._physicsMaterials = [];
  30435. this._fixedTimeStep = 1 / 60;
  30436. //private _maxSubSteps : number = 15;
  30437. this.name = "CannonJS";
  30438. this.updateBodyPosition = function (mesh) {
  30439. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30440. var registeredMesh = this._registeredMeshes[index];
  30441. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30442. var body = registeredMesh.body;
  30443. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30444. body.quaternion.copy(mesh.rotationQuaternion);
  30445. if (registeredMesh.deltaRotation) {
  30446. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30447. body.quaternion = body.quaternion.mult(tmpQ);
  30448. }
  30449. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  30450. //calculate the correct body position:
  30451. var rotationQuaternion = mesh.rotationQuaternion;
  30452. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30453. mesh.computeWorldMatrix(true);
  30454. //get original center with no rotation
  30455. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30456. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30457. //rotation is back
  30458. mesh.rotationQuaternion = rotationQuaternion;
  30459. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30460. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30461. mesh.setPivotMatrix(p);
  30462. mesh.computeWorldMatrix(true);
  30463. //calculate the translation
  30464. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30465. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30466. //add it inverted to the delta
  30467. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30468. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30469. mesh.setPivotMatrix(oldPivot);
  30470. mesh.computeWorldMatrix(true);
  30471. }
  30472. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  30473. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  30474. }
  30475. body.position.set(center.x, center.y, center.z);
  30476. return;
  30477. }
  30478. }
  30479. };
  30480. }
  30481. CannonJSPlugin.prototype.initialize = function (iterations) {
  30482. if (iterations === void 0) { iterations = 10; }
  30483. this._world = new CANNON.World();
  30484. this._world.broadphase = new CANNON.NaiveBroadphase();
  30485. this._world.solver.iterations = iterations;
  30486. };
  30487. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30488. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30489. };
  30490. CannonJSPlugin.prototype.runOneStep = function (delta) {
  30491. var _this = this;
  30492. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30493. this._registeredMeshes.forEach(function (registeredMesh) {
  30494. // Body position
  30495. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  30496. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  30497. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  30498. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  30499. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  30500. if (registeredMesh.deltaRotation) {
  30501. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  30502. }
  30503. //is the physics collision callback is set?
  30504. if (registeredMesh.mesh.onPhysicsCollide) {
  30505. if (!registeredMesh.collisionFunction) {
  30506. registeredMesh.collisionFunction = function (e) {
  30507. //find the mesh that collided with the registered mesh
  30508. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  30509. if (_this._registeredMeshes[idx].body == e.body) {
  30510. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  30511. }
  30512. }
  30513. };
  30514. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  30515. }
  30516. }
  30517. else {
  30518. //unregister, in case the function was removed for some reason
  30519. if (registeredMesh.collisionFunction) {
  30520. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  30521. }
  30522. }
  30523. });
  30524. };
  30525. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30526. this._gravity = gravity;
  30527. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  30528. };
  30529. CannonJSPlugin.prototype.getGravity = function () {
  30530. return this._gravity;
  30531. };
  30532. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30533. this.unregisterMesh(mesh);
  30534. if (!mesh.rotationQuaternion) {
  30535. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30536. }
  30537. mesh.computeWorldMatrix(true);
  30538. var shape = this._createShape(mesh, impostor);
  30539. return this._createRigidBodyFromShape(shape, mesh, options);
  30540. };
  30541. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  30542. //get the correct bounding box
  30543. var oldQuaternion = mesh.rotationQuaternion;
  30544. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30545. mesh.computeWorldMatrix(true);
  30546. var returnValue;
  30547. switch (impostor) {
  30548. case BABYLON.PhysicsEngine.SphereImpostor:
  30549. var bbox = mesh.getBoundingInfo().boundingBox;
  30550. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30551. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30552. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30553. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30554. break;
  30555. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30556. case BABYLON.PhysicsEngine.CylinderImpostor:
  30557. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30558. case BABYLON.PhysicsEngine.BoxImpostor:
  30559. bbox = mesh.getBoundingInfo().boundingBox;
  30560. var min = bbox.minimumWorld;
  30561. var max = bbox.maximumWorld;
  30562. var box = max.subtract(min).scale(0.5);
  30563. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30564. break;
  30565. case BABYLON.PhysicsEngine.PlaneImpostor:
  30566. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  30567. returnValue = new CANNON.Plane();
  30568. break;
  30569. case BABYLON.PhysicsEngine.MeshImpostor:
  30570. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30571. var rawFaces = mesh.getIndices();
  30572. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30573. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  30574. break;
  30575. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30576. returnValue = this._createHeightmap(mesh);
  30577. break;
  30578. }
  30579. mesh.rotationQuaternion = oldQuaternion;
  30580. return returnValue;
  30581. };
  30582. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  30583. var verts = [], faces = [];
  30584. mesh.computeWorldMatrix(true);
  30585. //reuse this variable
  30586. var transformed = BABYLON.Vector3.Zero();
  30587. // Get vertices
  30588. for (var i = 0; i < rawVerts.length; i += 3) {
  30589. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  30590. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  30591. }
  30592. // Get faces
  30593. for (var j = 0; j < rawFaces.length; j += 3) {
  30594. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  30595. }
  30596. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  30597. return shape;
  30598. };
  30599. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30600. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30601. var matrix = [];
  30602. //For now pointDepth will not be used and will be automatically calculated.
  30603. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30604. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30605. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30606. var elementSize = dim * 2 / arraySize;
  30607. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30608. for (var i = 0; i < pos.length; i = i + 3) {
  30609. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30610. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30611. var y = pos[i + 1] + minY;
  30612. if (!matrix[x]) {
  30613. matrix[x] = [];
  30614. }
  30615. if (!matrix[x][z]) {
  30616. matrix[x][z] = y;
  30617. }
  30618. matrix[x][z] = Math.max(y, matrix[x][z]);
  30619. }
  30620. for (var x = 0; x <= arraySize; ++x) {
  30621. if (!matrix[x]) {
  30622. var loc = 1;
  30623. while (!matrix[(x + loc) % arraySize]) {
  30624. loc++;
  30625. }
  30626. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30627. }
  30628. for (var z = 0; z <= arraySize; ++z) {
  30629. if (!matrix[x][z]) {
  30630. var loc = 1;
  30631. var newValue;
  30632. while (newValue === undefined) {
  30633. newValue = matrix[x][(z + loc++) % arraySize];
  30634. }
  30635. matrix[x][z] = newValue;
  30636. }
  30637. }
  30638. }
  30639. var shape = new CANNON.Heightfield(matrix, {
  30640. elementSize: elementSize
  30641. });
  30642. //For future reference, needed for body transformation
  30643. shape.minY = minY;
  30644. return shape;
  30645. };
  30646. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30647. var index;
  30648. var mat;
  30649. for (index = 0; index < this._physicsMaterials.length; index++) {
  30650. mat = this._physicsMaterials[index];
  30651. if (mat.friction === friction && mat.restitution === restitution) {
  30652. return mat;
  30653. }
  30654. }
  30655. var currentMat = new CANNON.Material("mat");
  30656. this._physicsMaterials.push(currentMat);
  30657. for (index = 0; index < this._physicsMaterials.length; index++) {
  30658. mat = this._physicsMaterials[index];
  30659. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30660. this._world.addContactMaterial(contactMaterial);
  30661. }
  30662. return currentMat;
  30663. };
  30664. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  30665. if (!mesh.rotationQuaternion) {
  30666. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30667. }
  30668. // The delta between the mesh position and the mesh bounding box center
  30669. var bbox = mesh.getBoundingInfo().boundingBox;
  30670. var deltaPosition = mesh.position.subtract(bbox.center);
  30671. var deltaRotation;
  30672. var material = this._addMaterial(options.friction, options.restitution);
  30673. var body = new CANNON.Body({
  30674. mass: options.mass,
  30675. material: material,
  30676. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  30677. });
  30678. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  30679. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30680. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30681. //-90 DEG in X, precalculated
  30682. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30683. body.quaternion = body.quaternion.mult(tmpQ);
  30684. //Invert! (Precalculated, 90 deg in X)
  30685. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30686. }
  30687. //If it is a heightfield, if should be centered.
  30688. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30689. //calculate the correct body position:
  30690. var rotationQuaternion = mesh.rotationQuaternion;
  30691. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30692. mesh.computeWorldMatrix(true);
  30693. //get original center with no rotation
  30694. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30695. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30696. //rotation is back
  30697. mesh.rotationQuaternion = rotationQuaternion;
  30698. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30699. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30700. mesh.setPivotMatrix(p);
  30701. mesh.computeWorldMatrix(true);
  30702. //calculate the translation
  30703. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30704. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30705. //add it inverted to the delta
  30706. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30707. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30708. mesh.setPivotMatrix(oldPivot);
  30709. mesh.computeWorldMatrix(true);
  30710. }
  30711. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  30712. deltaPosition = BABYLON.Vector3.Zero();
  30713. }
  30714. //add the shape
  30715. body.addShape(shape);
  30716. this._world.add(body);
  30717. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  30718. return body;
  30719. };
  30720. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30721. var initialMesh = parts[0].mesh;
  30722. this.unregisterMesh(initialMesh);
  30723. initialMesh.computeWorldMatrix(true);
  30724. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  30725. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  30726. for (var index = 1; index < parts.length; index++) {
  30727. var mesh = parts[index].mesh;
  30728. mesh.computeWorldMatrix(true);
  30729. var shape = this._createShape(mesh, parts[index].impostor);
  30730. var localPosition = mesh.position;
  30731. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30732. }
  30733. return body;
  30734. };
  30735. CannonJSPlugin.prototype._unbindBody = function (body) {
  30736. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30737. var registeredMesh = this._registeredMeshes[index];
  30738. if (registeredMesh.body === body) {
  30739. this._world.remove(registeredMesh.body);
  30740. registeredMesh.body = null;
  30741. registeredMesh.delta = null;
  30742. registeredMesh.deltaRotation = null;
  30743. }
  30744. }
  30745. };
  30746. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30747. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30748. var registeredMesh = this._registeredMeshes[index];
  30749. if (registeredMesh.mesh === mesh) {
  30750. // Remove body
  30751. if (registeredMesh.body) {
  30752. this._unbindBody(registeredMesh.body);
  30753. }
  30754. this._registeredMeshes.splice(index, 1);
  30755. return;
  30756. }
  30757. }
  30758. };
  30759. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30760. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30761. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30762. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30763. var registeredMesh = this._registeredMeshes[index];
  30764. if (registeredMesh.mesh === mesh) {
  30765. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30766. return;
  30767. }
  30768. }
  30769. };
  30770. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30771. var body1 = null, body2 = null;
  30772. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30773. var registeredMesh = this._registeredMeshes[index];
  30774. if (registeredMesh.mesh === mesh1) {
  30775. body1 = registeredMesh.body;
  30776. if (body2)
  30777. break;
  30778. }
  30779. else if (registeredMesh.mesh === mesh2) {
  30780. body2 = registeredMesh.body;
  30781. if (body1)
  30782. break;
  30783. }
  30784. }
  30785. if (!body1 || !body2) {
  30786. return false;
  30787. }
  30788. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  30789. this._world.addConstraint(constraint);
  30790. return true;
  30791. };
  30792. CannonJSPlugin.prototype.dispose = function () {
  30793. while (this._registeredMeshes.length) {
  30794. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30795. }
  30796. };
  30797. CannonJSPlugin.prototype.isSupported = function () {
  30798. return window.CANNON !== undefined;
  30799. };
  30800. CannonJSPlugin.prototype.getWorldObject = function () {
  30801. return this._world;
  30802. };
  30803. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30804. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30805. var registeredMesh = this._registeredMeshes[index];
  30806. if (registeredMesh.mesh === mesh) {
  30807. return registeredMesh.body;
  30808. }
  30809. }
  30810. return null;
  30811. };
  30812. return CannonJSPlugin;
  30813. })();
  30814. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30815. })(BABYLON || (BABYLON = {}));
  30816. var BABYLON;
  30817. (function (BABYLON) {
  30818. var OimoJSPlugin = (function () {
  30819. function OimoJSPlugin() {
  30820. this._registeredMeshes = [];
  30821. this.name = "oimo";
  30822. /**
  30823. * Update the body position according to the mesh position
  30824. * @param mesh
  30825. */
  30826. this.updateBodyPosition = function (mesh) {
  30827. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30828. var registeredMesh = this._registeredMeshes[index];
  30829. var body = registeredMesh.body.body;
  30830. var updated = false;
  30831. var newPosition;
  30832. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30833. mesh.computeWorldMatrix(true);
  30834. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30835. updated = true;
  30836. }
  30837. else if (registeredMesh.mesh.parent === mesh) {
  30838. mesh.computeWorldMatrix(true);
  30839. registeredMesh.mesh.computeWorldMatrix(true);
  30840. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30841. updated = true;
  30842. }
  30843. if (updated) {
  30844. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30845. body.setQuaternion(mesh.rotationQuaternion);
  30846. body.sleeping = false;
  30847. //force Oimo to update the body's position
  30848. body.updatePosition(1);
  30849. }
  30850. }
  30851. };
  30852. }
  30853. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30854. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30855. };
  30856. OimoJSPlugin.prototype.initialize = function (iterations) {
  30857. this._world = new OIMO.World(null, null, iterations);
  30858. this._world.clear();
  30859. };
  30860. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30861. this._gravity = this._world.gravity = gravity;
  30862. };
  30863. OimoJSPlugin.prototype.getGravity = function () {
  30864. return this._gravity;
  30865. };
  30866. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30867. this.unregisterMesh(mesh);
  30868. if (!mesh.rotationQuaternion) {
  30869. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30870. }
  30871. mesh.computeWorldMatrix(true);
  30872. var bbox = mesh.getBoundingInfo().boundingBox;
  30873. // The delta between the mesh position and the mesh bounding box center
  30874. var deltaPosition = mesh.position.subtract(bbox.center);
  30875. //calculate rotation to fit Oimo's needs (Euler...)
  30876. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30877. //get the correct bounding box
  30878. var oldQuaternion = mesh.rotationQuaternion;
  30879. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30880. mesh.computeWorldMatrix(true);
  30881. var bodyConfig = {
  30882. name: mesh.uniqueId,
  30883. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30884. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30885. move: options.mass != 0,
  30886. config: [options.mass, options.friction, options.restitution],
  30887. world: this._world
  30888. };
  30889. // register mesh
  30890. switch (impostor) {
  30891. case BABYLON.PhysicsEngine.SphereImpostor:
  30892. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30893. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30894. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30895. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30896. bodyConfig.type = 'sphere';
  30897. bodyConfig.size = [size];
  30898. break;
  30899. case BABYLON.PhysicsEngine.PlaneImpostor:
  30900. //Oimo "fakes" a cylinder as a box, so why don't we!
  30901. case BABYLON.PhysicsEngine.CylinderImpostor:
  30902. case BABYLON.PhysicsEngine.BoxImpostor:
  30903. var min = bbox.minimumWorld;
  30904. var max = bbox.maximumWorld;
  30905. var box = max.subtract(min);
  30906. var sizeX = this._checkWithEpsilon(box.x);
  30907. var sizeY = this._checkWithEpsilon(box.y);
  30908. var sizeZ = this._checkWithEpsilon(box.z);
  30909. bodyConfig.type = 'box';
  30910. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30911. break;
  30912. }
  30913. var body = new OIMO.Body(bodyConfig);
  30914. //We have to access the rigid body's properties to set the quaternion.
  30915. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30916. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30917. //TEST
  30918. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30919. //update the internal rotation matrix
  30920. //body.body.syncShapes();
  30921. this._registeredMeshes.push({
  30922. mesh: mesh,
  30923. body: body,
  30924. delta: deltaPosition
  30925. });
  30926. //for the sake of consistency.
  30927. mesh.rotationQuaternion = oldQuaternion;
  30928. return body;
  30929. };
  30930. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30931. var types = [], sizes = [], positions = [], rotations = [];
  30932. var initialMesh = parts[0].mesh;
  30933. for (var index = 0; index < parts.length; index++) {
  30934. var part = parts[index];
  30935. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30936. types.push(bodyParameters.type);
  30937. sizes.push.apply(sizes, bodyParameters.size);
  30938. positions.push.apply(positions, bodyParameters.pos);
  30939. rotations.push.apply(rotations, bodyParameters.rot);
  30940. }
  30941. var body = new OIMO.Body({
  30942. name: initialMesh.uniqueId,
  30943. type: types,
  30944. size: sizes,
  30945. pos: positions,
  30946. rot: rotations,
  30947. move: options.mass != 0,
  30948. config: [options.mass, options.friction, options.restitution],
  30949. world: this._world
  30950. });
  30951. //Reset the body's rotation to be of the initial mesh's.
  30952. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30953. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30954. this._registeredMeshes.push({
  30955. mesh: initialMesh,
  30956. body: body
  30957. });
  30958. return body;
  30959. };
  30960. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30961. var mesh = part.mesh;
  30962. if (!mesh.rotationQuaternion) {
  30963. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30964. }
  30965. // We need the bounding box/sphere info to compute the physics body
  30966. mesh.computeWorldMatrix(true);
  30967. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30968. var bodyParameters = {
  30969. name: mesh.uniqueId,
  30970. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30971. //A bug in Oimo (Body class) prevents us from using rot directly.
  30972. rot: [0, 0, 0],
  30973. //For future reference, if the bug will ever be fixed.
  30974. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30975. };
  30976. var oldQuaternion = mesh.rotationQuaternion;
  30977. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30978. mesh.computeWorldMatrix(true);
  30979. switch (part.impostor) {
  30980. case BABYLON.PhysicsEngine.SphereImpostor:
  30981. var bbox = mesh.getBoundingInfo().boundingBox;
  30982. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30983. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30984. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30985. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30986. bodyParameters.type = 'sphere';
  30987. bodyParameters.size = [size, size, size];
  30988. break;
  30989. case BABYLON.PhysicsEngine.PlaneImpostor:
  30990. case BABYLON.PhysicsEngine.CylinderImpostor:
  30991. case BABYLON.PhysicsEngine.BoxImpostor:
  30992. bbox = mesh.getBoundingInfo().boundingBox;
  30993. var min = bbox.minimumWorld;
  30994. var max = bbox.maximumWorld;
  30995. var box = max.subtract(min);
  30996. var sizeX = this._checkWithEpsilon(box.x);
  30997. var sizeY = this._checkWithEpsilon(box.y);
  30998. var sizeZ = this._checkWithEpsilon(box.z);
  30999. bodyParameters.type = 'box';
  31000. bodyParameters.size = [sizeX, sizeY, sizeZ];
  31001. break;
  31002. }
  31003. mesh.rotationQuaternion = oldQuaternion;
  31004. return bodyParameters;
  31005. };
  31006. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  31007. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31008. var registeredMesh = this._registeredMeshes[index];
  31009. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  31010. if (registeredMesh.body) {
  31011. this._world.removeRigidBody(registeredMesh.body.body);
  31012. this._unbindBody(registeredMesh.body);
  31013. }
  31014. this._registeredMeshes.splice(index, 1);
  31015. return;
  31016. }
  31017. }
  31018. };
  31019. OimoJSPlugin.prototype._unbindBody = function (body) {
  31020. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31021. var registeredMesh = this._registeredMeshes[index];
  31022. if (registeredMesh.body === body) {
  31023. registeredMesh.body = null;
  31024. }
  31025. }
  31026. };
  31027. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  31028. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31029. var registeredMesh = this._registeredMeshes[index];
  31030. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  31031. // Get object mass to have a behaviour similar to cannon.js
  31032. var mass = registeredMesh.body.body.massInfo.mass;
  31033. // The force is scaled with the mass of object
  31034. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31035. return;
  31036. }
  31037. }
  31038. };
  31039. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  31040. var body1 = null, body2 = null;
  31041. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31042. var registeredMesh = this._registeredMeshes[index];
  31043. if (registeredMesh.mesh === mesh1) {
  31044. body1 = registeredMesh.body.body;
  31045. }
  31046. else if (registeredMesh.mesh === mesh2) {
  31047. body2 = registeredMesh.body.body;
  31048. }
  31049. }
  31050. if (!body1 || !body2) {
  31051. return false;
  31052. }
  31053. if (!options) {
  31054. options = {};
  31055. }
  31056. new OIMO.Link({
  31057. type: options.type,
  31058. body1: body1,
  31059. body2: body2,
  31060. min: options.min,
  31061. max: options.max,
  31062. axe1: options.axe1,
  31063. axe2: options.axe2,
  31064. pos1: [pivot1.x, pivot1.y, pivot1.z],
  31065. pos2: [pivot2.x, pivot2.y, pivot2.z],
  31066. collision: options.collision,
  31067. spring: options.spring,
  31068. world: this._world
  31069. });
  31070. return true;
  31071. };
  31072. OimoJSPlugin.prototype.dispose = function () {
  31073. this._world.clear();
  31074. while (this._registeredMeshes.length) {
  31075. this.unregisterMesh(this._registeredMeshes[0].mesh);
  31076. }
  31077. };
  31078. OimoJSPlugin.prototype.isSupported = function () {
  31079. return OIMO !== undefined;
  31080. };
  31081. OimoJSPlugin.prototype.getWorldObject = function () {
  31082. return this._world;
  31083. };
  31084. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  31085. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31086. var registeredMesh = this._registeredMeshes[index];
  31087. if (registeredMesh.mesh === mesh) {
  31088. return registeredMesh.body;
  31089. }
  31090. }
  31091. return null;
  31092. };
  31093. OimoJSPlugin.prototype._getLastShape = function (body) {
  31094. var lastShape = body.shapes;
  31095. while (lastShape.next) {
  31096. lastShape = lastShape.next;
  31097. }
  31098. return lastShape;
  31099. };
  31100. OimoJSPlugin.prototype.runOneStep = function (time) {
  31101. this._world.step();
  31102. // Update the position of all registered meshes
  31103. var i = this._registeredMeshes.length;
  31104. var m;
  31105. while (i--) {
  31106. var body = this._registeredMeshes[i].body.body;
  31107. var mesh = this._registeredMeshes[i].mesh;
  31108. if (!this._registeredMeshes[i].delta) {
  31109. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  31110. }
  31111. if (!body.sleeping) {
  31112. //TODO check that
  31113. if (body.shapes.next) {
  31114. var parentShape = this._getLastShape(body);
  31115. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31116. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31117. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31118. }
  31119. else {
  31120. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  31121. }
  31122. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  31123. mesh.computeWorldMatrix();
  31124. }
  31125. //check if the collide callback is set.
  31126. if (mesh.onPhysicsCollide) {
  31127. var meshUniqueName = mesh.uniqueId;
  31128. var contact = this._world.contacts;
  31129. while (contact !== null) {
  31130. //is this body colliding with any other?
  31131. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31132. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  31133. //get the mesh and execute the callback
  31134. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  31135. if (otherMesh)
  31136. mesh.onPhysicsCollide(otherMesh, contact);
  31137. }
  31138. contact = contact.next;
  31139. }
  31140. }
  31141. }
  31142. };
  31143. return OimoJSPlugin;
  31144. })();
  31145. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31146. })(BABYLON || (BABYLON = {}));
  31147. var BABYLON;
  31148. (function (BABYLON) {
  31149. var DisplayPassPostProcess = (function (_super) {
  31150. __extends(DisplayPassPostProcess, _super);
  31151. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31152. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31153. }
  31154. return DisplayPassPostProcess;
  31155. })(BABYLON.PostProcess);
  31156. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31157. })(BABYLON || (BABYLON = {}));
  31158. var BABYLON;
  31159. (function (BABYLON) {
  31160. var SimplificationSettings = (function () {
  31161. function SimplificationSettings(quality, distance, optimizeMesh) {
  31162. this.quality = quality;
  31163. this.distance = distance;
  31164. this.optimizeMesh = optimizeMesh;
  31165. }
  31166. return SimplificationSettings;
  31167. })();
  31168. BABYLON.SimplificationSettings = SimplificationSettings;
  31169. var SimplificationQueue = (function () {
  31170. function SimplificationQueue() {
  31171. this.running = false;
  31172. this._simplificationArray = [];
  31173. }
  31174. SimplificationQueue.prototype.addTask = function (task) {
  31175. this._simplificationArray.push(task);
  31176. };
  31177. SimplificationQueue.prototype.executeNext = function () {
  31178. var task = this._simplificationArray.pop();
  31179. if (task) {
  31180. this.running = true;
  31181. this.runSimplification(task);
  31182. }
  31183. else {
  31184. this.running = false;
  31185. }
  31186. };
  31187. SimplificationQueue.prototype.runSimplification = function (task) {
  31188. var _this = this;
  31189. if (task.parallelProcessing) {
  31190. //parallel simplifier
  31191. task.settings.forEach(function (setting) {
  31192. var simplifier = _this.getSimplifier(task);
  31193. simplifier.simplify(setting, function (newMesh) {
  31194. task.mesh.addLODLevel(setting.distance, newMesh);
  31195. newMesh.isVisible = true;
  31196. //check if it is the last
  31197. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31198. //all done, run the success callback.
  31199. task.successCallback();
  31200. }
  31201. _this.executeNext();
  31202. });
  31203. });
  31204. }
  31205. else {
  31206. //single simplifier.
  31207. var simplifier = this.getSimplifier(task);
  31208. var runDecimation = function (setting, callback) {
  31209. simplifier.simplify(setting, function (newMesh) {
  31210. task.mesh.addLODLevel(setting.distance, newMesh);
  31211. newMesh.isVisible = true;
  31212. //run the next quality level
  31213. callback();
  31214. });
  31215. };
  31216. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31217. runDecimation(task.settings[loop.index], function () {
  31218. loop.executeNext();
  31219. });
  31220. }, function () {
  31221. //execution ended, run the success callback.
  31222. if (task.successCallback) {
  31223. task.successCallback();
  31224. }
  31225. _this.executeNext();
  31226. });
  31227. }
  31228. };
  31229. SimplificationQueue.prototype.getSimplifier = function (task) {
  31230. switch (task.simplificationType) {
  31231. case SimplificationType.QUADRATIC:
  31232. default:
  31233. return new QuadraticErrorSimplification(task.mesh);
  31234. }
  31235. };
  31236. return SimplificationQueue;
  31237. })();
  31238. BABYLON.SimplificationQueue = SimplificationQueue;
  31239. /**
  31240. * The implemented types of simplification.
  31241. * At the moment only Quadratic Error Decimation is implemented.
  31242. */
  31243. (function (SimplificationType) {
  31244. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31245. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31246. var SimplificationType = BABYLON.SimplificationType;
  31247. var DecimationTriangle = (function () {
  31248. function DecimationTriangle(vertices) {
  31249. this.vertices = vertices;
  31250. this.error = new Array(4);
  31251. this.deleted = false;
  31252. this.isDirty = false;
  31253. this.deletePending = false;
  31254. this.borderFactor = 0;
  31255. }
  31256. return DecimationTriangle;
  31257. })();
  31258. BABYLON.DecimationTriangle = DecimationTriangle;
  31259. var DecimationVertex = (function () {
  31260. function DecimationVertex(position, id) {
  31261. this.position = position;
  31262. this.id = id;
  31263. this.isBorder = true;
  31264. this.q = new QuadraticMatrix();
  31265. this.triangleCount = 0;
  31266. this.triangleStart = 0;
  31267. this.originalOffsets = [];
  31268. }
  31269. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31270. this.position.copyFrom(newPosition);
  31271. };
  31272. return DecimationVertex;
  31273. })();
  31274. BABYLON.DecimationVertex = DecimationVertex;
  31275. var QuadraticMatrix = (function () {
  31276. function QuadraticMatrix(data) {
  31277. this.data = new Array(10);
  31278. for (var i = 0; i < 10; ++i) {
  31279. if (data && data[i]) {
  31280. this.data[i] = data[i];
  31281. }
  31282. else {
  31283. this.data[i] = 0;
  31284. }
  31285. }
  31286. }
  31287. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31288. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31289. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31290. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31291. return det;
  31292. };
  31293. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31294. for (var i = 0; i < 10; ++i) {
  31295. this.data[i] += matrix.data[i];
  31296. }
  31297. };
  31298. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31299. for (var i = 0; i < 10; ++i) {
  31300. this.data[i] += data[i];
  31301. }
  31302. };
  31303. QuadraticMatrix.prototype.add = function (matrix) {
  31304. var m = new QuadraticMatrix();
  31305. for (var i = 0; i < 10; ++i) {
  31306. m.data[i] = this.data[i] + matrix.data[i];
  31307. }
  31308. return m;
  31309. };
  31310. QuadraticMatrix.FromData = function (a, b, c, d) {
  31311. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31312. };
  31313. //returning an array to avoid garbage collection
  31314. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31315. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31316. };
  31317. return QuadraticMatrix;
  31318. })();
  31319. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31320. var Reference = (function () {
  31321. function Reference(vertexId, triangleId) {
  31322. this.vertexId = vertexId;
  31323. this.triangleId = triangleId;
  31324. }
  31325. return Reference;
  31326. })();
  31327. BABYLON.Reference = Reference;
  31328. /**
  31329. * An implementation of the Quadratic Error simplification algorithm.
  31330. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31331. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31332. * @author RaananW
  31333. */
  31334. var QuadraticErrorSimplification = (function () {
  31335. function QuadraticErrorSimplification(_mesh) {
  31336. this._mesh = _mesh;
  31337. this.initialized = false;
  31338. this.syncIterations = 5000;
  31339. this.aggressiveness = 7;
  31340. this.decimationIterations = 100;
  31341. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31342. }
  31343. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31344. var _this = this;
  31345. this.initDecimatedMesh();
  31346. //iterating through the submeshes array, one after the other.
  31347. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31348. _this.initWithMesh(loop.index, function () {
  31349. _this.runDecimation(settings, loop.index, function () {
  31350. loop.executeNext();
  31351. });
  31352. }, settings.optimizeMesh);
  31353. }, function () {
  31354. setTimeout(function () {
  31355. successCallback(_this._reconstructedMesh);
  31356. }, 0);
  31357. });
  31358. };
  31359. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31360. var _this = this;
  31361. var gCount = 0;
  31362. triangle.vertices.forEach(function (vertex) {
  31363. var count = 0;
  31364. var vPos = vertex.position;
  31365. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31366. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31367. ++count;
  31368. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31369. ++count;
  31370. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31371. ++count;
  31372. if (count > 1) {
  31373. ++gCount;
  31374. }
  31375. ;
  31376. });
  31377. if (gCount > 1) {
  31378. console.log(triangle, gCount);
  31379. }
  31380. return gCount > 1;
  31381. };
  31382. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31383. var _this = this;
  31384. var targetCount = ~~(this.triangles.length * settings.quality);
  31385. var deletedTriangles = 0;
  31386. var triangleCount = this.triangles.length;
  31387. var iterationFunction = function (iteration, callback) {
  31388. setTimeout(function () {
  31389. if (iteration % 5 === 0) {
  31390. _this.updateMesh(iteration === 0);
  31391. }
  31392. for (var i = 0; i < _this.triangles.length; ++i) {
  31393. _this.triangles[i].isDirty = false;
  31394. }
  31395. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31396. var trianglesIterator = function (i) {
  31397. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31398. var t = _this.triangles[tIdx];
  31399. if (!t)
  31400. return;
  31401. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31402. return;
  31403. }
  31404. for (var j = 0; j < 3; ++j) {
  31405. if (t.error[j] < threshold) {
  31406. var deleted0 = [];
  31407. var deleted1 = [];
  31408. var v0 = t.vertices[j];
  31409. var v1 = t.vertices[(j + 1) % 3];
  31410. if (v0.isBorder !== v1.isBorder)
  31411. continue;
  31412. var p = BABYLON.Vector3.Zero();
  31413. var n = BABYLON.Vector3.Zero();
  31414. var uv = BABYLON.Vector2.Zero();
  31415. var color = new BABYLON.Color4(0, 0, 0, 1);
  31416. _this.calculateError(v0, v1, p, n, uv, color);
  31417. var delTr = [];
  31418. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31419. continue;
  31420. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31421. continue;
  31422. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31423. continue;
  31424. var uniqueArray = [];
  31425. delTr.forEach(function (deletedT) {
  31426. if (uniqueArray.indexOf(deletedT) === -1) {
  31427. deletedT.deletePending = true;
  31428. uniqueArray.push(deletedT);
  31429. }
  31430. });
  31431. if (uniqueArray.length % 2 !== 0) {
  31432. continue;
  31433. }
  31434. v0.q = v1.q.add(v0.q);
  31435. v0.updatePosition(p);
  31436. var tStart = _this.references.length;
  31437. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31438. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31439. var tCount = _this.references.length - tStart;
  31440. if (tCount <= v0.triangleCount) {
  31441. if (tCount) {
  31442. for (var c = 0; c < tCount; c++) {
  31443. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31444. }
  31445. }
  31446. }
  31447. else {
  31448. v0.triangleStart = tStart;
  31449. }
  31450. v0.triangleCount = tCount;
  31451. break;
  31452. }
  31453. }
  31454. };
  31455. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31456. }, 0);
  31457. };
  31458. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31459. if (triangleCount - deletedTriangles <= targetCount)
  31460. loop.breakLoop();
  31461. else {
  31462. iterationFunction(loop.index, function () {
  31463. loop.executeNext();
  31464. });
  31465. }
  31466. }, function () {
  31467. setTimeout(function () {
  31468. //reconstruct this part of the mesh
  31469. _this.reconstructMesh(submeshIndex);
  31470. successCallback();
  31471. }, 0);
  31472. });
  31473. };
  31474. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31475. var _this = this;
  31476. this.vertices = [];
  31477. this.triangles = [];
  31478. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31479. var indices = this._mesh.getIndices();
  31480. var submesh = this._mesh.subMeshes[submeshIndex];
  31481. var findInVertices = function (positionToSearch) {
  31482. if (optimizeMesh) {
  31483. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31484. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31485. return _this.vertices[ii];
  31486. }
  31487. }
  31488. }
  31489. return null;
  31490. };
  31491. var vertexReferences = [];
  31492. var vertexInit = function (i) {
  31493. var offset = i + submesh.verticesStart;
  31494. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31495. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31496. vertex.originalOffsets.push(offset);
  31497. if (vertex.id === _this.vertices.length) {
  31498. _this.vertices.push(vertex);
  31499. }
  31500. vertexReferences.push(vertex.id);
  31501. };
  31502. //var totalVertices = mesh.getTotalVertices();
  31503. var totalVertices = submesh.verticesCount;
  31504. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31505. var indicesInit = function (i) {
  31506. var offset = (submesh.indexStart / 3) + i;
  31507. var pos = (offset * 3);
  31508. var i0 = indices[pos + 0];
  31509. var i1 = indices[pos + 1];
  31510. var i2 = indices[pos + 2];
  31511. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31512. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31513. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31514. var triangle = new DecimationTriangle([v0, v1, v2]);
  31515. triangle.originalOffset = pos;
  31516. _this.triangles.push(triangle);
  31517. };
  31518. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31519. _this.init(callback);
  31520. });
  31521. });
  31522. };
  31523. QuadraticErrorSimplification.prototype.init = function (callback) {
  31524. var _this = this;
  31525. var triangleInit1 = function (i) {
  31526. var t = _this.triangles[i];
  31527. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31528. for (var j = 0; j < 3; j++) {
  31529. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  31530. }
  31531. };
  31532. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31533. var triangleInit2 = function (i) {
  31534. var t = _this.triangles[i];
  31535. for (var j = 0; j < 3; ++j) {
  31536. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31537. }
  31538. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31539. };
  31540. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31541. _this.initialized = true;
  31542. callback();
  31543. });
  31544. });
  31545. };
  31546. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31547. var newTriangles = [];
  31548. var i;
  31549. for (i = 0; i < this.vertices.length; ++i) {
  31550. this.vertices[i].triangleCount = 0;
  31551. }
  31552. var t;
  31553. var j;
  31554. for (i = 0; i < this.triangles.length; ++i) {
  31555. if (!this.triangles[i].deleted) {
  31556. t = this.triangles[i];
  31557. for (j = 0; j < 3; ++j) {
  31558. t.vertices[j].triangleCount = 1;
  31559. }
  31560. newTriangles.push(t);
  31561. }
  31562. }
  31563. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31564. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31565. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31566. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31567. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31568. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31569. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31570. var vertexCount = 0;
  31571. for (i = 0; i < this.vertices.length; ++i) {
  31572. var vertex = this.vertices[i];
  31573. vertex.id = vertexCount;
  31574. if (vertex.triangleCount) {
  31575. vertex.originalOffsets.forEach(function (originalOffset) {
  31576. newPositionData.push(vertex.position.x);
  31577. newPositionData.push(vertex.position.y);
  31578. newPositionData.push(vertex.position.z);
  31579. newNormalData.push(normalData[originalOffset * 3]);
  31580. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31581. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31582. if (uvs && uvs.length) {
  31583. newUVsData.push(uvs[(originalOffset * 2)]);
  31584. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31585. }
  31586. else if (colorsData && colorsData.length) {
  31587. newColorsData.push(colorsData[(originalOffset * 4)]);
  31588. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31589. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31590. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31591. }
  31592. ++vertexCount;
  31593. });
  31594. }
  31595. }
  31596. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31597. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31598. var submeshesArray = this._reconstructedMesh.subMeshes;
  31599. this._reconstructedMesh.subMeshes = [];
  31600. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31601. var originalIndices = this._mesh.getIndices();
  31602. for (i = 0; i < newTriangles.length; ++i) {
  31603. t = newTriangles[i]; //now get the new referencing point for each vertex
  31604. [0, 1, 2].forEach(function (idx) {
  31605. var id = originalIndices[t.originalOffset + idx];
  31606. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31607. if (offset < 0)
  31608. offset = 0;
  31609. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31610. });
  31611. }
  31612. //overwriting the old vertex buffers and indices.
  31613. this._reconstructedMesh.setIndices(newIndicesArray);
  31614. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31615. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31616. if (newUVsData.length > 0)
  31617. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31618. if (newColorsData.length > 0)
  31619. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31620. //create submesh
  31621. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31622. if (submeshIndex > 0) {
  31623. this._reconstructedMesh.subMeshes = [];
  31624. submeshesArray.forEach(function (submesh) {
  31625. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31626. });
  31627. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31628. }
  31629. };
  31630. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31631. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31632. this._reconstructedMesh.material = this._mesh.material;
  31633. this._reconstructedMesh.parent = this._mesh.parent;
  31634. this._reconstructedMesh.isVisible = false;
  31635. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31636. };
  31637. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31638. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31639. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31640. if (t.deleted)
  31641. continue;
  31642. var s = this.references[vertex1.triangleStart + i].vertexId;
  31643. var v1 = t.vertices[(s + 1) % 3];
  31644. var v2 = t.vertices[(s + 2) % 3];
  31645. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31646. deletedArray[i] = true;
  31647. delTr.push(t);
  31648. continue;
  31649. }
  31650. var d1 = v1.position.subtract(point);
  31651. d1 = d1.normalize();
  31652. var d2 = v2.position.subtract(point);
  31653. d2 = d2.normalize();
  31654. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31655. return true;
  31656. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31657. deletedArray[i] = false;
  31658. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31659. return true;
  31660. }
  31661. return false;
  31662. };
  31663. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31664. var newDeleted = deletedTriangles;
  31665. for (var i = 0; i < vertex.triangleCount; ++i) {
  31666. var ref = this.references[vertex.triangleStart + i];
  31667. var t = this.triangles[ref.triangleId];
  31668. if (t.deleted)
  31669. continue;
  31670. if (deletedArray[i] && t.deletePending) {
  31671. t.deleted = true;
  31672. newDeleted++;
  31673. continue;
  31674. }
  31675. t.vertices[ref.vertexId] = origVertex;
  31676. t.isDirty = true;
  31677. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31678. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31679. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31680. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31681. this.references.push(ref);
  31682. }
  31683. return newDeleted;
  31684. };
  31685. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31686. for (var i = 0; i < this.vertices.length; ++i) {
  31687. var vCount = [];
  31688. var vId = [];
  31689. var v = this.vertices[i];
  31690. var j;
  31691. for (j = 0; j < v.triangleCount; ++j) {
  31692. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31693. for (var ii = 0; ii < 3; ii++) {
  31694. var ofs = 0;
  31695. var vv = triangle.vertices[ii];
  31696. while (ofs < vCount.length) {
  31697. if (vId[ofs] === vv.id)
  31698. break;
  31699. ++ofs;
  31700. }
  31701. if (ofs === vCount.length) {
  31702. vCount.push(1);
  31703. vId.push(vv.id);
  31704. }
  31705. else {
  31706. vCount[ofs]++;
  31707. }
  31708. }
  31709. }
  31710. for (j = 0; j < vCount.length; ++j) {
  31711. if (vCount[j] === 1) {
  31712. this.vertices[vId[j]].isBorder = true;
  31713. }
  31714. else {
  31715. this.vertices[vId[j]].isBorder = false;
  31716. }
  31717. }
  31718. }
  31719. };
  31720. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31721. if (identifyBorders === void 0) { identifyBorders = false; }
  31722. var i;
  31723. if (!identifyBorders) {
  31724. var newTrianglesVector = [];
  31725. for (i = 0; i < this.triangles.length; ++i) {
  31726. if (!this.triangles[i].deleted) {
  31727. newTrianglesVector.push(this.triangles[i]);
  31728. }
  31729. }
  31730. this.triangles = newTrianglesVector;
  31731. }
  31732. for (i = 0; i < this.vertices.length; ++i) {
  31733. this.vertices[i].triangleCount = 0;
  31734. this.vertices[i].triangleStart = 0;
  31735. }
  31736. var t;
  31737. var j;
  31738. var v;
  31739. for (i = 0; i < this.triangles.length; ++i) {
  31740. t = this.triangles[i];
  31741. for (j = 0; j < 3; ++j) {
  31742. v = t.vertices[j];
  31743. v.triangleCount++;
  31744. }
  31745. }
  31746. var tStart = 0;
  31747. for (i = 0; i < this.vertices.length; ++i) {
  31748. this.vertices[i].triangleStart = tStart;
  31749. tStart += this.vertices[i].triangleCount;
  31750. this.vertices[i].triangleCount = 0;
  31751. }
  31752. var newReferences = new Array(this.triangles.length * 3);
  31753. for (i = 0; i < this.triangles.length; ++i) {
  31754. t = this.triangles[i];
  31755. for (j = 0; j < 3; ++j) {
  31756. v = t.vertices[j];
  31757. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31758. v.triangleCount++;
  31759. }
  31760. }
  31761. this.references = newReferences;
  31762. if (identifyBorders) {
  31763. this.identifyBorder();
  31764. }
  31765. };
  31766. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31767. var x = point.x;
  31768. var y = point.y;
  31769. var z = point.z;
  31770. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  31771. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31772. };
  31773. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31774. var q = vertex1.q.add(vertex2.q);
  31775. var border = vertex1.isBorder && vertex2.isBorder;
  31776. var error = 0;
  31777. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31778. if (qDet !== 0 && !border) {
  31779. if (!pointResult) {
  31780. pointResult = BABYLON.Vector3.Zero();
  31781. }
  31782. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31783. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31784. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31785. error = this.vertexError(q, pointResult);
  31786. }
  31787. else {
  31788. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31789. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31790. var error1 = this.vertexError(q, vertex1.position);
  31791. var error2 = this.vertexError(q, vertex2.position);
  31792. var error3 = this.vertexError(q, p3);
  31793. error = Math.min(error1, error2, error3);
  31794. if (error === error1) {
  31795. if (pointResult) {
  31796. pointResult.copyFrom(vertex1.position);
  31797. }
  31798. }
  31799. else if (error === error2) {
  31800. if (pointResult) {
  31801. pointResult.copyFrom(vertex2.position);
  31802. }
  31803. }
  31804. else {
  31805. if (pointResult) {
  31806. pointResult.copyFrom(p3);
  31807. }
  31808. }
  31809. }
  31810. return error;
  31811. };
  31812. return QuadraticErrorSimplification;
  31813. })();
  31814. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31815. })(BABYLON || (BABYLON = {}));
  31816. var BABYLON;
  31817. (function (BABYLON) {
  31818. var serializedGeometries = [];
  31819. var serializeGeometry = function (geometry, serializationGeometries) {
  31820. if (serializedGeometries[geometry.id]) {
  31821. return;
  31822. }
  31823. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31824. serializationGeometries.boxes.push(geometry.serialize());
  31825. }
  31826. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31827. serializationGeometries.spheres.push(geometry.serialize());
  31828. }
  31829. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31830. serializationGeometries.cylinders.push(geometry.serialize());
  31831. }
  31832. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31833. serializationGeometries.toruses.push(geometry.serialize());
  31834. }
  31835. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31836. serializationGeometries.grounds.push(geometry.serialize());
  31837. }
  31838. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31839. serializationGeometries.planes.push(geometry.serialize());
  31840. }
  31841. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31842. serializationGeometries.torusKnots.push(geometry.serialize());
  31843. }
  31844. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31845. throw new Error("Unknown primitive type");
  31846. }
  31847. else {
  31848. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31849. }
  31850. serializedGeometries[geometry.id] = true;
  31851. };
  31852. var serializeMesh = function (mesh, serializationScene) {
  31853. var serializationObject = {};
  31854. serializationObject.name = mesh.name;
  31855. serializationObject.id = mesh.id;
  31856. if (BABYLON.Tags.HasTags(mesh)) {
  31857. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31858. }
  31859. serializationObject.position = mesh.position.asArray();
  31860. if (mesh.rotationQuaternion) {
  31861. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31862. }
  31863. else if (mesh.rotation) {
  31864. serializationObject.rotation = mesh.rotation.asArray();
  31865. }
  31866. serializationObject.scaling = mesh.scaling.asArray();
  31867. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31868. serializationObject.isEnabled = mesh.isEnabled();
  31869. serializationObject.isVisible = mesh.isVisible;
  31870. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31871. serializationObject.pickable = mesh.isPickable;
  31872. serializationObject.receiveShadows = mesh.receiveShadows;
  31873. serializationObject.billboardMode = mesh.billboardMode;
  31874. serializationObject.visibility = mesh.visibility;
  31875. serializationObject.checkCollisions = mesh.checkCollisions;
  31876. // Parent
  31877. if (mesh.parent) {
  31878. serializationObject.parentId = mesh.parent.id;
  31879. }
  31880. // Geometry
  31881. var geometry = mesh._geometry;
  31882. if (geometry) {
  31883. var geometryId = geometry.id;
  31884. serializationObject.geometryId = geometryId;
  31885. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31886. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  31887. serializeGeometry(geometry, serializationScene.geometries);
  31888. }
  31889. // SubMeshes
  31890. serializationObject.subMeshes = [];
  31891. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31892. var subMesh = mesh.subMeshes[subIndex];
  31893. serializationObject.subMeshes.push({
  31894. materialIndex: subMesh.materialIndex,
  31895. verticesStart: subMesh.verticesStart,
  31896. verticesCount: subMesh.verticesCount,
  31897. indexStart: subMesh.indexStart,
  31898. indexCount: subMesh.indexCount
  31899. });
  31900. }
  31901. }
  31902. // Material
  31903. if (mesh.material) {
  31904. serializationObject.materialId = mesh.material.id;
  31905. }
  31906. else {
  31907. mesh.material = null;
  31908. }
  31909. // Skeleton
  31910. if (mesh.skeleton) {
  31911. serializationObject.skeletonId = mesh.skeleton.id;
  31912. }
  31913. // Physics
  31914. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31915. serializationObject.physicsMass = mesh.getPhysicsMass();
  31916. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31917. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31918. switch (mesh.getPhysicsImpostor()) {
  31919. case BABYLON.PhysicsEngine.BoxImpostor:
  31920. serializationObject.physicsImpostor = 1;
  31921. break;
  31922. case BABYLON.PhysicsEngine.SphereImpostor:
  31923. serializationObject.physicsImpostor = 2;
  31924. break;
  31925. }
  31926. }
  31927. // Instances
  31928. serializationObject.instances = [];
  31929. for (var index = 0; index < mesh.instances.length; index++) {
  31930. var instance = mesh.instances[index];
  31931. var serializationInstance = {
  31932. name: instance.name,
  31933. position: instance.position.asArray(),
  31934. scaling: instance.scaling.asArray()
  31935. };
  31936. if (instance.rotationQuaternion) {
  31937. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31938. }
  31939. else if (instance.rotation) {
  31940. serializationInstance.rotation = instance.rotation.asArray();
  31941. }
  31942. serializationObject.instances.push(serializationInstance);
  31943. // Animations
  31944. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31945. serializationInstance.ranges = instance.serializeAnimationRanges();
  31946. }
  31947. // Animations
  31948. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31949. serializationObject.ranges = mesh.serializeAnimationRanges();
  31950. // Layer mask
  31951. serializationObject.layerMask = mesh.layerMask;
  31952. return serializationObject;
  31953. };
  31954. var finalizeSingleMesh = function (mesh, serializationObject) {
  31955. //only works if the mesh is already loaded
  31956. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31957. //serialize material
  31958. if (mesh.material) {
  31959. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31960. serializationObject.materials = serializationObject.materials || [];
  31961. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31962. serializationObject.materials.push(mesh.material.serialize());
  31963. }
  31964. }
  31965. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31966. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31967. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31968. serializationObject.multiMaterials.push(mesh.material.serialize());
  31969. }
  31970. }
  31971. }
  31972. //serialize geometry
  31973. var geometry = mesh._geometry;
  31974. if (geometry) {
  31975. if (!serializationObject.geometries) {
  31976. serializationObject.geometries = {};
  31977. serializationObject.geometries.boxes = [];
  31978. serializationObject.geometries.spheres = [];
  31979. serializationObject.geometries.cylinders = [];
  31980. serializationObject.geometries.toruses = [];
  31981. serializationObject.geometries.grounds = [];
  31982. serializationObject.geometries.planes = [];
  31983. serializationObject.geometries.torusKnots = [];
  31984. serializationObject.geometries.vertexData = [];
  31985. }
  31986. serializeGeometry(geometry, serializationObject.geometries);
  31987. }
  31988. // Skeletons
  31989. if (mesh.skeleton) {
  31990. serializationObject.skeletons = serializationObject.skeletons || [];
  31991. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31992. }
  31993. //serialize the actual mesh
  31994. serializationObject.meshes = serializationObject.meshes || [];
  31995. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31996. }
  31997. };
  31998. var SceneSerializer = (function () {
  31999. function SceneSerializer() {
  32000. }
  32001. SceneSerializer.Serialize = function (scene) {
  32002. var serializationObject = {};
  32003. // Scene
  32004. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32005. serializationObject.autoClear = scene.autoClear;
  32006. serializationObject.clearColor = scene.clearColor.asArray();
  32007. serializationObject.ambientColor = scene.ambientColor.asArray();
  32008. serializationObject.gravity = scene.gravity.asArray();
  32009. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32010. serializationObject.workerCollisions = scene.workerCollisions;
  32011. // Fog
  32012. if (scene.fogMode && scene.fogMode !== 0) {
  32013. serializationObject.fogMode = scene.fogMode;
  32014. serializationObject.fogColor = scene.fogColor.asArray();
  32015. serializationObject.fogStart = scene.fogStart;
  32016. serializationObject.fogEnd = scene.fogEnd;
  32017. serializationObject.fogDensity = scene.fogDensity;
  32018. }
  32019. //Physics
  32020. if (scene.isPhysicsEnabled()) {
  32021. serializationObject.physicsEnabled = true;
  32022. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  32023. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32024. }
  32025. // Lights
  32026. serializationObject.lights = [];
  32027. var index;
  32028. var light;
  32029. for (index = 0; index < scene.lights.length; index++) {
  32030. light = scene.lights[index];
  32031. serializationObject.lights.push(light.serialize());
  32032. }
  32033. // Cameras
  32034. serializationObject.cameras = [];
  32035. for (index = 0; index < scene.cameras.length; index++) {
  32036. var camera = scene.cameras[index];
  32037. serializationObject.cameras.push(camera.serialize());
  32038. }
  32039. if (scene.activeCamera) {
  32040. serializationObject.activeCameraID = scene.activeCamera.id;
  32041. }
  32042. // Materials
  32043. serializationObject.materials = [];
  32044. serializationObject.multiMaterials = [];
  32045. var material;
  32046. for (index = 0; index < scene.materials.length; index++) {
  32047. material = scene.materials[index];
  32048. serializationObject.materials.push(material.serialize());
  32049. }
  32050. // MultiMaterials
  32051. serializationObject.multiMaterials = [];
  32052. for (index = 0; index < scene.multiMaterials.length; index++) {
  32053. var multiMaterial = scene.multiMaterials[index];
  32054. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32055. }
  32056. // Skeletons
  32057. serializationObject.skeletons = [];
  32058. for (index = 0; index < scene.skeletons.length; index++) {
  32059. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32060. }
  32061. // Geometries
  32062. serializationObject.geometries = {};
  32063. serializationObject.geometries.boxes = [];
  32064. serializationObject.geometries.spheres = [];
  32065. serializationObject.geometries.cylinders = [];
  32066. serializationObject.geometries.toruses = [];
  32067. serializationObject.geometries.grounds = [];
  32068. serializationObject.geometries.planes = [];
  32069. serializationObject.geometries.torusKnots = [];
  32070. serializationObject.geometries.vertexData = [];
  32071. serializedGeometries = [];
  32072. var geometries = scene.getGeometries();
  32073. for (index = 0; index < geometries.length; index++) {
  32074. var geometry = geometries[index];
  32075. if (geometry.isReady()) {
  32076. serializeGeometry(geometry, serializationObject.geometries);
  32077. }
  32078. }
  32079. // Meshes
  32080. serializationObject.meshes = [];
  32081. for (index = 0; index < scene.meshes.length; index++) {
  32082. var abstractMesh = scene.meshes[index];
  32083. if (abstractMesh instanceof BABYLON.Mesh) {
  32084. var mesh = abstractMesh;
  32085. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32086. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32087. }
  32088. }
  32089. }
  32090. // Particles Systems
  32091. serializationObject.particleSystems = [];
  32092. for (index = 0; index < scene.particleSystems.length; index++) {
  32093. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32094. }
  32095. // Lens flares
  32096. serializationObject.lensFlareSystems = [];
  32097. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32098. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32099. }
  32100. // Shadows
  32101. serializationObject.shadowGenerators = [];
  32102. for (index = 0; index < scene.lights.length; index++) {
  32103. light = scene.lights[index];
  32104. if (light.getShadowGenerator()) {
  32105. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32106. }
  32107. }
  32108. return serializationObject;
  32109. };
  32110. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32111. if (withParents === void 0) { withParents = false; }
  32112. if (withChildren === void 0) { withChildren = false; }
  32113. var serializationObject = {};
  32114. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32115. if (withParents || withChildren) {
  32116. //deliberate for loop! not for each, appended should be processed as well.
  32117. for (var i = 0; i < toSerialize.length; ++i) {
  32118. if (withChildren) {
  32119. toSerialize[i].getDescendants().forEach(function (node) {
  32120. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32121. toSerialize.push(node);
  32122. }
  32123. });
  32124. }
  32125. //make sure the array doesn't contain the object already
  32126. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32127. toSerialize.push(toSerialize[i].parent);
  32128. }
  32129. }
  32130. }
  32131. toSerialize.forEach(function (mesh) {
  32132. finalizeSingleMesh(mesh, serializationObject);
  32133. });
  32134. return serializationObject;
  32135. };
  32136. return SceneSerializer;
  32137. })();
  32138. BABYLON.SceneSerializer = SceneSerializer;
  32139. })(BABYLON || (BABYLON = {}));
  32140. var BABYLON;
  32141. (function (BABYLON) {
  32142. // Unique ID when we import meshes from Babylon to CSG
  32143. var currentCSGMeshId = 0;
  32144. // # class Vertex
  32145. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32146. // one to provide additional features like texture coordinates and vertex
  32147. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32148. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32149. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32150. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32151. // is not used anywhere else.
  32152. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32153. var Vertex = (function () {
  32154. function Vertex(pos, normal, uv) {
  32155. this.pos = pos;
  32156. this.normal = normal;
  32157. this.uv = uv;
  32158. }
  32159. Vertex.prototype.clone = function () {
  32160. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32161. };
  32162. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32163. // orientation of a polygon is flipped.
  32164. Vertex.prototype.flip = function () {
  32165. this.normal = this.normal.scale(-1);
  32166. };
  32167. // Create a new vertex between this vertex and `other` by linearly
  32168. // interpolating all properties using a parameter of `t`. Subclasses should
  32169. // override this to interpolate additional properties.
  32170. Vertex.prototype.interpolate = function (other, t) {
  32171. 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));
  32172. };
  32173. return Vertex;
  32174. })();
  32175. // # class Plane
  32176. // Represents a plane in 3D space.
  32177. var Plane = (function () {
  32178. function Plane(normal, w) {
  32179. this.normal = normal;
  32180. this.w = w;
  32181. }
  32182. Plane.FromPoints = function (a, b, c) {
  32183. var v0 = c.subtract(a);
  32184. var v1 = b.subtract(a);
  32185. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32186. return null;
  32187. }
  32188. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32189. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32190. };
  32191. Plane.prototype.clone = function () {
  32192. return new Plane(this.normal.clone(), this.w);
  32193. };
  32194. Plane.prototype.flip = function () {
  32195. this.normal.scaleInPlace(-1);
  32196. this.w = -this.w;
  32197. };
  32198. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32199. // fragments in the appropriate lists. Coplanar polygons go into either
  32200. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32201. // respect to this plane. Polygons in front or in back of this plane go into
  32202. // either `front` or `back`.
  32203. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32204. var COPLANAR = 0;
  32205. var FRONT = 1;
  32206. var BACK = 2;
  32207. var SPANNING = 3;
  32208. // Classify each point as well as the entire polygon into one of the above
  32209. // four classes.
  32210. var polygonType = 0;
  32211. var types = [];
  32212. var i;
  32213. var t;
  32214. for (i = 0; i < polygon.vertices.length; i++) {
  32215. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32216. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32217. polygonType |= type;
  32218. types.push(type);
  32219. }
  32220. // Put the polygon in the correct list, splitting it when necessary.
  32221. switch (polygonType) {
  32222. case COPLANAR:
  32223. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32224. break;
  32225. case FRONT:
  32226. front.push(polygon);
  32227. break;
  32228. case BACK:
  32229. back.push(polygon);
  32230. break;
  32231. case SPANNING:
  32232. var f = [], b = [];
  32233. for (i = 0; i < polygon.vertices.length; i++) {
  32234. var j = (i + 1) % polygon.vertices.length;
  32235. var ti = types[i], tj = types[j];
  32236. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32237. if (ti !== BACK)
  32238. f.push(vi);
  32239. if (ti !== FRONT)
  32240. b.push(ti !== BACK ? vi.clone() : vi);
  32241. if ((ti | tj) === SPANNING) {
  32242. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32243. var v = vi.interpolate(vj, t);
  32244. f.push(v);
  32245. b.push(v.clone());
  32246. }
  32247. }
  32248. var poly;
  32249. if (f.length >= 3) {
  32250. poly = new Polygon(f, polygon.shared);
  32251. if (poly.plane)
  32252. front.push(poly);
  32253. }
  32254. if (b.length >= 3) {
  32255. poly = new Polygon(b, polygon.shared);
  32256. if (poly.plane)
  32257. back.push(poly);
  32258. }
  32259. break;
  32260. }
  32261. };
  32262. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32263. // point is on the plane.
  32264. Plane.EPSILON = 1e-5;
  32265. return Plane;
  32266. })();
  32267. // # class Polygon
  32268. // Represents a convex polygon. The vertices used to initialize a polygon must
  32269. // be coplanar and form a convex loop.
  32270. //
  32271. // Each convex polygon has a `shared` property, which is shared between all
  32272. // polygons that are clones of each other or were split from the same polygon.
  32273. // This can be used to define per-polygon properties (such as surface color).
  32274. var Polygon = (function () {
  32275. function Polygon(vertices, shared) {
  32276. this.vertices = vertices;
  32277. this.shared = shared;
  32278. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32279. }
  32280. Polygon.prototype.clone = function () {
  32281. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32282. return new Polygon(vertices, this.shared);
  32283. };
  32284. Polygon.prototype.flip = function () {
  32285. this.vertices.reverse().map(function (v) { v.flip(); });
  32286. this.plane.flip();
  32287. };
  32288. return Polygon;
  32289. })();
  32290. // # class Node
  32291. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32292. // by picking a polygon to split along. That polygon (and all other coplanar
  32293. // polygons) are added directly to that node and the other polygons are added to
  32294. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32295. // no distinction between internal and leaf nodes.
  32296. var Node = (function () {
  32297. function Node(polygons) {
  32298. this.plane = null;
  32299. this.front = null;
  32300. this.back = null;
  32301. this.polygons = [];
  32302. if (polygons) {
  32303. this.build(polygons);
  32304. }
  32305. }
  32306. Node.prototype.clone = function () {
  32307. var node = new Node();
  32308. node.plane = this.plane && this.plane.clone();
  32309. node.front = this.front && this.front.clone();
  32310. node.back = this.back && this.back.clone();
  32311. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32312. return node;
  32313. };
  32314. // Convert solid space to empty space and empty space to solid space.
  32315. Node.prototype.invert = function () {
  32316. for (var i = 0; i < this.polygons.length; i++) {
  32317. this.polygons[i].flip();
  32318. }
  32319. if (this.plane) {
  32320. this.plane.flip();
  32321. }
  32322. if (this.front) {
  32323. this.front.invert();
  32324. }
  32325. if (this.back) {
  32326. this.back.invert();
  32327. }
  32328. var temp = this.front;
  32329. this.front = this.back;
  32330. this.back = temp;
  32331. };
  32332. // Recursively remove all polygons in `polygons` that are inside this BSP
  32333. // tree.
  32334. Node.prototype.clipPolygons = function (polygons) {
  32335. if (!this.plane)
  32336. return polygons.slice();
  32337. var front = [], back = [];
  32338. for (var i = 0; i < polygons.length; i++) {
  32339. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32340. }
  32341. if (this.front) {
  32342. front = this.front.clipPolygons(front);
  32343. }
  32344. if (this.back) {
  32345. back = this.back.clipPolygons(back);
  32346. }
  32347. else {
  32348. back = [];
  32349. }
  32350. return front.concat(back);
  32351. };
  32352. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32353. // `bsp`.
  32354. Node.prototype.clipTo = function (bsp) {
  32355. this.polygons = bsp.clipPolygons(this.polygons);
  32356. if (this.front)
  32357. this.front.clipTo(bsp);
  32358. if (this.back)
  32359. this.back.clipTo(bsp);
  32360. };
  32361. // Return a list of all polygons in this BSP tree.
  32362. Node.prototype.allPolygons = function () {
  32363. var polygons = this.polygons.slice();
  32364. if (this.front)
  32365. polygons = polygons.concat(this.front.allPolygons());
  32366. if (this.back)
  32367. polygons = polygons.concat(this.back.allPolygons());
  32368. return polygons;
  32369. };
  32370. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32371. // new polygons are filtered down to the bottom of the tree and become new
  32372. // nodes there. Each set of polygons is partitioned using the first polygon
  32373. // (no heuristic is used to pick a good split).
  32374. Node.prototype.build = function (polygons) {
  32375. if (!polygons.length)
  32376. return;
  32377. if (!this.plane)
  32378. this.plane = polygons[0].plane.clone();
  32379. var front = [], back = [];
  32380. for (var i = 0; i < polygons.length; i++) {
  32381. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32382. }
  32383. if (front.length) {
  32384. if (!this.front)
  32385. this.front = new Node();
  32386. this.front.build(front);
  32387. }
  32388. if (back.length) {
  32389. if (!this.back)
  32390. this.back = new Node();
  32391. this.back.build(back);
  32392. }
  32393. };
  32394. return Node;
  32395. })();
  32396. var CSG = (function () {
  32397. function CSG() {
  32398. this.polygons = new Array();
  32399. }
  32400. // Convert BABYLON.Mesh to BABYLON.CSG
  32401. CSG.FromMesh = function (mesh) {
  32402. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32403. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32404. if (mesh instanceof BABYLON.Mesh) {
  32405. mesh.computeWorldMatrix(true);
  32406. matrix = mesh.getWorldMatrix();
  32407. meshPosition = mesh.position.clone();
  32408. meshRotation = mesh.rotation.clone();
  32409. if (mesh.rotationQuaternion) {
  32410. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32411. }
  32412. meshScaling = mesh.scaling.clone();
  32413. }
  32414. else {
  32415. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32416. }
  32417. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32418. var subMeshes = mesh.subMeshes;
  32419. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32420. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32421. vertices = [];
  32422. for (var j = 0; j < 3; j++) {
  32423. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32424. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32425. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32426. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32427. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32428. vertex = new Vertex(position, normal, uv);
  32429. vertices.push(vertex);
  32430. }
  32431. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32432. // To handle the case of degenerated triangle
  32433. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32434. if (polygon.plane)
  32435. polygons.push(polygon);
  32436. }
  32437. }
  32438. var csg = CSG.FromPolygons(polygons);
  32439. csg.matrix = matrix;
  32440. csg.position = meshPosition;
  32441. csg.rotation = meshRotation;
  32442. csg.scaling = meshScaling;
  32443. csg.rotationQuaternion = meshRotationQuaternion;
  32444. currentCSGMeshId++;
  32445. return csg;
  32446. };
  32447. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32448. CSG.FromPolygons = function (polygons) {
  32449. var csg = new CSG();
  32450. csg.polygons = polygons;
  32451. return csg;
  32452. };
  32453. CSG.prototype.clone = function () {
  32454. var csg = new CSG();
  32455. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32456. csg.copyTransformAttributes(this);
  32457. return csg;
  32458. };
  32459. CSG.prototype.toPolygons = function () {
  32460. return this.polygons;
  32461. };
  32462. CSG.prototype.union = function (csg) {
  32463. var a = new Node(this.clone().polygons);
  32464. var b = new Node(csg.clone().polygons);
  32465. a.clipTo(b);
  32466. b.clipTo(a);
  32467. b.invert();
  32468. b.clipTo(a);
  32469. b.invert();
  32470. a.build(b.allPolygons());
  32471. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32472. };
  32473. CSG.prototype.unionInPlace = function (csg) {
  32474. var a = new Node(this.polygons);
  32475. var b = new Node(csg.polygons);
  32476. a.clipTo(b);
  32477. b.clipTo(a);
  32478. b.invert();
  32479. b.clipTo(a);
  32480. b.invert();
  32481. a.build(b.allPolygons());
  32482. this.polygons = a.allPolygons();
  32483. };
  32484. CSG.prototype.subtract = function (csg) {
  32485. var a = new Node(this.clone().polygons);
  32486. var b = new Node(csg.clone().polygons);
  32487. a.invert();
  32488. a.clipTo(b);
  32489. b.clipTo(a);
  32490. b.invert();
  32491. b.clipTo(a);
  32492. b.invert();
  32493. a.build(b.allPolygons());
  32494. a.invert();
  32495. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32496. };
  32497. CSG.prototype.subtractInPlace = function (csg) {
  32498. var a = new Node(this.polygons);
  32499. var b = new Node(csg.polygons);
  32500. a.invert();
  32501. a.clipTo(b);
  32502. b.clipTo(a);
  32503. b.invert();
  32504. b.clipTo(a);
  32505. b.invert();
  32506. a.build(b.allPolygons());
  32507. a.invert();
  32508. this.polygons = a.allPolygons();
  32509. };
  32510. CSG.prototype.intersect = function (csg) {
  32511. var a = new Node(this.clone().polygons);
  32512. var b = new Node(csg.clone().polygons);
  32513. a.invert();
  32514. b.clipTo(a);
  32515. b.invert();
  32516. a.clipTo(b);
  32517. b.clipTo(a);
  32518. a.build(b.allPolygons());
  32519. a.invert();
  32520. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32521. };
  32522. CSG.prototype.intersectInPlace = function (csg) {
  32523. var a = new Node(this.polygons);
  32524. var b = new Node(csg.polygons);
  32525. a.invert();
  32526. b.clipTo(a);
  32527. b.invert();
  32528. a.clipTo(b);
  32529. b.clipTo(a);
  32530. a.build(b.allPolygons());
  32531. a.invert();
  32532. this.polygons = a.allPolygons();
  32533. };
  32534. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32535. // not modified.
  32536. CSG.prototype.inverse = function () {
  32537. var csg = this.clone();
  32538. csg.inverseInPlace();
  32539. return csg;
  32540. };
  32541. CSG.prototype.inverseInPlace = function () {
  32542. this.polygons.map(function (p) { p.flip(); });
  32543. };
  32544. // This is used to keep meshes transformations so they can be restored
  32545. // when we build back a Babylon Mesh
  32546. // NB : All CSG operations are performed in world coordinates
  32547. CSG.prototype.copyTransformAttributes = function (csg) {
  32548. this.matrix = csg.matrix;
  32549. this.position = csg.position;
  32550. this.rotation = csg.rotation;
  32551. this.scaling = csg.scaling;
  32552. this.rotationQuaternion = csg.rotationQuaternion;
  32553. return this;
  32554. };
  32555. // Build Raw mesh from CSG
  32556. // Coordinates here are in world space
  32557. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32558. var matrix = this.matrix.clone();
  32559. matrix.invert();
  32560. 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;
  32561. if (keepSubMeshes) {
  32562. // Sort Polygons, since subMeshes are indices range
  32563. polygons.sort(function (a, b) {
  32564. if (a.shared.meshId === b.shared.meshId) {
  32565. return a.shared.subMeshId - b.shared.subMeshId;
  32566. }
  32567. else {
  32568. return a.shared.meshId - b.shared.meshId;
  32569. }
  32570. });
  32571. }
  32572. for (var i = 0, il = polygons.length; i < il; i++) {
  32573. polygon = polygons[i];
  32574. // Building SubMeshes
  32575. if (!subMesh_dict[polygon.shared.meshId]) {
  32576. subMesh_dict[polygon.shared.meshId] = {};
  32577. }
  32578. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32579. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32580. indexStart: +Infinity,
  32581. indexEnd: -Infinity,
  32582. materialIndex: polygon.shared.materialIndex
  32583. };
  32584. }
  32585. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32586. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32587. polygonIndices[0] = 0;
  32588. polygonIndices[1] = j - 1;
  32589. polygonIndices[2] = j;
  32590. for (var k = 0; k < 3; k++) {
  32591. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32592. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32593. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32594. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32595. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32596. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32597. // Check if 2 points can be merged
  32598. if (!(typeof vertex_idx !== 'undefined' &&
  32599. normals[vertex_idx * 3] === localNormal.x &&
  32600. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32601. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32602. uvs[vertex_idx * 2] === uv.x &&
  32603. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32604. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32605. uvs.push(uv.x, uv.y);
  32606. normals.push(normal.x, normal.y, normal.z);
  32607. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32608. }
  32609. indices.push(vertex_idx);
  32610. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32611. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32612. currentIndex++;
  32613. }
  32614. }
  32615. }
  32616. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32617. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32618. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32619. mesh.setIndices(indices);
  32620. if (keepSubMeshes) {
  32621. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32622. var materialIndexOffset = 0, materialMaxIndex;
  32623. mesh.subMeshes = new Array();
  32624. for (var m in subMesh_dict) {
  32625. materialMaxIndex = -1;
  32626. for (var sm in subMesh_dict[m]) {
  32627. subMesh_obj = subMesh_dict[m][sm];
  32628. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32629. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32630. }
  32631. materialIndexOffset += ++materialMaxIndex;
  32632. }
  32633. }
  32634. return mesh;
  32635. };
  32636. // Build Mesh from CSG taking material and transforms into account
  32637. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32638. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32639. mesh.material = material;
  32640. mesh.position.copyFrom(this.position);
  32641. mesh.rotation.copyFrom(this.rotation);
  32642. if (this.rotationQuaternion) {
  32643. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32644. }
  32645. mesh.scaling.copyFrom(this.scaling);
  32646. mesh.computeWorldMatrix(true);
  32647. return mesh;
  32648. };
  32649. return CSG;
  32650. })();
  32651. BABYLON.CSG = CSG;
  32652. })(BABYLON || (BABYLON = {}));
  32653. var BABYLON;
  32654. (function (BABYLON) {
  32655. var VRDistortionCorrectionPostProcess = (function (_super) {
  32656. __extends(VRDistortionCorrectionPostProcess, _super);
  32657. //ANY
  32658. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32659. var _this = this;
  32660. _super.call(this, name, "vrDistortionCorrection", [
  32661. 'LensCenter',
  32662. 'Scale',
  32663. 'ScaleIn',
  32664. 'HmdWarpParam'
  32665. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32666. this._isRightEye = isRightEye;
  32667. this._distortionFactors = vrMetrics.distortionK;
  32668. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32669. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32670. this.onSizeChanged = function () {
  32671. _this.aspectRatio = _this.width * .5 / _this.height;
  32672. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32673. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32674. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32675. };
  32676. this.onApply = function (effect) {
  32677. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32678. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32679. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32680. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32681. };
  32682. }
  32683. return VRDistortionCorrectionPostProcess;
  32684. })(BABYLON.PostProcess);
  32685. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32686. })(BABYLON || (BABYLON = {}));
  32687. // Mainly based on these 2 articles :
  32688. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  32689. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32690. var BABYLON;
  32691. (function (BABYLON) {
  32692. (function (JoystickAxis) {
  32693. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32694. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32695. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32696. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32697. var JoystickAxis = BABYLON.JoystickAxis;
  32698. var VirtualJoystick = (function () {
  32699. function VirtualJoystick(leftJoystick) {
  32700. var _this = this;
  32701. if (leftJoystick) {
  32702. this._leftJoystick = true;
  32703. }
  32704. else {
  32705. this._leftJoystick = false;
  32706. }
  32707. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32708. VirtualJoystick._globalJoystickIndex++;
  32709. // By default left & right arrow keys are moving the X
  32710. // and up & down keys are moving the Y
  32711. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32712. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32713. this.reverseLeftRight = false;
  32714. this.reverseUpDown = false;
  32715. // collections of pointers
  32716. this._touches = new BABYLON.SmartCollection();
  32717. this.deltaPosition = BABYLON.Vector3.Zero();
  32718. this._joystickSensibility = 25;
  32719. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32720. this._rotationSpeed = 25;
  32721. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32722. this._rotateOnAxisRelativeToMesh = false;
  32723. this._onResize = function (evt) {
  32724. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32725. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32726. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32727. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32728. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32729. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32730. };
  32731. // injecting a canvas element on top of the canvas 3D game
  32732. if (!VirtualJoystick.vjCanvas) {
  32733. window.addEventListener("resize", this._onResize, false);
  32734. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32735. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32736. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32737. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32738. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32739. VirtualJoystick.vjCanvas.style.width = "100%";
  32740. VirtualJoystick.vjCanvas.style.height = "100%";
  32741. VirtualJoystick.vjCanvas.style.position = "absolute";
  32742. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32743. VirtualJoystick.vjCanvas.style.top = "0px";
  32744. VirtualJoystick.vjCanvas.style.left = "0px";
  32745. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32746. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32747. // Support for jQuery PEP polyfill
  32748. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32749. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32750. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32751. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32752. document.body.appendChild(VirtualJoystick.vjCanvas);
  32753. }
  32754. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32755. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32756. this.pressed = false;
  32757. // default joystick color
  32758. this._joystickColor = "cyan";
  32759. this._joystickPointerID = -1;
  32760. // current joystick position
  32761. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32762. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32763. // origin joystick position
  32764. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32765. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32766. this._onPointerDownHandlerRef = function (evt) {
  32767. _this._onPointerDown(evt);
  32768. };
  32769. this._onPointerMoveHandlerRef = function (evt) {
  32770. _this._onPointerMove(evt);
  32771. };
  32772. this._onPointerOutHandlerRef = function (evt) {
  32773. _this._onPointerUp(evt);
  32774. };
  32775. this._onPointerUpHandlerRef = function (evt) {
  32776. _this._onPointerUp(evt);
  32777. };
  32778. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32779. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32780. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32781. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32782. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32783. evt.preventDefault(); // Disables system menu
  32784. }, false);
  32785. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32786. }
  32787. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32788. this._joystickSensibility = newJoystickSensibility;
  32789. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32790. };
  32791. VirtualJoystick.prototype._onPointerDown = function (e) {
  32792. var positionOnScreenCondition;
  32793. e.preventDefault();
  32794. if (this._leftJoystick === true) {
  32795. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32796. }
  32797. else {
  32798. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32799. }
  32800. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32801. // First contact will be dedicated to the virtual joystick
  32802. this._joystickPointerID = e.pointerId;
  32803. this._joystickPointerStartPos.x = e.clientX;
  32804. this._joystickPointerStartPos.y = e.clientY;
  32805. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32806. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32807. this._deltaJoystickVector.x = 0;
  32808. this._deltaJoystickVector.y = 0;
  32809. this.pressed = true;
  32810. this._touches.add(e.pointerId.toString(), e);
  32811. }
  32812. else {
  32813. // You can only trigger the action buttons with a joystick declared
  32814. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32815. this._action();
  32816. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32817. }
  32818. }
  32819. };
  32820. VirtualJoystick.prototype._onPointerMove = function (e) {
  32821. // If the current pointer is the one associated to the joystick (first touch contact)
  32822. if (this._joystickPointerID == e.pointerId) {
  32823. this._joystickPointerPos.x = e.clientX;
  32824. this._joystickPointerPos.y = e.clientY;
  32825. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32826. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32827. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32828. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32829. switch (this._axisTargetedByLeftAndRight) {
  32830. case JoystickAxis.X:
  32831. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32832. break;
  32833. case JoystickAxis.Y:
  32834. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32835. break;
  32836. case JoystickAxis.Z:
  32837. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32838. break;
  32839. }
  32840. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32841. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32842. switch (this._axisTargetedByUpAndDown) {
  32843. case JoystickAxis.X:
  32844. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32845. break;
  32846. case JoystickAxis.Y:
  32847. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32848. break;
  32849. case JoystickAxis.Z:
  32850. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32851. break;
  32852. }
  32853. }
  32854. else {
  32855. if (this._touches.item(e.pointerId.toString())) {
  32856. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32857. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32858. }
  32859. }
  32860. };
  32861. VirtualJoystick.prototype._onPointerUp = function (e) {
  32862. if (this._joystickPointerID == e.pointerId) {
  32863. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32864. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32865. this._joystickPointerID = -1;
  32866. this.pressed = false;
  32867. }
  32868. else {
  32869. var touch = this._touches.item(e.pointerId.toString());
  32870. if (touch) {
  32871. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32872. }
  32873. }
  32874. this._deltaJoystickVector.x = 0;
  32875. this._deltaJoystickVector.y = 0;
  32876. this._touches.remove(e.pointerId.toString());
  32877. };
  32878. /**
  32879. * Change the color of the virtual joystick
  32880. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32881. */
  32882. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32883. this._joystickColor = newColor;
  32884. };
  32885. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32886. this._action = action;
  32887. };
  32888. // Define which axis you'd like to control for left & right
  32889. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32890. switch (axis) {
  32891. case JoystickAxis.X:
  32892. case JoystickAxis.Y:
  32893. case JoystickAxis.Z:
  32894. this._axisTargetedByLeftAndRight = axis;
  32895. break;
  32896. default:
  32897. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32898. break;
  32899. }
  32900. };
  32901. // Define which axis you'd like to control for up & down
  32902. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32903. switch (axis) {
  32904. case JoystickAxis.X:
  32905. case JoystickAxis.Y:
  32906. case JoystickAxis.Z:
  32907. this._axisTargetedByUpAndDown = axis;
  32908. break;
  32909. default:
  32910. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32911. break;
  32912. }
  32913. };
  32914. VirtualJoystick.prototype._clearCanvas = function () {
  32915. if (this._leftJoystick) {
  32916. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32917. }
  32918. else {
  32919. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32920. }
  32921. };
  32922. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32923. var _this = this;
  32924. if (this.pressed) {
  32925. this._touches.forEach(function (touch) {
  32926. if (touch.pointerId === _this._joystickPointerID) {
  32927. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32928. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32929. VirtualJoystick.vjCanvasContext.beginPath();
  32930. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32931. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32932. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32933. VirtualJoystick.vjCanvasContext.stroke();
  32934. VirtualJoystick.vjCanvasContext.closePath();
  32935. VirtualJoystick.vjCanvasContext.beginPath();
  32936. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32937. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32938. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32939. VirtualJoystick.vjCanvasContext.stroke();
  32940. VirtualJoystick.vjCanvasContext.closePath();
  32941. VirtualJoystick.vjCanvasContext.beginPath();
  32942. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32943. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32944. VirtualJoystick.vjCanvasContext.stroke();
  32945. VirtualJoystick.vjCanvasContext.closePath();
  32946. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32947. }
  32948. else {
  32949. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32950. VirtualJoystick.vjCanvasContext.beginPath();
  32951. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32952. VirtualJoystick.vjCanvasContext.beginPath();
  32953. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32954. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32955. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32956. VirtualJoystick.vjCanvasContext.stroke();
  32957. VirtualJoystick.vjCanvasContext.closePath();
  32958. touch.prevX = touch.x;
  32959. touch.prevY = touch.y;
  32960. }
  32961. ;
  32962. });
  32963. }
  32964. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32965. };
  32966. VirtualJoystick.prototype.releaseCanvas = function () {
  32967. if (VirtualJoystick.vjCanvas) {
  32968. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32969. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32970. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32971. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32972. window.removeEventListener("resize", this._onResize);
  32973. document.body.removeChild(VirtualJoystick.vjCanvas);
  32974. VirtualJoystick.vjCanvas = null;
  32975. }
  32976. };
  32977. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32978. VirtualJoystick._globalJoystickIndex = 0;
  32979. return VirtualJoystick;
  32980. })();
  32981. BABYLON.VirtualJoystick = VirtualJoystick;
  32982. })(BABYLON || (BABYLON = {}));
  32983. var BABYLON;
  32984. (function (BABYLON) {
  32985. // We're mainly based on the logic defined into the FreeCamera code
  32986. var VirtualJoysticksCamera = (function (_super) {
  32987. __extends(VirtualJoysticksCamera, _super);
  32988. function VirtualJoysticksCamera(name, position, scene) {
  32989. _super.call(this, name, position, scene);
  32990. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32991. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32992. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32993. this._leftjoystick.setJoystickSensibility(0.15);
  32994. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32995. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32996. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32997. this._rightjoystick.reverseUpDown = true;
  32998. this._rightjoystick.setJoystickSensibility(0.05);
  32999. this._rightjoystick.setJoystickColor("yellow");
  33000. }
  33001. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33002. return this._leftjoystick;
  33003. };
  33004. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33005. return this._rightjoystick;
  33006. };
  33007. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33008. var speed = this._computeLocalCameraSpeed() * 50;
  33009. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33010. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33011. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33012. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33013. if (!this._leftjoystick.pressed) {
  33014. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33015. }
  33016. if (!this._rightjoystick.pressed) {
  33017. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33018. }
  33019. _super.prototype._checkInputs.call(this);
  33020. };
  33021. VirtualJoysticksCamera.prototype.dispose = function () {
  33022. this._leftjoystick.releaseCanvas();
  33023. _super.prototype.dispose.call(this);
  33024. };
  33025. return VirtualJoysticksCamera;
  33026. })(BABYLON.FreeCamera);
  33027. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33028. })(BABYLON || (BABYLON = {}));
  33029. var BABYLON;
  33030. (function (BABYLON) {
  33031. var AnaglyphPostProcess = (function (_super) {
  33032. __extends(AnaglyphPostProcess, _super);
  33033. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33034. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33035. }
  33036. return AnaglyphPostProcess;
  33037. })(BABYLON.PostProcess);
  33038. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33039. })(BABYLON || (BABYLON = {}));
  33040. var BABYLON;
  33041. (function (BABYLON) {
  33042. var OutlineRenderer = (function () {
  33043. function OutlineRenderer(scene) {
  33044. this._scene = scene;
  33045. }
  33046. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33047. var _this = this;
  33048. if (useOverlay === void 0) { useOverlay = false; }
  33049. var scene = this._scene;
  33050. var engine = this._scene.getEngine();
  33051. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33052. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33053. return;
  33054. }
  33055. var mesh = subMesh.getRenderingMesh();
  33056. var material = subMesh.getMaterial();
  33057. engine.enableEffect(this._effect);
  33058. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33059. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33060. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33061. // Bones
  33062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33063. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33064. }
  33065. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33066. // Alpha test
  33067. if (material && material.needAlphaTesting()) {
  33068. var alphaTexture = material.getAlphaTestTexture();
  33069. this._effect.setTexture("diffuseSampler", alphaTexture);
  33070. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33071. }
  33072. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33073. };
  33074. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33075. var defines = [];
  33076. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33077. var mesh = subMesh.getMesh();
  33078. var material = subMesh.getMaterial();
  33079. // Alpha test
  33080. if (material && material.needAlphaTesting()) {
  33081. defines.push("#define ALPHATEST");
  33082. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33083. attribs.push(BABYLON.VertexBuffer.UVKind);
  33084. defines.push("#define UV1");
  33085. }
  33086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33088. defines.push("#define UV2");
  33089. }
  33090. }
  33091. // Bones
  33092. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33095. if (mesh.numBoneInfluencers > 4) {
  33096. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33097. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33098. }
  33099. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33101. }
  33102. else {
  33103. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33104. }
  33105. // Instances
  33106. if (useInstances) {
  33107. defines.push("#define INSTANCES");
  33108. attribs.push("world0");
  33109. attribs.push("world1");
  33110. attribs.push("world2");
  33111. attribs.push("world3");
  33112. }
  33113. // Get correct effect
  33114. var join = defines.join("\n");
  33115. if (this._cachedDefines !== join) {
  33116. this._cachedDefines = join;
  33117. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33118. }
  33119. return this._effect.isReady();
  33120. };
  33121. return OutlineRenderer;
  33122. })();
  33123. BABYLON.OutlineRenderer = OutlineRenderer;
  33124. })(BABYLON || (BABYLON = {}));
  33125. var BABYLON;
  33126. (function (BABYLON) {
  33127. var MeshAssetTask = (function () {
  33128. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33129. this.name = name;
  33130. this.meshesNames = meshesNames;
  33131. this.rootUrl = rootUrl;
  33132. this.sceneFilename = sceneFilename;
  33133. this.isCompleted = false;
  33134. }
  33135. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33136. var _this = this;
  33137. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33138. _this.loadedMeshes = meshes;
  33139. _this.loadedParticleSystems = particleSystems;
  33140. _this.loadedSkeletons = skeletons;
  33141. _this.isCompleted = true;
  33142. if (_this.onSuccess) {
  33143. _this.onSuccess(_this);
  33144. }
  33145. onSuccess();
  33146. }, null, function () {
  33147. if (_this.onError) {
  33148. _this.onError(_this);
  33149. }
  33150. onError();
  33151. });
  33152. };
  33153. return MeshAssetTask;
  33154. })();
  33155. BABYLON.MeshAssetTask = MeshAssetTask;
  33156. var TextFileAssetTask = (function () {
  33157. function TextFileAssetTask(name, url) {
  33158. this.name = name;
  33159. this.url = url;
  33160. this.isCompleted = false;
  33161. }
  33162. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33163. var _this = this;
  33164. BABYLON.Tools.LoadFile(this.url, function (data) {
  33165. _this.text = data;
  33166. _this.isCompleted = true;
  33167. if (_this.onSuccess) {
  33168. _this.onSuccess(_this);
  33169. }
  33170. onSuccess();
  33171. }, null, scene.database, false, function () {
  33172. if (_this.onError) {
  33173. _this.onError(_this);
  33174. }
  33175. onError();
  33176. });
  33177. };
  33178. return TextFileAssetTask;
  33179. })();
  33180. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33181. var BinaryFileAssetTask = (function () {
  33182. function BinaryFileAssetTask(name, url) {
  33183. this.name = name;
  33184. this.url = url;
  33185. this.isCompleted = false;
  33186. }
  33187. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33188. var _this = this;
  33189. BABYLON.Tools.LoadFile(this.url, function (data) {
  33190. _this.data = data;
  33191. _this.isCompleted = true;
  33192. if (_this.onSuccess) {
  33193. _this.onSuccess(_this);
  33194. }
  33195. onSuccess();
  33196. }, null, scene.database, true, function () {
  33197. if (_this.onError) {
  33198. _this.onError(_this);
  33199. }
  33200. onError();
  33201. });
  33202. };
  33203. return BinaryFileAssetTask;
  33204. })();
  33205. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33206. var ImageAssetTask = (function () {
  33207. function ImageAssetTask(name, url) {
  33208. this.name = name;
  33209. this.url = url;
  33210. this.isCompleted = false;
  33211. }
  33212. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33213. var _this = this;
  33214. var img = new Image();
  33215. img.onload = function () {
  33216. _this.image = img;
  33217. _this.isCompleted = true;
  33218. if (_this.onSuccess) {
  33219. _this.onSuccess(_this);
  33220. }
  33221. onSuccess();
  33222. };
  33223. img.onerror = function () {
  33224. if (_this.onError) {
  33225. _this.onError(_this);
  33226. }
  33227. onError();
  33228. };
  33229. img.src = this.url;
  33230. };
  33231. return ImageAssetTask;
  33232. })();
  33233. BABYLON.ImageAssetTask = ImageAssetTask;
  33234. var TextureAssetTask = (function () {
  33235. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33237. this.name = name;
  33238. this.url = url;
  33239. this.noMipmap = noMipmap;
  33240. this.invertY = invertY;
  33241. this.samplingMode = samplingMode;
  33242. this.isCompleted = false;
  33243. }
  33244. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33245. var _this = this;
  33246. var onload = function () {
  33247. _this.isCompleted = true;
  33248. if (_this.onSuccess) {
  33249. _this.onSuccess(_this);
  33250. }
  33251. onSuccess();
  33252. };
  33253. var onerror = function () {
  33254. if (_this.onError) {
  33255. _this.onError(_this);
  33256. }
  33257. onError();
  33258. };
  33259. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33260. };
  33261. return TextureAssetTask;
  33262. })();
  33263. BABYLON.TextureAssetTask = TextureAssetTask;
  33264. var AssetsManager = (function () {
  33265. function AssetsManager(scene) {
  33266. this._tasks = new Array();
  33267. this._waitingTasksCount = 0;
  33268. this.useDefaultLoadingScreen = true;
  33269. this._scene = scene;
  33270. }
  33271. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33272. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33273. this._tasks.push(task);
  33274. return task;
  33275. };
  33276. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33277. var task = new TextFileAssetTask(taskName, url);
  33278. this._tasks.push(task);
  33279. return task;
  33280. };
  33281. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33282. var task = new BinaryFileAssetTask(taskName, url);
  33283. this._tasks.push(task);
  33284. return task;
  33285. };
  33286. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33287. var task = new ImageAssetTask(taskName, url);
  33288. this._tasks.push(task);
  33289. return task;
  33290. };
  33291. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33292. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33293. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33294. this._tasks.push(task);
  33295. return task;
  33296. };
  33297. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33298. this._waitingTasksCount--;
  33299. if (this._waitingTasksCount === 0) {
  33300. if (this.onFinish) {
  33301. this.onFinish(this._tasks);
  33302. }
  33303. this._scene.getEngine().hideLoadingUI();
  33304. }
  33305. };
  33306. AssetsManager.prototype._runTask = function (task) {
  33307. var _this = this;
  33308. task.run(this._scene, function () {
  33309. if (_this.onTaskSuccess) {
  33310. _this.onTaskSuccess(task);
  33311. }
  33312. _this._decreaseWaitingTasksCount();
  33313. }, function () {
  33314. if (_this.onTaskError) {
  33315. _this.onTaskError(task);
  33316. }
  33317. _this._decreaseWaitingTasksCount();
  33318. });
  33319. };
  33320. AssetsManager.prototype.reset = function () {
  33321. this._tasks = new Array();
  33322. return this;
  33323. };
  33324. AssetsManager.prototype.load = function () {
  33325. this._waitingTasksCount = this._tasks.length;
  33326. if (this._waitingTasksCount === 0) {
  33327. if (this.onFinish) {
  33328. this.onFinish(this._tasks);
  33329. }
  33330. return this;
  33331. }
  33332. if (this.useDefaultLoadingScreen) {
  33333. this._scene.getEngine().displayLoadingUI();
  33334. }
  33335. for (var index = 0; index < this._tasks.length; index++) {
  33336. var task = this._tasks[index];
  33337. this._runTask(task);
  33338. }
  33339. return this;
  33340. };
  33341. return AssetsManager;
  33342. })();
  33343. BABYLON.AssetsManager = AssetsManager;
  33344. })(BABYLON || (BABYLON = {}));
  33345. var BABYLON;
  33346. (function (BABYLON) {
  33347. var VRDeviceOrientationFreeCamera = (function (_super) {
  33348. __extends(VRDeviceOrientationFreeCamera, _super);
  33349. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33350. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33351. _super.call(this, name, position, scene);
  33352. this._alpha = 0;
  33353. this._beta = 0;
  33354. this._gamma = 0;
  33355. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33356. metrics.compensateDistortion = compensateDistortion;
  33357. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33358. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33359. }
  33360. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33361. this._alpha = +evt.alpha | 0;
  33362. this._beta = +evt.beta | 0;
  33363. this._gamma = +evt.gamma | 0;
  33364. if (this._gamma < 0) {
  33365. this._gamma = 90 + this._gamma;
  33366. }
  33367. else {
  33368. // Incline it in the correct angle.
  33369. this._gamma = 270 - this._gamma;
  33370. }
  33371. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33372. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33373. this.rotation.z = this._beta / 180.0 * Math.PI;
  33374. };
  33375. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33376. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33377. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33378. };
  33379. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33380. _super.prototype.detachControl.call(this, element);
  33381. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33382. };
  33383. return VRDeviceOrientationFreeCamera;
  33384. })(BABYLON.FreeCamera);
  33385. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33386. })(BABYLON || (BABYLON = {}));
  33387. var BABYLON;
  33388. (function (BABYLON) {
  33389. var WebVRFreeCamera = (function (_super) {
  33390. __extends(WebVRFreeCamera, _super);
  33391. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33392. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33393. _super.call(this, name, position, scene);
  33394. this._hmdDevice = null;
  33395. this._sensorDevice = null;
  33396. this._cacheState = null;
  33397. this._cacheQuaternion = new BABYLON.Quaternion();
  33398. this._cacheRotation = BABYLON.Vector3.Zero();
  33399. this._vrEnabled = false;
  33400. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33401. metrics.compensateDistortion = compensateDistortion;
  33402. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33403. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33404. }
  33405. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33406. var size = devices.length;
  33407. var i = 0;
  33408. // Reset devices.
  33409. this._sensorDevice = null;
  33410. this._hmdDevice = null;
  33411. // Search for a HmdDevice.
  33412. while (i < size && this._hmdDevice === null) {
  33413. if (devices[i] instanceof HMDVRDevice) {
  33414. this._hmdDevice = devices[i];
  33415. }
  33416. i++;
  33417. }
  33418. i = 0;
  33419. while (i < size && this._sensorDevice === null) {
  33420. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33421. this._sensorDevice = devices[i];
  33422. }
  33423. i++;
  33424. }
  33425. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33426. };
  33427. WebVRFreeCamera.prototype._checkInputs = function () {
  33428. if (this._vrEnabled) {
  33429. this._cacheState = this._sensorDevice.getState();
  33430. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33431. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33432. this.rotation.x = -this._cacheRotation.z;
  33433. this.rotation.y = -this._cacheRotation.y;
  33434. this.rotation.z = this._cacheRotation.x;
  33435. }
  33436. _super.prototype._checkInputs.call(this);
  33437. };
  33438. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33439. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33440. if (navigator.getVRDevices) {
  33441. navigator.getVRDevices().then(this._getWebVRDevices);
  33442. }
  33443. else if (navigator.mozGetVRDevices) {
  33444. navigator.mozGetVRDevices(this._getWebVRDevices);
  33445. }
  33446. };
  33447. WebVRFreeCamera.prototype.detachControl = function (element) {
  33448. _super.prototype.detachControl.call(this, element);
  33449. this._vrEnabled = false;
  33450. };
  33451. return WebVRFreeCamera;
  33452. })(BABYLON.FreeCamera);
  33453. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33454. })(BABYLON || (BABYLON = {}));
  33455. var BABYLON;
  33456. (function (BABYLON) {
  33457. // Standard optimizations
  33458. var SceneOptimization = (function () {
  33459. function SceneOptimization(priority) {
  33460. if (priority === void 0) { priority = 0; }
  33461. this.priority = priority;
  33462. this.apply = function (scene) {
  33463. return true; // Return true if everything that can be done was applied
  33464. };
  33465. }
  33466. return SceneOptimization;
  33467. })();
  33468. BABYLON.SceneOptimization = SceneOptimization;
  33469. var TextureOptimization = (function (_super) {
  33470. __extends(TextureOptimization, _super);
  33471. function TextureOptimization(priority, maximumSize) {
  33472. var _this = this;
  33473. if (priority === void 0) { priority = 0; }
  33474. if (maximumSize === void 0) { maximumSize = 1024; }
  33475. _super.call(this, priority);
  33476. this.priority = priority;
  33477. this.maximumSize = maximumSize;
  33478. this.apply = function (scene) {
  33479. var allDone = true;
  33480. for (var index = 0; index < scene.textures.length; index++) {
  33481. var texture = scene.textures[index];
  33482. if (!texture.canRescale) {
  33483. continue;
  33484. }
  33485. var currentSize = texture.getSize();
  33486. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33487. if (maxDimension > _this.maximumSize) {
  33488. texture.scale(0.5);
  33489. allDone = false;
  33490. }
  33491. }
  33492. return allDone;
  33493. };
  33494. }
  33495. return TextureOptimization;
  33496. })(SceneOptimization);
  33497. BABYLON.TextureOptimization = TextureOptimization;
  33498. var HardwareScalingOptimization = (function (_super) {
  33499. __extends(HardwareScalingOptimization, _super);
  33500. function HardwareScalingOptimization(priority, maximumScale) {
  33501. var _this = this;
  33502. if (priority === void 0) { priority = 0; }
  33503. if (maximumScale === void 0) { maximumScale = 2; }
  33504. _super.call(this, priority);
  33505. this.priority = priority;
  33506. this.maximumScale = maximumScale;
  33507. this._currentScale = 1;
  33508. this.apply = function (scene) {
  33509. _this._currentScale++;
  33510. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33511. return _this._currentScale >= _this.maximumScale;
  33512. };
  33513. }
  33514. return HardwareScalingOptimization;
  33515. })(SceneOptimization);
  33516. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33517. var ShadowsOptimization = (function (_super) {
  33518. __extends(ShadowsOptimization, _super);
  33519. function ShadowsOptimization() {
  33520. _super.apply(this, arguments);
  33521. this.apply = function (scene) {
  33522. scene.shadowsEnabled = false;
  33523. return true;
  33524. };
  33525. }
  33526. return ShadowsOptimization;
  33527. })(SceneOptimization);
  33528. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33529. var PostProcessesOptimization = (function (_super) {
  33530. __extends(PostProcessesOptimization, _super);
  33531. function PostProcessesOptimization() {
  33532. _super.apply(this, arguments);
  33533. this.apply = function (scene) {
  33534. scene.postProcessesEnabled = false;
  33535. return true;
  33536. };
  33537. }
  33538. return PostProcessesOptimization;
  33539. })(SceneOptimization);
  33540. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33541. var LensFlaresOptimization = (function (_super) {
  33542. __extends(LensFlaresOptimization, _super);
  33543. function LensFlaresOptimization() {
  33544. _super.apply(this, arguments);
  33545. this.apply = function (scene) {
  33546. scene.lensFlaresEnabled = false;
  33547. return true;
  33548. };
  33549. }
  33550. return LensFlaresOptimization;
  33551. })(SceneOptimization);
  33552. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33553. var ParticlesOptimization = (function (_super) {
  33554. __extends(ParticlesOptimization, _super);
  33555. function ParticlesOptimization() {
  33556. _super.apply(this, arguments);
  33557. this.apply = function (scene) {
  33558. scene.particlesEnabled = false;
  33559. return true;
  33560. };
  33561. }
  33562. return ParticlesOptimization;
  33563. })(SceneOptimization);
  33564. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33565. var RenderTargetsOptimization = (function (_super) {
  33566. __extends(RenderTargetsOptimization, _super);
  33567. function RenderTargetsOptimization() {
  33568. _super.apply(this, arguments);
  33569. this.apply = function (scene) {
  33570. scene.renderTargetsEnabled = false;
  33571. return true;
  33572. };
  33573. }
  33574. return RenderTargetsOptimization;
  33575. })(SceneOptimization);
  33576. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33577. var MergeMeshesOptimization = (function (_super) {
  33578. __extends(MergeMeshesOptimization, _super);
  33579. function MergeMeshesOptimization() {
  33580. var _this = this;
  33581. _super.apply(this, arguments);
  33582. this._canBeMerged = function (abstractMesh) {
  33583. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33584. return false;
  33585. }
  33586. var mesh = abstractMesh;
  33587. if (!mesh.isVisible || !mesh.isEnabled()) {
  33588. return false;
  33589. }
  33590. if (mesh.instances.length > 0) {
  33591. return false;
  33592. }
  33593. if (mesh.skeleton || mesh.hasLODLevels) {
  33594. return false;
  33595. }
  33596. if (mesh.parent) {
  33597. return false;
  33598. }
  33599. return true;
  33600. };
  33601. this.apply = function (scene, updateSelectionTree) {
  33602. var globalPool = scene.meshes.slice(0);
  33603. var globalLength = globalPool.length;
  33604. for (var index = 0; index < globalLength; index++) {
  33605. var currentPool = new Array();
  33606. var current = globalPool[index];
  33607. // Checks
  33608. if (!_this._canBeMerged(current)) {
  33609. continue;
  33610. }
  33611. currentPool.push(current);
  33612. // Find compatible meshes
  33613. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33614. var otherMesh = globalPool[subIndex];
  33615. if (!_this._canBeMerged(otherMesh)) {
  33616. continue;
  33617. }
  33618. if (otherMesh.material !== current.material) {
  33619. continue;
  33620. }
  33621. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33622. continue;
  33623. }
  33624. currentPool.push(otherMesh);
  33625. globalLength--;
  33626. globalPool.splice(subIndex, 1);
  33627. subIndex--;
  33628. }
  33629. if (currentPool.length < 2) {
  33630. continue;
  33631. }
  33632. // Merge meshes
  33633. BABYLON.Mesh.MergeMeshes(currentPool);
  33634. }
  33635. if (updateSelectionTree != undefined) {
  33636. if (updateSelectionTree) {
  33637. scene.createOrUpdateSelectionOctree();
  33638. }
  33639. }
  33640. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33641. scene.createOrUpdateSelectionOctree();
  33642. }
  33643. return true;
  33644. };
  33645. }
  33646. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33647. get: function () {
  33648. return MergeMeshesOptimization._UpdateSelectionTree;
  33649. },
  33650. set: function (value) {
  33651. MergeMeshesOptimization._UpdateSelectionTree = value;
  33652. },
  33653. enumerable: true,
  33654. configurable: true
  33655. });
  33656. MergeMeshesOptimization._UpdateSelectionTree = false;
  33657. return MergeMeshesOptimization;
  33658. })(SceneOptimization);
  33659. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33660. // Options
  33661. var SceneOptimizerOptions = (function () {
  33662. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33663. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33664. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33665. this.targetFrameRate = targetFrameRate;
  33666. this.trackerDuration = trackerDuration;
  33667. this.optimizations = new Array();
  33668. }
  33669. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33670. var result = new SceneOptimizerOptions(targetFrameRate);
  33671. var priority = 0;
  33672. result.optimizations.push(new MergeMeshesOptimization(priority));
  33673. result.optimizations.push(new ShadowsOptimization(priority));
  33674. result.optimizations.push(new LensFlaresOptimization(priority));
  33675. // Next priority
  33676. priority++;
  33677. result.optimizations.push(new PostProcessesOptimization(priority));
  33678. result.optimizations.push(new ParticlesOptimization(priority));
  33679. // Next priority
  33680. priority++;
  33681. result.optimizations.push(new TextureOptimization(priority, 1024));
  33682. return result;
  33683. };
  33684. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33685. var result = new SceneOptimizerOptions(targetFrameRate);
  33686. var priority = 0;
  33687. result.optimizations.push(new MergeMeshesOptimization(priority));
  33688. result.optimizations.push(new ShadowsOptimization(priority));
  33689. result.optimizations.push(new LensFlaresOptimization(priority));
  33690. // Next priority
  33691. priority++;
  33692. result.optimizations.push(new PostProcessesOptimization(priority));
  33693. result.optimizations.push(new ParticlesOptimization(priority));
  33694. // Next priority
  33695. priority++;
  33696. result.optimizations.push(new TextureOptimization(priority, 512));
  33697. // Next priority
  33698. priority++;
  33699. result.optimizations.push(new RenderTargetsOptimization(priority));
  33700. // Next priority
  33701. priority++;
  33702. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33703. return result;
  33704. };
  33705. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33706. var result = new SceneOptimizerOptions(targetFrameRate);
  33707. var priority = 0;
  33708. result.optimizations.push(new MergeMeshesOptimization(priority));
  33709. result.optimizations.push(new ShadowsOptimization(priority));
  33710. result.optimizations.push(new LensFlaresOptimization(priority));
  33711. // Next priority
  33712. priority++;
  33713. result.optimizations.push(new PostProcessesOptimization(priority));
  33714. result.optimizations.push(new ParticlesOptimization(priority));
  33715. // Next priority
  33716. priority++;
  33717. result.optimizations.push(new TextureOptimization(priority, 256));
  33718. // Next priority
  33719. priority++;
  33720. result.optimizations.push(new RenderTargetsOptimization(priority));
  33721. // Next priority
  33722. priority++;
  33723. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33724. return result;
  33725. };
  33726. return SceneOptimizerOptions;
  33727. })();
  33728. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33729. // Scene optimizer tool
  33730. var SceneOptimizer = (function () {
  33731. function SceneOptimizer() {
  33732. }
  33733. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33734. // TODO: add an epsilon
  33735. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33736. if (onSuccess) {
  33737. onSuccess();
  33738. }
  33739. return;
  33740. }
  33741. // Apply current level of optimizations
  33742. var allDone = true;
  33743. var noOptimizationApplied = true;
  33744. for (var index = 0; index < options.optimizations.length; index++) {
  33745. var optimization = options.optimizations[index];
  33746. if (optimization.priority === currentPriorityLevel) {
  33747. noOptimizationApplied = false;
  33748. allDone = allDone && optimization.apply(scene);
  33749. }
  33750. }
  33751. // If no optimization was applied, this is a failure :(
  33752. if (noOptimizationApplied) {
  33753. if (onFailure) {
  33754. onFailure();
  33755. }
  33756. return;
  33757. }
  33758. // If all optimizations were done, move to next level
  33759. if (allDone) {
  33760. currentPriorityLevel++;
  33761. }
  33762. // Let's the system running for a specific amount of time before checking FPS
  33763. scene.executeWhenReady(function () {
  33764. setTimeout(function () {
  33765. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33766. }, options.trackerDuration);
  33767. });
  33768. };
  33769. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33770. if (!options) {
  33771. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33772. }
  33773. // Let's the system running for a specific amount of time before checking FPS
  33774. scene.executeWhenReady(function () {
  33775. setTimeout(function () {
  33776. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33777. }, options.trackerDuration);
  33778. });
  33779. };
  33780. return SceneOptimizer;
  33781. })();
  33782. BABYLON.SceneOptimizer = SceneOptimizer;
  33783. })(BABYLON || (BABYLON = {}));
  33784. var BABYLON;
  33785. (function (BABYLON) {
  33786. var Internals;
  33787. (function (Internals) {
  33788. var MeshLODLevel = (function () {
  33789. function MeshLODLevel(distance, mesh) {
  33790. this.distance = distance;
  33791. this.mesh = mesh;
  33792. }
  33793. return MeshLODLevel;
  33794. })();
  33795. Internals.MeshLODLevel = MeshLODLevel;
  33796. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33797. })(BABYLON || (BABYLON = {}));
  33798. var BABYLON;
  33799. (function (BABYLON) {
  33800. var RawTexture = (function (_super) {
  33801. __extends(RawTexture, _super);
  33802. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33803. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33804. if (invertY === void 0) { invertY = false; }
  33805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33806. _super.call(this, null, scene, !generateMipMaps, invertY);
  33807. this.format = format;
  33808. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33809. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33810. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33811. }
  33812. RawTexture.prototype.update = function (data) {
  33813. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33814. };
  33815. // Statics
  33816. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33817. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33818. if (invertY === void 0) { invertY = false; }
  33819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33820. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33821. };
  33822. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33823. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33824. if (invertY === void 0) { invertY = false; }
  33825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33826. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33827. };
  33828. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33830. if (invertY === void 0) { invertY = false; }
  33831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33832. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33833. };
  33834. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33835. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33836. if (invertY === void 0) { invertY = false; }
  33837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33838. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33839. };
  33840. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33841. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33842. if (invertY === void 0) { invertY = false; }
  33843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33844. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33845. };
  33846. return RawTexture;
  33847. })(BABYLON.Texture);
  33848. BABYLON.RawTexture = RawTexture;
  33849. })(BABYLON || (BABYLON = {}));
  33850. var BABYLON;
  33851. (function (BABYLON) {
  33852. var IndexedVector2 = (function (_super) {
  33853. __extends(IndexedVector2, _super);
  33854. function IndexedVector2(original, index) {
  33855. _super.call(this, original.x, original.y);
  33856. this.index = index;
  33857. }
  33858. return IndexedVector2;
  33859. })(BABYLON.Vector2);
  33860. var PolygonPoints = (function () {
  33861. function PolygonPoints() {
  33862. this.elements = new Array();
  33863. }
  33864. PolygonPoints.prototype.add = function (originalPoints) {
  33865. var _this = this;
  33866. var result = new Array();
  33867. originalPoints.forEach(function (point) {
  33868. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33869. var newPoint = new IndexedVector2(point, _this.elements.length);
  33870. result.push(newPoint);
  33871. _this.elements.push(newPoint);
  33872. }
  33873. });
  33874. return result;
  33875. };
  33876. PolygonPoints.prototype.computeBounds = function () {
  33877. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33878. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33879. this.elements.forEach(function (point) {
  33880. // x
  33881. if (point.x < lmin.x) {
  33882. lmin.x = point.x;
  33883. }
  33884. else if (point.x > lmax.x) {
  33885. lmax.x = point.x;
  33886. }
  33887. // y
  33888. if (point.y < lmin.y) {
  33889. lmin.y = point.y;
  33890. }
  33891. else if (point.y > lmax.y) {
  33892. lmax.y = point.y;
  33893. }
  33894. });
  33895. return {
  33896. min: lmin,
  33897. max: lmax,
  33898. width: lmax.x - lmin.x,
  33899. height: lmax.y - lmin.y
  33900. };
  33901. };
  33902. return PolygonPoints;
  33903. })();
  33904. var Polygon = (function () {
  33905. function Polygon() {
  33906. }
  33907. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33908. return [
  33909. new BABYLON.Vector2(xmin, ymin),
  33910. new BABYLON.Vector2(xmax, ymin),
  33911. new BABYLON.Vector2(xmax, ymax),
  33912. new BABYLON.Vector2(xmin, ymax)
  33913. ];
  33914. };
  33915. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33916. if (cx === void 0) { cx = 0; }
  33917. if (cy === void 0) { cy = 0; }
  33918. if (numberOfSides === void 0) { numberOfSides = 32; }
  33919. var result = new Array();
  33920. var angle = 0;
  33921. var increment = (Math.PI * 2) / numberOfSides;
  33922. for (var i = 0; i < numberOfSides; i++) {
  33923. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33924. angle -= increment;
  33925. }
  33926. return result;
  33927. };
  33928. Polygon.Parse = function (input) {
  33929. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33930. var i, result = [];
  33931. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33932. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33933. }
  33934. return result;
  33935. };
  33936. Polygon.StartingAt = function (x, y) {
  33937. return BABYLON.Path2.StartingAt(x, y);
  33938. };
  33939. return Polygon;
  33940. })();
  33941. BABYLON.Polygon = Polygon;
  33942. var PolygonMeshBuilder = (function () {
  33943. function PolygonMeshBuilder(name, contours, scene) {
  33944. this._points = new PolygonPoints();
  33945. this._outlinepoints = new PolygonPoints();
  33946. this._holes = [];
  33947. if (!("poly2tri" in window)) {
  33948. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33949. }
  33950. this._name = name;
  33951. this._scene = scene;
  33952. var points;
  33953. if (contours instanceof BABYLON.Path2) {
  33954. points = contours.getPoints();
  33955. }
  33956. else {
  33957. points = contours;
  33958. }
  33959. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33960. this._outlinepoints.add(points);
  33961. }
  33962. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33963. this._swctx.addHole(this._points.add(hole));
  33964. var holepoints = new PolygonPoints();
  33965. holepoints.add(hole);
  33966. this._holes.push(holepoints);
  33967. return this;
  33968. };
  33969. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33970. var _this = this;
  33971. if (updatable === void 0) { updatable = false; }
  33972. var result = new BABYLON.Mesh(this._name, this._scene);
  33973. var normals = [];
  33974. var positions = [];
  33975. var uvs = [];
  33976. var bounds = this._points.computeBounds();
  33977. this._points.elements.forEach(function (p) {
  33978. normals.push(0, 1.0, 0);
  33979. positions.push(p.x, 0, p.y);
  33980. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33981. });
  33982. var indices = [];
  33983. this._swctx.triangulate();
  33984. this._swctx.getTriangles().forEach(function (triangle) {
  33985. triangle.getPoints().forEach(function (point) {
  33986. indices.push(point.index);
  33987. });
  33988. });
  33989. if (depth > 0) {
  33990. var positionscount = (positions.length / 3); //get the current pointcount
  33991. this._points.elements.forEach(function (p) {
  33992. normals.push(0, -1.0, 0);
  33993. positions.push(p.x, -depth, p.y);
  33994. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33995. });
  33996. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33997. var p2;
  33998. var poscounter = 0;
  33999. this._swctx.getTriangles().forEach(function (triangle) {
  34000. triangle.getPoints().forEach(function (point) {
  34001. switch (poscounter) {
  34002. case 0:
  34003. p1 = point;
  34004. break;
  34005. case 1:
  34006. p2 = point;
  34007. break;
  34008. case 2:
  34009. indices.push(point.index + positionscount);
  34010. indices.push(p2.index + positionscount);
  34011. indices.push(p1.index + positionscount);
  34012. poscounter = -1;
  34013. break;
  34014. }
  34015. poscounter++;
  34016. //indices.push((<IndexedVector2>point).index + positionscount);
  34017. });
  34018. });
  34019. //Add the sides
  34020. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34021. this._holes.forEach(function (hole) {
  34022. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34023. });
  34024. }
  34025. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34026. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34027. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34028. result.setIndices(indices);
  34029. return result;
  34030. };
  34031. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34032. var StartIndex = positions.length / 3;
  34033. var ulength = 0;
  34034. for (var i = 0; i < points.elements.length; i++) {
  34035. var p = points.elements[i];
  34036. var p1;
  34037. if ((i + 1) > points.elements.length - 1) {
  34038. p1 = points.elements[0];
  34039. }
  34040. else {
  34041. p1 = points.elements[i + 1];
  34042. }
  34043. positions.push(p.x, 0, p.y);
  34044. positions.push(p.x, -depth, p.y);
  34045. positions.push(p1.x, 0, p1.y);
  34046. positions.push(p1.x, -depth, p1.y);
  34047. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34048. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34049. var v3 = v2.subtract(v1);
  34050. var v4 = new BABYLON.Vector3(0, 1, 0);
  34051. var vn = BABYLON.Vector3.Cross(v3, v4);
  34052. vn = vn.normalize();
  34053. uvs.push(ulength / bounds.width, 0);
  34054. uvs.push(ulength / bounds.width, 1);
  34055. ulength += v3.length();
  34056. uvs.push((ulength / bounds.width), 0);
  34057. uvs.push((ulength / bounds.width), 1);
  34058. if (!flip) {
  34059. normals.push(-vn.x, -vn.y, -vn.z);
  34060. normals.push(-vn.x, -vn.y, -vn.z);
  34061. normals.push(-vn.x, -vn.y, -vn.z);
  34062. normals.push(-vn.x, -vn.y, -vn.z);
  34063. indices.push(StartIndex);
  34064. indices.push(StartIndex + 1);
  34065. indices.push(StartIndex + 2);
  34066. indices.push(StartIndex + 1);
  34067. indices.push(StartIndex + 3);
  34068. indices.push(StartIndex + 2);
  34069. }
  34070. else {
  34071. normals.push(vn.x, vn.y, vn.z);
  34072. normals.push(vn.x, vn.y, vn.z);
  34073. normals.push(vn.x, vn.y, vn.z);
  34074. normals.push(vn.x, vn.y, vn.z);
  34075. indices.push(StartIndex);
  34076. indices.push(StartIndex + 2);
  34077. indices.push(StartIndex + 1);
  34078. indices.push(StartIndex + 1);
  34079. indices.push(StartIndex + 2);
  34080. indices.push(StartIndex + 3);
  34081. }
  34082. StartIndex += 4;
  34083. }
  34084. ;
  34085. };
  34086. return PolygonMeshBuilder;
  34087. })();
  34088. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34089. })(BABYLON || (BABYLON = {}));
  34090. var BABYLON;
  34091. (function (BABYLON) {
  34092. var Octree = (function () {
  34093. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34094. if (maxDepth === void 0) { maxDepth = 2; }
  34095. this.maxDepth = maxDepth;
  34096. this.dynamicContent = new Array();
  34097. this._maxBlockCapacity = maxBlockCapacity || 64;
  34098. this._selectionContent = new BABYLON.SmartArray(1024);
  34099. this._creationFunc = creationFunc;
  34100. }
  34101. // Methods
  34102. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34103. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34104. };
  34105. Octree.prototype.addMesh = function (entry) {
  34106. for (var index = 0; index < this.blocks.length; index++) {
  34107. var block = this.blocks[index];
  34108. block.addEntry(entry);
  34109. }
  34110. };
  34111. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34112. this._selectionContent.reset();
  34113. for (var index = 0; index < this.blocks.length; index++) {
  34114. var block = this.blocks[index];
  34115. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34116. }
  34117. if (allowDuplicate) {
  34118. this._selectionContent.concat(this.dynamicContent);
  34119. }
  34120. else {
  34121. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34122. }
  34123. return this._selectionContent;
  34124. };
  34125. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34126. this._selectionContent.reset();
  34127. for (var index = 0; index < this.blocks.length; index++) {
  34128. var block = this.blocks[index];
  34129. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34130. }
  34131. if (allowDuplicate) {
  34132. this._selectionContent.concat(this.dynamicContent);
  34133. }
  34134. else {
  34135. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34136. }
  34137. return this._selectionContent;
  34138. };
  34139. Octree.prototype.intersectsRay = function (ray) {
  34140. this._selectionContent.reset();
  34141. for (var index = 0; index < this.blocks.length; index++) {
  34142. var block = this.blocks[index];
  34143. block.intersectsRay(ray, this._selectionContent);
  34144. }
  34145. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34146. return this._selectionContent;
  34147. };
  34148. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34149. target.blocks = new Array();
  34150. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34151. // Segmenting space
  34152. for (var x = 0; x < 2; x++) {
  34153. for (var y = 0; y < 2; y++) {
  34154. for (var z = 0; z < 2; z++) {
  34155. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34156. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34157. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34158. block.addEntries(entries);
  34159. target.blocks.push(block);
  34160. }
  34161. }
  34162. }
  34163. };
  34164. Octree.CreationFuncForMeshes = function (entry, block) {
  34165. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34166. block.entries.push(entry);
  34167. }
  34168. };
  34169. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34170. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34171. block.entries.push(entry);
  34172. }
  34173. };
  34174. return Octree;
  34175. })();
  34176. BABYLON.Octree = Octree;
  34177. })(BABYLON || (BABYLON = {}));
  34178. var BABYLON;
  34179. (function (BABYLON) {
  34180. var OctreeBlock = (function () {
  34181. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34182. this.entries = new Array();
  34183. this._boundingVectors = new Array();
  34184. this._capacity = capacity;
  34185. this._depth = depth;
  34186. this._maxDepth = maxDepth;
  34187. this._creationFunc = creationFunc;
  34188. this._minPoint = minPoint;
  34189. this._maxPoint = maxPoint;
  34190. this._boundingVectors.push(minPoint.clone());
  34191. this._boundingVectors.push(maxPoint.clone());
  34192. this._boundingVectors.push(minPoint.clone());
  34193. this._boundingVectors[2].x = maxPoint.x;
  34194. this._boundingVectors.push(minPoint.clone());
  34195. this._boundingVectors[3].y = maxPoint.y;
  34196. this._boundingVectors.push(minPoint.clone());
  34197. this._boundingVectors[4].z = maxPoint.z;
  34198. this._boundingVectors.push(maxPoint.clone());
  34199. this._boundingVectors[5].z = minPoint.z;
  34200. this._boundingVectors.push(maxPoint.clone());
  34201. this._boundingVectors[6].x = minPoint.x;
  34202. this._boundingVectors.push(maxPoint.clone());
  34203. this._boundingVectors[7].y = minPoint.y;
  34204. }
  34205. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34206. // Property
  34207. get: function () {
  34208. return this._capacity;
  34209. },
  34210. enumerable: true,
  34211. configurable: true
  34212. });
  34213. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34214. get: function () {
  34215. return this._minPoint;
  34216. },
  34217. enumerable: true,
  34218. configurable: true
  34219. });
  34220. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34221. get: function () {
  34222. return this._maxPoint;
  34223. },
  34224. enumerable: true,
  34225. configurable: true
  34226. });
  34227. // Methods
  34228. OctreeBlock.prototype.addEntry = function (entry) {
  34229. if (this.blocks) {
  34230. for (var index = 0; index < this.blocks.length; index++) {
  34231. var block = this.blocks[index];
  34232. block.addEntry(entry);
  34233. }
  34234. return;
  34235. }
  34236. this._creationFunc(entry, this);
  34237. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34238. this.createInnerBlocks();
  34239. }
  34240. };
  34241. OctreeBlock.prototype.addEntries = function (entries) {
  34242. for (var index = 0; index < entries.length; index++) {
  34243. var mesh = entries[index];
  34244. this.addEntry(mesh);
  34245. }
  34246. };
  34247. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34248. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34249. if (this.blocks) {
  34250. for (var index = 0; index < this.blocks.length; index++) {
  34251. var block = this.blocks[index];
  34252. block.select(frustumPlanes, selection, allowDuplicate);
  34253. }
  34254. return;
  34255. }
  34256. if (allowDuplicate) {
  34257. selection.concat(this.entries);
  34258. }
  34259. else {
  34260. selection.concatWithNoDuplicate(this.entries);
  34261. }
  34262. }
  34263. };
  34264. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34265. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34266. if (this.blocks) {
  34267. for (var index = 0; index < this.blocks.length; index++) {
  34268. var block = this.blocks[index];
  34269. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34270. }
  34271. return;
  34272. }
  34273. if (allowDuplicate) {
  34274. selection.concat(this.entries);
  34275. }
  34276. else {
  34277. selection.concatWithNoDuplicate(this.entries);
  34278. }
  34279. }
  34280. };
  34281. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34282. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34283. if (this.blocks) {
  34284. for (var index = 0; index < this.blocks.length; index++) {
  34285. var block = this.blocks[index];
  34286. block.intersectsRay(ray, selection);
  34287. }
  34288. return;
  34289. }
  34290. selection.concatWithNoDuplicate(this.entries);
  34291. }
  34292. };
  34293. OctreeBlock.prototype.createInnerBlocks = function () {
  34294. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34295. };
  34296. return OctreeBlock;
  34297. })();
  34298. BABYLON.OctreeBlock = OctreeBlock;
  34299. })(BABYLON || (BABYLON = {}));
  34300. var BABYLON;
  34301. (function (BABYLON) {
  34302. var BlurPostProcess = (function (_super) {
  34303. __extends(BlurPostProcess, _super);
  34304. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34305. var _this = this;
  34306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34307. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34308. this.direction = direction;
  34309. this.blurWidth = blurWidth;
  34310. this.onApply = function (effect) {
  34311. effect.setFloat2("screenSize", _this.width, _this.height);
  34312. effect.setVector2("direction", _this.direction);
  34313. effect.setFloat("blurWidth", _this.blurWidth);
  34314. };
  34315. }
  34316. return BlurPostProcess;
  34317. })(BABYLON.PostProcess);
  34318. BABYLON.BlurPostProcess = BlurPostProcess;
  34319. })(BABYLON || (BABYLON = {}));
  34320. var BABYLON;
  34321. (function (BABYLON) {
  34322. var RefractionPostProcess = (function (_super) {
  34323. __extends(RefractionPostProcess, _super);
  34324. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34325. var _this = this;
  34326. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34327. this.color = color;
  34328. this.depth = depth;
  34329. this.colorLevel = colorLevel;
  34330. this.onActivate = function (cam) {
  34331. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34332. };
  34333. this.onApply = function (effect) {
  34334. effect.setColor3("baseColor", _this.color);
  34335. effect.setFloat("depth", _this.depth);
  34336. effect.setFloat("colorLevel", _this.colorLevel);
  34337. effect.setTexture("refractionSampler", _this._refRexture);
  34338. };
  34339. }
  34340. // Methods
  34341. RefractionPostProcess.prototype.dispose = function (camera) {
  34342. if (this._refRexture) {
  34343. this._refRexture.dispose();
  34344. }
  34345. _super.prototype.dispose.call(this, camera);
  34346. };
  34347. return RefractionPostProcess;
  34348. })(BABYLON.PostProcess);
  34349. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34350. })(BABYLON || (BABYLON = {}));
  34351. var BABYLON;
  34352. (function (BABYLON) {
  34353. var BlackAndWhitePostProcess = (function (_super) {
  34354. __extends(BlackAndWhitePostProcess, _super);
  34355. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34356. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34357. }
  34358. return BlackAndWhitePostProcess;
  34359. })(BABYLON.PostProcess);
  34360. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34361. })(BABYLON || (BABYLON = {}));
  34362. var BABYLON;
  34363. (function (BABYLON) {
  34364. var ConvolutionPostProcess = (function (_super) {
  34365. __extends(ConvolutionPostProcess, _super);
  34366. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34367. var _this = this;
  34368. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34369. this.kernel = kernel;
  34370. this.onApply = function (effect) {
  34371. effect.setFloat2("screenSize", _this.width, _this.height);
  34372. effect.setArray("kernel", _this.kernel);
  34373. };
  34374. }
  34375. // Statics
  34376. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34377. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34378. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34379. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34380. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34381. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34382. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34383. return ConvolutionPostProcess;
  34384. })(BABYLON.PostProcess);
  34385. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34386. })(BABYLON || (BABYLON = {}));
  34387. var BABYLON;
  34388. (function (BABYLON) {
  34389. var FilterPostProcess = (function (_super) {
  34390. __extends(FilterPostProcess, _super);
  34391. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34392. var _this = this;
  34393. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34394. this.kernelMatrix = kernelMatrix;
  34395. this.onApply = function (effect) {
  34396. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34397. };
  34398. }
  34399. return FilterPostProcess;
  34400. })(BABYLON.PostProcess);
  34401. BABYLON.FilterPostProcess = FilterPostProcess;
  34402. })(BABYLON || (BABYLON = {}));
  34403. var BABYLON;
  34404. (function (BABYLON) {
  34405. var FxaaPostProcess = (function (_super) {
  34406. __extends(FxaaPostProcess, _super);
  34407. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34408. var _this = this;
  34409. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34410. this.onSizeChanged = function () {
  34411. _this.texelWidth = 1.0 / _this.width;
  34412. _this.texelHeight = 1.0 / _this.height;
  34413. };
  34414. this.onApply = function (effect) {
  34415. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34416. };
  34417. }
  34418. return FxaaPostProcess;
  34419. })(BABYLON.PostProcess);
  34420. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34421. })(BABYLON || (BABYLON = {}));
  34422. var BABYLON;
  34423. (function (BABYLON) {
  34424. var StereoscopicInterlacePostProcess = (function (_super) {
  34425. __extends(StereoscopicInterlacePostProcess, _super);
  34426. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34427. var _this = this;
  34428. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34429. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34430. this.onSizeChanged = function () {
  34431. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34432. };
  34433. this.onApply = function (effect) {
  34434. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34435. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34436. };
  34437. }
  34438. return StereoscopicInterlacePostProcess;
  34439. })(BABYLON.PostProcess);
  34440. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34441. })(BABYLON || (BABYLON = {}));
  34442. var BABYLON;
  34443. (function (BABYLON) {
  34444. var LensFlare = (function () {
  34445. function LensFlare(size, position, color, imgUrl, system) {
  34446. this.size = size;
  34447. this.position = position;
  34448. this.dispose = function () {
  34449. if (this.texture) {
  34450. this.texture.dispose();
  34451. }
  34452. // Remove from scene
  34453. var index = this._system.lensFlares.indexOf(this);
  34454. this._system.lensFlares.splice(index, 1);
  34455. };
  34456. this.color = color || new BABYLON.Color3(1, 1, 1);
  34457. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34458. this._system = system;
  34459. system.lensFlares.push(this);
  34460. }
  34461. return LensFlare;
  34462. })();
  34463. BABYLON.LensFlare = LensFlare;
  34464. })(BABYLON || (BABYLON = {}));
  34465. var BABYLON;
  34466. (function (BABYLON) {
  34467. var LensFlareSystem = (function () {
  34468. function LensFlareSystem(name, emitter, scene) {
  34469. this.name = name;
  34470. this.lensFlares = new Array();
  34471. this.borderLimit = 300;
  34472. this.layerMask = 0x0FFFFFFF;
  34473. this._vertexDeclaration = [2];
  34474. this._vertexStrideSize = 2 * 4;
  34475. this._isEnabled = true;
  34476. this._scene = scene;
  34477. this._emitter = emitter;
  34478. scene.lensFlareSystems.push(this);
  34479. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34480. // VBO
  34481. var vertices = [];
  34482. vertices.push(1, 1);
  34483. vertices.push(-1, 1);
  34484. vertices.push(-1, -1);
  34485. vertices.push(1, -1);
  34486. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34487. // Indices
  34488. var indices = [];
  34489. indices.push(0);
  34490. indices.push(1);
  34491. indices.push(2);
  34492. indices.push(0);
  34493. indices.push(2);
  34494. indices.push(3);
  34495. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34496. // Effects
  34497. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34498. }
  34499. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34500. get: function () {
  34501. return this._isEnabled;
  34502. },
  34503. set: function (value) {
  34504. this._isEnabled = value;
  34505. },
  34506. enumerable: true,
  34507. configurable: true
  34508. });
  34509. LensFlareSystem.prototype.getScene = function () {
  34510. return this._scene;
  34511. };
  34512. LensFlareSystem.prototype.getEmitter = function () {
  34513. return this._emitter;
  34514. };
  34515. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34516. this._emitter = newEmitter;
  34517. };
  34518. LensFlareSystem.prototype.getEmitterPosition = function () {
  34519. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34520. };
  34521. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34522. var position = this.getEmitterPosition();
  34523. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34524. this._positionX = position.x;
  34525. this._positionY = position.y;
  34526. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34527. if (position.z > 0) {
  34528. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34529. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34530. return true;
  34531. }
  34532. }
  34533. return false;
  34534. };
  34535. LensFlareSystem.prototype._isVisible = function () {
  34536. if (!this._isEnabled) {
  34537. return false;
  34538. }
  34539. var emitterPosition = this.getEmitterPosition();
  34540. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34541. var distance = direction.length();
  34542. direction.normalize();
  34543. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34544. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34545. return !pickInfo.hit || pickInfo.distance > distance;
  34546. };
  34547. LensFlareSystem.prototype.render = function () {
  34548. if (!this._effect.isReady())
  34549. return false;
  34550. var engine = this._scene.getEngine();
  34551. var viewport = this._scene.activeCamera.viewport;
  34552. var globalViewport = viewport.toScreenGlobal(engine);
  34553. // Position
  34554. if (!this.computeEffectivePosition(globalViewport)) {
  34555. return false;
  34556. }
  34557. // Visibility
  34558. if (!this._isVisible()) {
  34559. return false;
  34560. }
  34561. // Intensity
  34562. var awayX;
  34563. var awayY;
  34564. if (this._positionX < this.borderLimit + globalViewport.x) {
  34565. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34566. }
  34567. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34568. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34569. }
  34570. else {
  34571. awayX = 0;
  34572. }
  34573. if (this._positionY < this.borderLimit + globalViewport.y) {
  34574. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34575. }
  34576. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34577. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34578. }
  34579. else {
  34580. awayY = 0;
  34581. }
  34582. var away = (awayX > awayY) ? awayX : awayY;
  34583. if (away > this.borderLimit) {
  34584. away = this.borderLimit;
  34585. }
  34586. var intensity = 1.0 - (away / this.borderLimit);
  34587. if (intensity < 0) {
  34588. return false;
  34589. }
  34590. if (intensity > 1.0) {
  34591. intensity = 1.0;
  34592. }
  34593. // Position
  34594. var centerX = globalViewport.x + globalViewport.width / 2;
  34595. var centerY = globalViewport.y + globalViewport.height / 2;
  34596. var distX = centerX - this._positionX;
  34597. var distY = centerY - this._positionY;
  34598. // Effects
  34599. engine.enableEffect(this._effect);
  34600. engine.setState(false);
  34601. engine.setDepthBuffer(false);
  34602. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34603. // VBOs
  34604. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34605. // Flares
  34606. for (var index = 0; index < this.lensFlares.length; index++) {
  34607. var flare = this.lensFlares[index];
  34608. var x = centerX - (distX * flare.position);
  34609. var y = centerY - (distY * flare.position);
  34610. var cw = flare.size;
  34611. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34612. var cx = 2 * (x / globalViewport.width) - 1.0;
  34613. var cy = 1.0 - 2 * (y / globalViewport.height);
  34614. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34615. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34616. // Texture
  34617. this._effect.setTexture("textureSampler", flare.texture);
  34618. // Color
  34619. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34620. // Draw order
  34621. engine.draw(true, 0, 6);
  34622. }
  34623. engine.setDepthBuffer(true);
  34624. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34625. return true;
  34626. };
  34627. LensFlareSystem.prototype.dispose = function () {
  34628. if (this._vertexBuffer) {
  34629. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34630. this._vertexBuffer = null;
  34631. }
  34632. if (this._indexBuffer) {
  34633. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34634. this._indexBuffer = null;
  34635. }
  34636. while (this.lensFlares.length) {
  34637. this.lensFlares[0].dispose();
  34638. }
  34639. // Remove from scene
  34640. var index = this._scene.lensFlareSystems.indexOf(this);
  34641. this._scene.lensFlareSystems.splice(index, 1);
  34642. };
  34643. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34644. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34645. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34646. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34647. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34648. var parsedFlare = parsedLensFlareSystem.flares[index];
  34649. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34650. }
  34651. return lensFlareSystem;
  34652. };
  34653. LensFlareSystem.prototype.serialize = function () {
  34654. var serializationObject = {};
  34655. serializationObject.emitterId = this.getEmitter().id;
  34656. serializationObject.borderLimit = this.borderLimit;
  34657. serializationObject.flares = [];
  34658. for (var index = 0; index < this.lensFlares.length; index++) {
  34659. var flare = this.lensFlares[index];
  34660. serializationObject.flares.push({
  34661. size: flare.size,
  34662. position: flare.position,
  34663. color: flare.color.asArray(),
  34664. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34665. });
  34666. }
  34667. return serializationObject;
  34668. };
  34669. return LensFlareSystem;
  34670. })();
  34671. BABYLON.LensFlareSystem = LensFlareSystem;
  34672. })(BABYLON || (BABYLON = {}));
  34673. var BABYLON;
  34674. (function (BABYLON) {
  34675. // We're mainly based on the logic defined into the FreeCamera code
  34676. var DeviceOrientationCamera = (function (_super) {
  34677. __extends(DeviceOrientationCamera, _super);
  34678. function DeviceOrientationCamera(name, position, scene) {
  34679. var _this = this;
  34680. _super.call(this, name, position, scene);
  34681. this._offsetX = null;
  34682. this._offsetY = null;
  34683. this._orientationGamma = 0;
  34684. this._orientationBeta = 0;
  34685. this._initialOrientationGamma = 0;
  34686. this._initialOrientationBeta = 0;
  34687. this.angularSensibility = 10000.0;
  34688. this.moveSensibility = 50.0;
  34689. window.addEventListener("resize", function () {
  34690. _this._initialOrientationGamma = null;
  34691. }, false);
  34692. }
  34693. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34694. var _this = this;
  34695. if (this._attachedCanvas) {
  34696. return;
  34697. }
  34698. this._attachedCanvas = canvas;
  34699. if (!this._orientationChanged) {
  34700. this._orientationChanged = function (evt) {
  34701. if (!_this._initialOrientationGamma) {
  34702. _this._initialOrientationGamma = evt.gamma;
  34703. _this._initialOrientationBeta = evt.beta;
  34704. }
  34705. _this._orientationGamma = evt.gamma;
  34706. _this._orientationBeta = evt.beta;
  34707. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34708. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34709. };
  34710. }
  34711. window.addEventListener("deviceorientation", this._orientationChanged);
  34712. };
  34713. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34714. if (this._attachedCanvas !== canvas) {
  34715. return;
  34716. }
  34717. window.removeEventListener("deviceorientation", this._orientationChanged);
  34718. this._attachedCanvas = null;
  34719. this._orientationGamma = 0;
  34720. this._orientationBeta = 0;
  34721. this._initialOrientationGamma = 0;
  34722. this._initialOrientationBeta = 0;
  34723. };
  34724. DeviceOrientationCamera.prototype._checkInputs = function () {
  34725. if (!this._offsetX) {
  34726. return;
  34727. }
  34728. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34729. var speed = this._computeLocalCameraSpeed();
  34730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34732. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34733. _super.prototype._checkInputs.call(this);
  34734. };
  34735. return DeviceOrientationCamera;
  34736. })(BABYLON.FreeCamera);
  34737. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34738. })(BABYLON || (BABYLON = {}));
  34739. var BABYLON;
  34740. (function (BABYLON) {
  34741. // We're mainly based on the logic defined into the FreeCamera code
  34742. var UniversalCamera = (function (_super) {
  34743. __extends(UniversalCamera, _super);
  34744. function UniversalCamera(name, position, scene) {
  34745. var _this = this;
  34746. _super.call(this, name, position, scene);
  34747. this.gamepadAngularSensibility = 200;
  34748. this.gamepadMoveSensibility = 40;
  34749. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  34750. }
  34751. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  34752. // Only the first gamepad can control the camera
  34753. if (gamepad.index === 0) {
  34754. this.gamepad = gamepad;
  34755. }
  34756. };
  34757. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34758. _super.prototype.attachControl.call(this, canvas, false);
  34759. };
  34760. UniversalCamera.prototype.detachControl = function (canvas) {
  34761. _super.prototype.detachControl.call(this, canvas);
  34762. };
  34763. UniversalCamera.prototype._checkInputs = function () {
  34764. if (this.gamepad) {
  34765. var LSValues = this.gamepad.leftStick;
  34766. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  34767. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  34768. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  34769. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  34770. var RSValues = this.gamepad.rightStick;
  34771. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  34772. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  34773. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  34774. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  34775. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  34776. var speed = this._computeLocalCameraSpeed() * 50.0;
  34777. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  34778. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  34779. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  34780. }
  34781. _super.prototype._checkInputs.call(this);
  34782. };
  34783. UniversalCamera.prototype.dispose = function () {
  34784. this._gamepads.dispose();
  34785. _super.prototype.dispose.call(this);
  34786. };
  34787. return UniversalCamera;
  34788. })(BABYLON.TouchCamera);
  34789. BABYLON.UniversalCamera = UniversalCamera;
  34790. })(BABYLON || (BABYLON = {}));
  34791. var BABYLON;
  34792. (function (BABYLON) {
  34793. var Gamepads = (function () {
  34794. function Gamepads(ongamedpadconnected) {
  34795. var _this = this;
  34796. this.babylonGamepads = [];
  34797. this.oneGamepadConnected = false;
  34798. this.isMonitoring = false;
  34799. this.gamepadEventSupported = 'GamepadEvent' in window;
  34800. this.gamepadSupportAvailable = (navigator.getGamepads ||
  34801. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  34802. this._callbackGamepadConnected = ongamedpadconnected;
  34803. if (this.gamepadSupportAvailable) {
  34804. // Checking if the gamepad connected event is supported (like in Firefox)
  34805. if (this.gamepadEventSupported) {
  34806. window.addEventListener('gamepadconnected', function (evt) {
  34807. _this._onGamepadConnected(evt);
  34808. }, false);
  34809. window.addEventListener('gamepaddisconnected', function (evt) {
  34810. _this._onGamepadDisconnected(evt);
  34811. }, false);
  34812. }
  34813. else {
  34814. this._startMonitoringGamepads();
  34815. }
  34816. }
  34817. }
  34818. Gamepads.prototype.dispose = function () {
  34819. if (Gamepads.gamepadDOMInfo) {
  34820. document.body.removeChild(Gamepads.gamepadDOMInfo);
  34821. }
  34822. };
  34823. Gamepads.prototype._onGamepadConnected = function (evt) {
  34824. var newGamepad = this._addNewGamepad(evt.gamepad);
  34825. if (this._callbackGamepadConnected)
  34826. this._callbackGamepadConnected(newGamepad);
  34827. this._startMonitoringGamepads();
  34828. };
  34829. Gamepads.prototype._addNewGamepad = function (gamepad) {
  34830. if (!this.oneGamepadConnected) {
  34831. this.oneGamepadConnected = true;
  34832. if (Gamepads.gamepadDOMInfo) {
  34833. document.body.removeChild(Gamepads.gamepadDOMInfo);
  34834. Gamepads.gamepadDOMInfo = null;
  34835. }
  34836. }
  34837. var newGamepad;
  34838. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  34839. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  34840. }
  34841. else {
  34842. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  34843. }
  34844. this.babylonGamepads.push(newGamepad);
  34845. return newGamepad;
  34846. };
  34847. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  34848. // Remove the gamepad from the list of gamepads to monitor.
  34849. for (var i in this.babylonGamepads) {
  34850. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  34851. this.babylonGamepads.splice(i, 1);
  34852. break;
  34853. }
  34854. }
  34855. // If no gamepads are left, stop the polling loop.
  34856. if (this.babylonGamepads.length == 0) {
  34857. this._stopMonitoringGamepads();
  34858. }
  34859. };
  34860. Gamepads.prototype._startMonitoringGamepads = function () {
  34861. if (!this.isMonitoring) {
  34862. this.isMonitoring = true;
  34863. this._checkGamepadsStatus();
  34864. }
  34865. };
  34866. Gamepads.prototype._stopMonitoringGamepads = function () {
  34867. this.isMonitoring = false;
  34868. };
  34869. Gamepads.prototype._checkGamepadsStatus = function () {
  34870. var _this = this;
  34871. // updating gamepad objects
  34872. this._updateGamepadObjects();
  34873. for (var i in this.babylonGamepads) {
  34874. this.babylonGamepads[i].update();
  34875. }
  34876. if (this.isMonitoring) {
  34877. if (window.requestAnimationFrame) {
  34878. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  34879. }
  34880. else if (window.mozRequestAnimationFrame) {
  34881. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  34882. }
  34883. else if (window.webkitRequestAnimationFrame) {
  34884. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  34885. }
  34886. }
  34887. };
  34888. // This function is called only on Chrome, which does not yet support
  34889. // connection/disconnection events, but requires you to monitor
  34890. // an array for changes.
  34891. Gamepads.prototype._updateGamepadObjects = function () {
  34892. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  34893. for (var i = 0; i < gamepads.length; i++) {
  34894. if (gamepads[i]) {
  34895. if (!(gamepads[i].index in this.babylonGamepads)) {
  34896. var newGamepad = this._addNewGamepad(gamepads[i]);
  34897. if (this._callbackGamepadConnected) {
  34898. this._callbackGamepadConnected(newGamepad);
  34899. }
  34900. }
  34901. else {
  34902. this.babylonGamepads[i].browserGamepad = gamepads[i];
  34903. }
  34904. }
  34905. }
  34906. };
  34907. return Gamepads;
  34908. })();
  34909. BABYLON.Gamepads = Gamepads;
  34910. var StickValues = (function () {
  34911. function StickValues(x, y) {
  34912. this.x = x;
  34913. this.y = y;
  34914. }
  34915. return StickValues;
  34916. })();
  34917. BABYLON.StickValues = StickValues;
  34918. var Gamepad = (function () {
  34919. function Gamepad(id, index, browserGamepad) {
  34920. this.id = id;
  34921. this.index = index;
  34922. this.browserGamepad = browserGamepad;
  34923. if (this.browserGamepad.axes.length >= 2) {
  34924. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  34925. }
  34926. if (this.browserGamepad.axes.length >= 4) {
  34927. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  34928. }
  34929. }
  34930. Gamepad.prototype.onleftstickchanged = function (callback) {
  34931. this._onleftstickchanged = callback;
  34932. };
  34933. Gamepad.prototype.onrightstickchanged = function (callback) {
  34934. this._onrightstickchanged = callback;
  34935. };
  34936. Object.defineProperty(Gamepad.prototype, "leftStick", {
  34937. get: function () {
  34938. return this._leftStick;
  34939. },
  34940. set: function (newValues) {
  34941. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  34942. this._onleftstickchanged(newValues);
  34943. }
  34944. this._leftStick = newValues;
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(Gamepad.prototype, "rightStick", {
  34950. get: function () {
  34951. return this._rightStick;
  34952. },
  34953. set: function (newValues) {
  34954. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  34955. this._onrightstickchanged(newValues);
  34956. }
  34957. this._rightStick = newValues;
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Gamepad.prototype.update = function () {
  34963. if (this._leftStick) {
  34964. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  34965. }
  34966. if (this._rightStick) {
  34967. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  34968. }
  34969. };
  34970. return Gamepad;
  34971. })();
  34972. BABYLON.Gamepad = Gamepad;
  34973. var GenericPad = (function (_super) {
  34974. __extends(GenericPad, _super);
  34975. function GenericPad(id, index, gamepad) {
  34976. _super.call(this, id, index, gamepad);
  34977. this.id = id;
  34978. this.index = index;
  34979. this.gamepad = gamepad;
  34980. this._buttons = new Array(gamepad.buttons.length);
  34981. }
  34982. GenericPad.prototype.onbuttondown = function (callback) {
  34983. this._onbuttondown = callback;
  34984. };
  34985. GenericPad.prototype.onbuttonup = function (callback) {
  34986. this._onbuttonup = callback;
  34987. };
  34988. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  34989. if (newValue !== currentValue) {
  34990. if (this._onbuttondown && newValue === 1) {
  34991. this._onbuttondown(buttonIndex);
  34992. }
  34993. if (this._onbuttonup && newValue === 0) {
  34994. this._onbuttonup(buttonIndex);
  34995. }
  34996. }
  34997. return newValue;
  34998. };
  34999. GenericPad.prototype.update = function () {
  35000. _super.prototype.update.call(this);
  35001. for (var index = 0; index < this._buttons.length; index++) {
  35002. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  35003. }
  35004. };
  35005. return GenericPad;
  35006. })(Gamepad);
  35007. BABYLON.GenericPad = GenericPad;
  35008. (function (Xbox360Button) {
  35009. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  35010. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  35011. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  35012. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  35013. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  35014. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  35015. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  35016. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  35017. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  35018. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  35019. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  35020. var Xbox360Button = BABYLON.Xbox360Button;
  35021. (function (Xbox360Dpad) {
  35022. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  35023. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  35024. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  35025. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  35026. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  35027. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  35028. var Xbox360Pad = (function (_super) {
  35029. __extends(Xbox360Pad, _super);
  35030. function Xbox360Pad() {
  35031. _super.apply(this, arguments);
  35032. this._leftTrigger = 0;
  35033. this._rightTrigger = 0;
  35034. this._buttonA = 0;
  35035. this._buttonB = 0;
  35036. this._buttonX = 0;
  35037. this._buttonY = 0;
  35038. this._buttonBack = 0;
  35039. this._buttonStart = 0;
  35040. this._buttonLB = 0;
  35041. this._buttonRB = 0;
  35042. this._buttonLeftStick = 0;
  35043. this._buttonRightStick = 0;
  35044. this._dPadUp = 0;
  35045. this._dPadDown = 0;
  35046. this._dPadLeft = 0;
  35047. this._dPadRight = 0;
  35048. }
  35049. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  35050. this._onlefttriggerchanged = callback;
  35051. };
  35052. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  35053. this._onrighttriggerchanged = callback;
  35054. };
  35055. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  35056. get: function () {
  35057. return this._leftTrigger;
  35058. },
  35059. set: function (newValue) {
  35060. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  35061. this._onlefttriggerchanged(newValue);
  35062. }
  35063. this._leftTrigger = newValue;
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  35069. get: function () {
  35070. return this._rightTrigger;
  35071. },
  35072. set: function (newValue) {
  35073. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  35074. this._onrighttriggerchanged(newValue);
  35075. }
  35076. this._rightTrigger = newValue;
  35077. },
  35078. enumerable: true,
  35079. configurable: true
  35080. });
  35081. Xbox360Pad.prototype.onbuttondown = function (callback) {
  35082. this._onbuttondown = callback;
  35083. };
  35084. Xbox360Pad.prototype.onbuttonup = function (callback) {
  35085. this._onbuttonup = callback;
  35086. };
  35087. Xbox360Pad.prototype.ondpaddown = function (callback) {
  35088. this._ondpaddown = callback;
  35089. };
  35090. Xbox360Pad.prototype.ondpadup = function (callback) {
  35091. this._ondpadup = callback;
  35092. };
  35093. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  35094. if (newValue !== currentValue) {
  35095. if (this._onbuttondown && newValue === 1) {
  35096. this._onbuttondown(buttonType);
  35097. }
  35098. if (this._onbuttonup && newValue === 0) {
  35099. this._onbuttonup(buttonType);
  35100. }
  35101. }
  35102. return newValue;
  35103. };
  35104. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  35105. if (newValue !== currentValue) {
  35106. if (this._ondpaddown && newValue === 1) {
  35107. this._ondpaddown(buttonType);
  35108. }
  35109. if (this._ondpadup && newValue === 0) {
  35110. this._ondpadup(buttonType);
  35111. }
  35112. }
  35113. return newValue;
  35114. };
  35115. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  35116. get: function () {
  35117. return this._buttonA;
  35118. },
  35119. set: function (value) {
  35120. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  35121. },
  35122. enumerable: true,
  35123. configurable: true
  35124. });
  35125. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  35126. get: function () {
  35127. return this._buttonB;
  35128. },
  35129. set: function (value) {
  35130. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  35136. get: function () {
  35137. return this._buttonX;
  35138. },
  35139. set: function (value) {
  35140. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  35141. },
  35142. enumerable: true,
  35143. configurable: true
  35144. });
  35145. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  35146. get: function () {
  35147. return this._buttonY;
  35148. },
  35149. set: function (value) {
  35150. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  35156. get: function () {
  35157. return this._buttonStart;
  35158. },
  35159. set: function (value) {
  35160. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  35166. get: function () {
  35167. return this._buttonBack;
  35168. },
  35169. set: function (value) {
  35170. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  35176. get: function () {
  35177. return this._buttonLB;
  35178. },
  35179. set: function (value) {
  35180. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  35181. },
  35182. enumerable: true,
  35183. configurable: true
  35184. });
  35185. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  35186. get: function () {
  35187. return this._buttonRB;
  35188. },
  35189. set: function (value) {
  35190. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  35191. },
  35192. enumerable: true,
  35193. configurable: true
  35194. });
  35195. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  35196. get: function () {
  35197. return this._buttonLeftStick;
  35198. },
  35199. set: function (value) {
  35200. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  35206. get: function () {
  35207. return this._buttonRightStick;
  35208. },
  35209. set: function (value) {
  35210. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  35211. },
  35212. enumerable: true,
  35213. configurable: true
  35214. });
  35215. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  35216. get: function () {
  35217. return this._dPadUp;
  35218. },
  35219. set: function (value) {
  35220. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  35226. get: function () {
  35227. return this._dPadDown;
  35228. },
  35229. set: function (value) {
  35230. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  35236. get: function () {
  35237. return this._dPadLeft;
  35238. },
  35239. set: function (value) {
  35240. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  35241. },
  35242. enumerable: true,
  35243. configurable: true
  35244. });
  35245. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  35246. get: function () {
  35247. return this._dPadRight;
  35248. },
  35249. set: function (value) {
  35250. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Xbox360Pad.prototype.update = function () {
  35256. _super.prototype.update.call(this);
  35257. this.buttonA = this.browserGamepad.buttons[0].value;
  35258. this.buttonB = this.browserGamepad.buttons[1].value;
  35259. this.buttonX = this.browserGamepad.buttons[2].value;
  35260. this.buttonY = this.browserGamepad.buttons[3].value;
  35261. this.buttonLB = this.browserGamepad.buttons[4].value;
  35262. this.buttonRB = this.browserGamepad.buttons[5].value;
  35263. this.leftTrigger = this.browserGamepad.buttons[6].value;
  35264. this.rightTrigger = this.browserGamepad.buttons[7].value;
  35265. this.buttonBack = this.browserGamepad.buttons[8].value;
  35266. this.buttonStart = this.browserGamepad.buttons[9].value;
  35267. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  35268. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  35269. this.dPadUp = this.browserGamepad.buttons[12].value;
  35270. this.dPadDown = this.browserGamepad.buttons[13].value;
  35271. this.dPadLeft = this.browserGamepad.buttons[14].value;
  35272. this.dPadRight = this.browserGamepad.buttons[15].value;
  35273. };
  35274. return Xbox360Pad;
  35275. })(Gamepad);
  35276. BABYLON.Xbox360Pad = Xbox360Pad;
  35277. })(BABYLON || (BABYLON = {}));
  35278. var BABYLON;
  35279. (function (BABYLON) {
  35280. // We're mainly based on the logic defined into the FreeCamera code
  35281. var GamepadCamera = (function (_super) {
  35282. __extends(GamepadCamera, _super);
  35283. function GamepadCamera(name, position, scene) {
  35284. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  35285. _super.call(this, name, position, scene);
  35286. }
  35287. return GamepadCamera;
  35288. })(BABYLON.UniversalCamera);
  35289. BABYLON.GamepadCamera = GamepadCamera;
  35290. })(BABYLON || (BABYLON = {}));
  35291. var BABYLON;
  35292. (function (BABYLON) {
  35293. var Analyser = (function () {
  35294. function Analyser(scene) {
  35295. this.SMOOTHING = 0.75;
  35296. this.FFT_SIZE = 512;
  35297. this.BARGRAPHAMPLITUDE = 256;
  35298. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35299. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35300. this._scene = scene;
  35301. this._audioEngine = BABYLON.Engine.audioEngine;
  35302. if (this._audioEngine.canUseWebAudio) {
  35303. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35304. this._webAudioAnalyser.minDecibels = -140;
  35305. this._webAudioAnalyser.maxDecibels = 0;
  35306. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35307. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35308. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35309. }
  35310. }
  35311. Analyser.prototype.getFrequencyBinCount = function () {
  35312. if (this._audioEngine.canUseWebAudio) {
  35313. return this._webAudioAnalyser.frequencyBinCount;
  35314. }
  35315. else {
  35316. return 0;
  35317. }
  35318. };
  35319. Analyser.prototype.getByteFrequencyData = function () {
  35320. if (this._audioEngine.canUseWebAudio) {
  35321. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35322. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35323. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35324. }
  35325. return this._byteFreqs;
  35326. };
  35327. Analyser.prototype.getByteTimeDomainData = function () {
  35328. if (this._audioEngine.canUseWebAudio) {
  35329. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35330. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35331. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35332. }
  35333. return this._byteTime;
  35334. };
  35335. Analyser.prototype.getFloatFrequencyData = function () {
  35336. if (this._audioEngine.canUseWebAudio) {
  35337. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35338. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35339. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35340. }
  35341. return this._floatFreqs;
  35342. };
  35343. Analyser.prototype.drawDebugCanvas = function () {
  35344. var _this = this;
  35345. if (this._audioEngine.canUseWebAudio) {
  35346. if (!this._debugCanvas) {
  35347. this._debugCanvas = document.createElement("canvas");
  35348. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35349. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35350. this._debugCanvas.style.position = "absolute";
  35351. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35352. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35353. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35354. document.body.appendChild(this._debugCanvas);
  35355. this._registerFunc = function () {
  35356. _this.drawDebugCanvas();
  35357. };
  35358. this._scene.registerBeforeRender(this._registerFunc);
  35359. }
  35360. if (this._registerFunc) {
  35361. var workingArray = this.getByteFrequencyData();
  35362. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35363. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35364. // Draw the frequency domain chart.
  35365. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35366. var value = workingArray[i];
  35367. var percent = value / this.BARGRAPHAMPLITUDE;
  35368. var height = this.DEBUGCANVASSIZE.height * percent;
  35369. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35370. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35371. var hue = i / this.getFrequencyBinCount() * 360;
  35372. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35373. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35374. }
  35375. }
  35376. }
  35377. };
  35378. Analyser.prototype.stopDebugCanvas = function () {
  35379. if (this._debugCanvas) {
  35380. this._scene.unregisterBeforeRender(this._registerFunc);
  35381. this._registerFunc = null;
  35382. document.body.removeChild(this._debugCanvas);
  35383. this._debugCanvas = null;
  35384. this._debugCanvasContext = null;
  35385. }
  35386. };
  35387. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35388. if (this._audioEngine.canUseWebAudio) {
  35389. inputAudioNode.connect(this._webAudioAnalyser);
  35390. this._webAudioAnalyser.connect(outputAudioNode);
  35391. }
  35392. };
  35393. Analyser.prototype.dispose = function () {
  35394. if (this._audioEngine.canUseWebAudio) {
  35395. this._webAudioAnalyser.disconnect();
  35396. }
  35397. };
  35398. return Analyser;
  35399. })();
  35400. BABYLON.Analyser = Analyser;
  35401. })(BABYLON || (BABYLON = {}));
  35402. var BABYLON;
  35403. (function (BABYLON) {
  35404. var DepthRenderer = (function () {
  35405. function DepthRenderer(scene, type) {
  35406. var _this = this;
  35407. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35408. this._viewMatrix = BABYLON.Matrix.Zero();
  35409. this._projectionMatrix = BABYLON.Matrix.Zero();
  35410. this._transformMatrix = BABYLON.Matrix.Zero();
  35411. this._worldViewProjection = BABYLON.Matrix.Zero();
  35412. this._scene = scene;
  35413. var engine = scene.getEngine();
  35414. // Render target
  35415. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35416. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35417. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35418. this._depthMap.refreshRate = 1;
  35419. this._depthMap.renderParticles = false;
  35420. this._depthMap.renderList = null;
  35421. // set default depth value to 1.0 (far away)
  35422. this._depthMap.onClear = function (engine) {
  35423. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35424. };
  35425. // Custom render function
  35426. var renderSubMesh = function (subMesh) {
  35427. var mesh = subMesh.getRenderingMesh();
  35428. var scene = _this._scene;
  35429. var engine = scene.getEngine();
  35430. // Culling
  35431. engine.setState(subMesh.getMaterial().backFaceCulling);
  35432. // Managing instances
  35433. var batch = mesh._getInstancesRenderList(subMesh._id);
  35434. if (batch.mustReturn) {
  35435. return;
  35436. }
  35437. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35438. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35439. engine.enableEffect(_this._effect);
  35440. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35441. var material = subMesh.getMaterial();
  35442. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35443. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35444. // Alpha test
  35445. if (material && material.needAlphaTesting()) {
  35446. var alphaTexture = material.getAlphaTestTexture();
  35447. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35448. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35449. }
  35450. // Bones
  35451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35452. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35453. }
  35454. // Draw
  35455. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35456. }
  35457. };
  35458. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35459. var index;
  35460. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35461. renderSubMesh(opaqueSubMeshes.data[index]);
  35462. }
  35463. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35464. renderSubMesh(alphaTestSubMeshes.data[index]);
  35465. }
  35466. };
  35467. }
  35468. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35469. var defines = [];
  35470. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35471. var mesh = subMesh.getMesh();
  35472. var scene = mesh.getScene();
  35473. var material = subMesh.getMaterial();
  35474. // Alpha test
  35475. if (material && material.needAlphaTesting()) {
  35476. defines.push("#define ALPHATEST");
  35477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35478. attribs.push(BABYLON.VertexBuffer.UVKind);
  35479. defines.push("#define UV1");
  35480. }
  35481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35482. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35483. defines.push("#define UV2");
  35484. }
  35485. }
  35486. // Bones
  35487. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35490. if (mesh.numBoneInfluencers > 4) {
  35491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35493. }
  35494. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35495. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35496. }
  35497. else {
  35498. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35499. }
  35500. // Instances
  35501. if (useInstances) {
  35502. defines.push("#define INSTANCES");
  35503. attribs.push("world0");
  35504. attribs.push("world1");
  35505. attribs.push("world2");
  35506. attribs.push("world3");
  35507. }
  35508. // Get correct effect
  35509. var join = defines.join("\n");
  35510. if (this._cachedDefines !== join) {
  35511. this._cachedDefines = join;
  35512. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35513. }
  35514. return this._effect.isReady();
  35515. };
  35516. DepthRenderer.prototype.getDepthMap = function () {
  35517. return this._depthMap;
  35518. };
  35519. // Methods
  35520. DepthRenderer.prototype.dispose = function () {
  35521. this._depthMap.dispose();
  35522. };
  35523. return DepthRenderer;
  35524. })();
  35525. BABYLON.DepthRenderer = DepthRenderer;
  35526. })(BABYLON || (BABYLON = {}));
  35527. var BABYLON;
  35528. (function (BABYLON) {
  35529. var SSAORenderingPipeline = (function (_super) {
  35530. __extends(SSAORenderingPipeline, _super);
  35531. /**
  35532. * @constructor
  35533. * @param {string} name - The rendering pipeline name
  35534. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35535. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  35536. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35537. */
  35538. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35539. var _this = this;
  35540. _super.call(this, scene.getEngine(), name);
  35541. // Members
  35542. /**
  35543. * The PassPostProcess id in the pipeline that contains the original scene color
  35544. * @type {string}
  35545. */
  35546. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35547. /**
  35548. * The SSAO PostProcess id in the pipeline
  35549. * @type {string}
  35550. */
  35551. this.SSAORenderEffect = "SSAORenderEffect";
  35552. /**
  35553. * The horizontal blur PostProcess id in the pipeline
  35554. * @type {string}
  35555. */
  35556. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35557. /**
  35558. * The vertical blur PostProcess id in the pipeline
  35559. * @type {string}
  35560. */
  35561. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35562. /**
  35563. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35564. * @type {string}
  35565. */
  35566. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35567. /**
  35568. * The output strength of the SSAO post-process. Default value is 1.0.
  35569. * @type {number}
  35570. */
  35571. this.totalStrength = 1.0;
  35572. /**
  35573. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35574. * @type {number}
  35575. */
  35576. this.radius = 0.0001;
  35577. /**
  35578. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35579. * Must not be equal to fallOff and superior to fallOff.
  35580. * Default value is 0.975
  35581. * @type {number}
  35582. */
  35583. this.area = 0.0075;
  35584. /**
  35585. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35586. * Must not be equal to area and inferior to area.
  35587. * Default value is 0.0
  35588. * @type {number}
  35589. */
  35590. this.fallOff = 0.000001;
  35591. /**
  35592. * The base color of the SSAO post-process
  35593. * The final result is "base + ssao" between [0, 1]
  35594. * @type {number}
  35595. */
  35596. this.base = 0.5;
  35597. this._firstUpdate = true;
  35598. this._scene = scene;
  35599. // Set up assets
  35600. this._createRandomTexture();
  35601. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35602. var ssaoRatio = ratio.ssaoRatio || ratio;
  35603. var combineRatio = ratio.combineRatio || ratio;
  35604. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35605. this._createSSAOPostProcess(ssaoRatio);
  35606. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35607. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35608. this._createSSAOCombinePostProcess(combineRatio);
  35609. // Set up pipeline
  35610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35615. // Finish
  35616. scene.postProcessRenderPipelineManager.addPipeline(this);
  35617. if (cameras)
  35618. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35619. }
  35620. // Public Methods
  35621. /**
  35622. * Returns the horizontal blur PostProcess
  35623. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35624. */
  35625. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35626. return this._blurHPostProcess;
  35627. };
  35628. /**
  35629. * Returns the vertical blur PostProcess
  35630. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35631. */
  35632. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35633. return this._blurVPostProcess;
  35634. };
  35635. /**
  35636. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35637. */
  35638. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35639. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35640. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35641. this._originalColorPostProcess = undefined;
  35642. this._ssaoPostProcess = undefined;
  35643. this._blurHPostProcess = undefined;
  35644. this._blurVPostProcess = undefined;
  35645. this._ssaoCombinePostProcess = undefined;
  35646. this._randomTexture.dispose();
  35647. if (disableDepthRender)
  35648. this._scene.disableDepthRenderer();
  35649. };
  35650. // Private Methods
  35651. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35652. var _this = this;
  35653. var numSamples = 16;
  35654. var sampleSphere = [
  35655. 0.5381, 0.1856, -0.4319,
  35656. 0.1379, 0.2486, 0.4430,
  35657. 0.3371, 0.5679, -0.0057,
  35658. -0.6999, -0.0451, -0.0019,
  35659. 0.0689, -0.1598, -0.8547,
  35660. 0.0560, 0.0069, -0.1843,
  35661. -0.0146, 0.1402, 0.0762,
  35662. 0.0100, -0.1924, -0.0344,
  35663. -0.3577, -0.5301, -0.4358,
  35664. -0.3169, 0.1063, 0.0158,
  35665. 0.0103, -0.5869, 0.0046,
  35666. -0.0897, -0.4940, 0.3287,
  35667. 0.7119, -0.0154, -0.0918,
  35668. -0.0533, 0.0596, -0.5411,
  35669. 0.0352, -0.0631, 0.5460,
  35670. -0.4776, 0.2847, -0.0271
  35671. ];
  35672. var samplesFactor = 1.0 / numSamples;
  35673. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35674. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35675. "area", "fallOff", "base"
  35676. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35677. this._ssaoPostProcess.onApply = function (effect) {
  35678. if (_this._firstUpdate) {
  35679. effect.setArray3("sampleSphere", sampleSphere);
  35680. effect.setFloat("samplesFactor", samplesFactor);
  35681. effect.setFloat("randTextureTiles", 4.0);
  35682. _this._firstUpdate = false;
  35683. }
  35684. effect.setFloat("totalStrength", _this.totalStrength);
  35685. effect.setFloat("radius", _this.radius);
  35686. effect.setFloat("area", _this.area);
  35687. effect.setFloat("fallOff", _this.fallOff);
  35688. effect.setFloat("base", _this.base);
  35689. effect.setTexture("textureSampler", _this._depthTexture);
  35690. effect.setTexture("randomSampler", _this._randomTexture);
  35691. };
  35692. };
  35693. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35694. var _this = this;
  35695. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35696. this._ssaoCombinePostProcess.onApply = function (effect) {
  35697. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35698. };
  35699. };
  35700. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35701. var size = 512;
  35702. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35703. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35704. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35705. var context = this._randomTexture.getContext();
  35706. var rand = function (min, max) {
  35707. return Math.random() * (max - min) + min;
  35708. };
  35709. var randVector = BABYLON.Vector3.Zero();
  35710. for (var x = 0; x < size; x++) {
  35711. for (var y = 0; y < size; y++) {
  35712. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35713. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35714. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35715. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35716. context.fillRect(x, y, 1, 1);
  35717. }
  35718. }
  35719. this._randomTexture.update(false);
  35720. };
  35721. return SSAORenderingPipeline;
  35722. })(BABYLON.PostProcessRenderPipeline);
  35723. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35724. })(BABYLON || (BABYLON = {}));
  35725. var BABYLON;
  35726. (function (BABYLON) {
  35727. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35728. var VolumetricLightScatteringPostProcess = (function (_super) {
  35729. __extends(VolumetricLightScatteringPostProcess, _super);
  35730. /**
  35731. * @constructor
  35732. * @param {string} name - The post-process name
  35733. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  35734. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35735. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35736. * @param {number} samples - The post-process quality, default 100
  35737. * @param {number} samplingMode - The post-process filtering mode
  35738. * @param {BABYLON.Engine} engine - The babylon engine
  35739. * @param {boolean} reusable - If the post-process is reusable
  35740. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35741. */
  35742. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35743. var _this = this;
  35744. if (samples === void 0) { samples = 100; }
  35745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35746. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35747. this._screenCoordinates = BABYLON.Vector2.Zero();
  35748. /**
  35749. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35750. * @type {boolean}
  35751. */
  35752. this.useCustomMeshPosition = false;
  35753. /**
  35754. * If the post-process should inverse the light scattering direction
  35755. * @type {boolean}
  35756. */
  35757. this.invert = true;
  35758. /**
  35759. * Set to true to use the diffuseColor instead of the diffuseTexture
  35760. * @type {boolean}
  35761. */
  35762. this.useDiffuseColor = false;
  35763. /**
  35764. * Array containing the excluded meshes not rendered in the internal pass
  35765. */
  35766. this.excludedMeshes = new Array();
  35767. /**
  35768. * Controls the overall intensity of the post-process
  35769. * @type {number}
  35770. */
  35771. this.exposure = 0.3;
  35772. /**
  35773. * Dissipates each sample's contribution in range [0, 1]
  35774. * @type {number}
  35775. */
  35776. this.decay = 0.96815;
  35777. /**
  35778. * Controls the overall intensity of each sample
  35779. * @type {number}
  35780. */
  35781. this.weight = 0.58767;
  35782. /**
  35783. * Controls the density of each sample
  35784. * @type {number}
  35785. */
  35786. this.density = 0.926;
  35787. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35788. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35789. // Configure mesh
  35790. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35791. // Configure
  35792. this._createPass(scene, ratio.passRatio || ratio);
  35793. this.onActivate = function (camera) {
  35794. if (!_this.isSupported) {
  35795. _this.dispose(camera);
  35796. }
  35797. _this.onActivate = null;
  35798. };
  35799. this.onApply = function (effect) {
  35800. _this._updateMeshScreenCoordinates(scene);
  35801. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35802. effect.setFloat("exposure", _this.exposure);
  35803. effect.setFloat("decay", _this.decay);
  35804. effect.setFloat("weight", _this.weight);
  35805. effect.setFloat("density", _this.density);
  35806. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35807. };
  35808. }
  35809. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35810. var mesh = subMesh.getMesh();
  35811. var defines = [];
  35812. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35813. var material = subMesh.getMaterial();
  35814. var needUV = false;
  35815. // Render this.mesh as default
  35816. if (mesh === this.mesh) {
  35817. if (this.useDiffuseColor) {
  35818. defines.push("#define DIFFUSE_COLOR_RENDER");
  35819. }
  35820. else if (material) {
  35821. if (material.diffuseTexture !== undefined) {
  35822. defines.push("#define BASIC_RENDER");
  35823. }
  35824. else {
  35825. defines.push("#define DIFFUSE_COLOR_RENDER");
  35826. }
  35827. }
  35828. defines.push("#define NEED_UV");
  35829. needUV = true;
  35830. }
  35831. // Alpha test
  35832. if (material) {
  35833. if (material.needAlphaTesting()) {
  35834. defines.push("#define ALPHATEST");
  35835. }
  35836. if (material.opacityTexture !== undefined) {
  35837. defines.push("#define OPACITY");
  35838. if (material.opacityTexture.getAlphaFromRGB) {
  35839. defines.push("#define OPACITYRGB");
  35840. }
  35841. if (!needUV) {
  35842. defines.push("#define NEED_UV");
  35843. }
  35844. }
  35845. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35846. attribs.push(BABYLON.VertexBuffer.UVKind);
  35847. defines.push("#define UV1");
  35848. }
  35849. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35850. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35851. defines.push("#define UV2");
  35852. }
  35853. }
  35854. // Bones
  35855. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35858. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35859. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35860. }
  35861. else {
  35862. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35863. }
  35864. // Instances
  35865. if (useInstances) {
  35866. defines.push("#define INSTANCES");
  35867. attribs.push("world0");
  35868. attribs.push("world1");
  35869. attribs.push("world2");
  35870. attribs.push("world3");
  35871. }
  35872. // Get correct effect
  35873. var join = defines.join("\n");
  35874. if (this._cachedDefines !== join) {
  35875. this._cachedDefines = join;
  35876. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35877. }
  35878. return this._volumetricLightScatteringPass.isReady();
  35879. };
  35880. /**
  35881. * Sets the new light position for light scattering effect
  35882. * @param {BABYLON.Vector3} The new custom light position
  35883. */
  35884. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35885. this._customMeshPosition = position;
  35886. };
  35887. /**
  35888. * Returns the light position for light scattering effect
  35889. * @return {BABYLON.Vector3} The custom light position
  35890. */
  35891. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35892. return this._customMeshPosition;
  35893. };
  35894. /**
  35895. * Disposes the internal assets and detaches the post-process from the camera
  35896. */
  35897. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35898. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35899. if (rttIndex !== -1) {
  35900. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35901. }
  35902. this._volumetricLightScatteringRTT.dispose();
  35903. _super.prototype.dispose.call(this, camera);
  35904. };
  35905. /**
  35906. * Returns the render target texture used by the post-process
  35907. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35908. */
  35909. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35910. return this._volumetricLightScatteringRTT;
  35911. };
  35912. // Private methods
  35913. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35914. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35915. return true;
  35916. }
  35917. return false;
  35918. };
  35919. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35920. var _this = this;
  35921. var engine = scene.getEngine();
  35922. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35923. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35924. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35925. this._volumetricLightScatteringRTT.renderList = null;
  35926. this._volumetricLightScatteringRTT.renderParticles = false;
  35927. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35928. // Custom render function for submeshes
  35929. var renderSubMesh = function (subMesh) {
  35930. var mesh = subMesh.getRenderingMesh();
  35931. if (_this._meshExcluded(mesh)) {
  35932. return;
  35933. }
  35934. var scene = mesh.getScene();
  35935. var engine = scene.getEngine();
  35936. // Culling
  35937. engine.setState(subMesh.getMaterial().backFaceCulling);
  35938. // Managing instances
  35939. var batch = mesh._getInstancesRenderList(subMesh._id);
  35940. if (batch.mustReturn) {
  35941. return;
  35942. }
  35943. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35944. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35945. engine.enableEffect(_this._volumetricLightScatteringPass);
  35946. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35947. var material = subMesh.getMaterial();
  35948. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35949. // Alpha test
  35950. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35951. var alphaTexture = material.getAlphaTestTexture();
  35952. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35953. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35954. }
  35955. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35956. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35957. if (alphaTexture) {
  35958. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35959. }
  35960. }
  35961. if (material.opacityTexture !== undefined) {
  35962. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35963. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35964. }
  35965. }
  35966. // Bones
  35967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35968. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35969. }
  35970. // Draw
  35971. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35972. }
  35973. };
  35974. // Render target texture callbacks
  35975. var savedSceneClearColor;
  35976. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35977. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35978. savedSceneClearColor = scene.clearColor;
  35979. scene.clearColor = sceneClearColor;
  35980. };
  35981. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35982. scene.clearColor = savedSceneClearColor;
  35983. };
  35984. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35985. var engine = scene.getEngine();
  35986. var index;
  35987. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35988. renderSubMesh(opaqueSubMeshes.data[index]);
  35989. }
  35990. engine.setAlphaTesting(true);
  35991. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35992. renderSubMesh(alphaTestSubMeshes.data[index]);
  35993. }
  35994. engine.setAlphaTesting(false);
  35995. if (transparentSubMeshes.length) {
  35996. // Sort sub meshes
  35997. for (index = 0; index < transparentSubMeshes.length; index++) {
  35998. var submesh = transparentSubMeshes.data[index];
  35999. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36000. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36001. }
  36002. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36003. sortedArray.sort(function (a, b) {
  36004. // Alpha index first
  36005. if (a._alphaIndex > b._alphaIndex) {
  36006. return 1;
  36007. }
  36008. if (a._alphaIndex < b._alphaIndex) {
  36009. return -1;
  36010. }
  36011. // Then distance to camera
  36012. if (a._distanceToCamera < b._distanceToCamera) {
  36013. return 1;
  36014. }
  36015. if (a._distanceToCamera > b._distanceToCamera) {
  36016. return -1;
  36017. }
  36018. return 0;
  36019. });
  36020. // Render sub meshes
  36021. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36022. for (index = 0; index < sortedArray.length; index++) {
  36023. renderSubMesh(sortedArray[index]);
  36024. }
  36025. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36026. }
  36027. };
  36028. };
  36029. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36030. var transform = scene.getTransformMatrix();
  36031. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36032. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36033. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36034. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36035. if (this.invert)
  36036. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36037. };
  36038. // Static methods
  36039. /**
  36040. * Creates a default mesh for the Volumeric Light Scattering post-process
  36041. * @param {string} The mesh name
  36042. * @param {BABYLON.Scene} The scene where to create the mesh
  36043. * @return {BABYLON.Mesh} the default mesh
  36044. */
  36045. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36046. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36047. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36048. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36049. return mesh;
  36050. };
  36051. return VolumetricLightScatteringPostProcess;
  36052. })(BABYLON.PostProcess);
  36053. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36054. })(BABYLON || (BABYLON = {}));
  36055. // BABYLON.JS Chromatic Aberration GLSL Shader
  36056. // Author: Olivier Guyot
  36057. // Separates very slightly R, G and B colors on the edges of the screen
  36058. // Inspired by Francois Tarlier & Martins Upitis
  36059. var BABYLON;
  36060. (function (BABYLON) {
  36061. var LensRenderingPipeline = (function (_super) {
  36062. __extends(LensRenderingPipeline, _super);
  36063. /**
  36064. * @constructor
  36065. *
  36066. * Effect parameters are as follow:
  36067. * {
  36068. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36069. * edge_blur: number; // from 0 to x (1 for realism)
  36070. * distortion: number; // from 0 to x (1 for realism)
  36071. * grain_amount: number; // from 0 to 1
  36072. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36073. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36074. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36075. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36076. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36077. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36078. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36079. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36080. * }
  36081. * Note: if an effect parameter is unset, effect is disabled
  36082. *
  36083. * @param {string} name - The rendering pipeline name
  36084. * @param {object} parameters - An object containing all parameters (see above)
  36085. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36086. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  36087. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36088. */
  36089. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36090. var _this = this;
  36091. if (ratio === void 0) { ratio = 1.0; }
  36092. _super.call(this, scene.getEngine(), name);
  36093. // Lens effects can be of the following:
  36094. // - chromatic aberration (slight shift of RGB colors)
  36095. // - blur on the edge of the lens
  36096. // - lens distortion
  36097. // - depth-of-field blur & highlights enhancing
  36098. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36099. // - grain effect (noise or custom texture)
  36100. // Two additional texture samplers are needed:
  36101. // - depth map (for depth-of-field)
  36102. // - grain texture
  36103. /**
  36104. * The chromatic aberration PostProcess id in the pipeline
  36105. * @type {string}
  36106. */
  36107. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36108. /**
  36109. * The highlights enhancing PostProcess id in the pipeline
  36110. * @type {string}
  36111. */
  36112. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36113. /**
  36114. * The depth-of-field PostProcess id in the pipeline
  36115. * @type {string}
  36116. */
  36117. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36118. this._scene = scene;
  36119. // Fetch texture samplers
  36120. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36121. if (parameters.grain_texture) {
  36122. this._grainTexture = parameters.grain_texture;
  36123. }
  36124. else {
  36125. this._createGrainTexture();
  36126. }
  36127. // save parameters
  36128. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36129. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36130. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36131. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36132. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36133. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36134. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36135. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36136. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36137. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36138. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36139. // Create effects
  36140. this._createChromaticAberrationPostProcess(ratio);
  36141. this._createHighlightsPostProcess(ratio);
  36142. this._createDepthOfFieldPostProcess(ratio / 4);
  36143. // Set up pipeline
  36144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36147. if (this._highlightsGain === -1) {
  36148. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36149. }
  36150. // Finish
  36151. scene.postProcessRenderPipelineManager.addPipeline(this);
  36152. if (cameras) {
  36153. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36154. }
  36155. }
  36156. // public methods (self explanatory)
  36157. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36158. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36159. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36160. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36161. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36162. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36163. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36164. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36165. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36166. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36167. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36168. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36169. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36170. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36171. };
  36172. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36173. this._highlightsPostProcess.updateEffect();
  36174. };
  36175. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36176. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36177. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36178. this._highlightsGain = amount;
  36179. };
  36180. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36181. if (this._highlightsGain === -1) {
  36182. this._highlightsGain = 1.0;
  36183. }
  36184. this._highlightsThreshold = amount;
  36185. };
  36186. LensRenderingPipeline.prototype.disableHighlights = function () {
  36187. this._highlightsGain = -1;
  36188. };
  36189. /**
  36190. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36191. */
  36192. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36193. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36194. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36195. this._chromaticAberrationPostProcess = undefined;
  36196. this._highlightsPostProcess = undefined;
  36197. this._depthOfFieldPostProcess = undefined;
  36198. this._grainTexture.dispose();
  36199. if (disableDepthRender)
  36200. this._scene.disableDepthRenderer();
  36201. };
  36202. // colors shifting and distortion
  36203. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36204. var _this = this;
  36205. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36206. [], // samplers
  36207. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36208. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36209. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36210. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36211. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36212. };
  36213. };
  36214. // highlights enhancing
  36215. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36216. var _this = this;
  36217. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36218. [], // samplers
  36219. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36220. this._highlightsPostProcess.onApply = function (effect) {
  36221. effect.setFloat('gain', _this._highlightsGain);
  36222. effect.setFloat('threshold', _this._highlightsThreshold);
  36223. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36224. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36225. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36226. };
  36227. };
  36228. // colors shifting and distortion
  36229. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36230. var _this = this;
  36231. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36232. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36233. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36234. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36235. this._depthOfFieldPostProcess.onApply = function (effect) {
  36236. effect.setTexture("depthSampler", _this._depthTexture);
  36237. effect.setTexture("grainSampler", _this._grainTexture);
  36238. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36239. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36240. effect.setFloat('grain_amount', _this._grainAmount);
  36241. effect.setBool('blur_noise', _this._blurNoise);
  36242. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36243. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36244. effect.setFloat('distortion', _this._distortion);
  36245. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36246. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36247. effect.setFloat('aperture', _this._dofAperture);
  36248. effect.setFloat('darken', _this._dofDarken);
  36249. effect.setFloat('edge_blur', _this._edgeBlur);
  36250. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36251. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36252. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36253. };
  36254. };
  36255. // creates a black and white random noise texture, 512x512
  36256. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36257. var size = 512;
  36258. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36259. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36260. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36261. var context = this._grainTexture.getContext();
  36262. var rand = function (min, max) {
  36263. return Math.random() * (max - min) + min;
  36264. };
  36265. var value;
  36266. for (var x = 0; x < size; x++) {
  36267. for (var y = 0; y < size; y++) {
  36268. value = Math.floor(rand(0.42, 0.58) * 255);
  36269. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36270. context.fillRect(x, y, 1, 1);
  36271. }
  36272. }
  36273. this._grainTexture.update(false);
  36274. };
  36275. return LensRenderingPipeline;
  36276. })(BABYLON.PostProcessRenderPipeline);
  36277. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36278. })(BABYLON || (BABYLON = {}));
  36279. //
  36280. // This post-process allows the modification of rendered colors by using
  36281. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36282. //
  36283. // The object needs to be provided an url to a texture containing the color
  36284. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36285. // Use an image editing software to tweak the LUT to match your needs.
  36286. //
  36287. // For an example of a color LUT, see here:
  36288. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36289. // For explanations on color grading, see here:
  36290. // http://udn.epicgames.com/Three/ColorGrading.html
  36291. //
  36292. var BABYLON;
  36293. (function (BABYLON) {
  36294. var ColorCorrectionPostProcess = (function (_super) {
  36295. __extends(ColorCorrectionPostProcess, _super);
  36296. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36297. var _this = this;
  36298. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36299. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36300. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36301. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36302. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36303. this.onApply = function (effect) {
  36304. effect.setTexture("colorTable", _this._colorTableTexture);
  36305. };
  36306. }
  36307. return ColorCorrectionPostProcess;
  36308. })(BABYLON.PostProcess);
  36309. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36310. })(BABYLON || (BABYLON = {}));
  36311. var BABYLON;
  36312. (function (BABYLON) {
  36313. var AnaglyphFreeCamera = (function (_super) {
  36314. __extends(AnaglyphFreeCamera, _super);
  36315. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  36316. _super.call(this, name, position, scene);
  36317. this.interaxialDistance = interaxialDistance;
  36318. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36319. }
  36320. return AnaglyphFreeCamera;
  36321. })(BABYLON.FreeCamera);
  36322. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  36323. var AnaglyphArcRotateCamera = (function (_super) {
  36324. __extends(AnaglyphArcRotateCamera, _super);
  36325. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  36326. _super.call(this, name, alpha, beta, radius, target, scene);
  36327. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36328. }
  36329. return AnaglyphArcRotateCamera;
  36330. })(BABYLON.ArcRotateCamera);
  36331. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  36332. var AnaglyphGamepadCamera = (function (_super) {
  36333. __extends(AnaglyphGamepadCamera, _super);
  36334. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  36335. _super.call(this, name, position, scene);
  36336. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36337. }
  36338. return AnaglyphGamepadCamera;
  36339. })(BABYLON.GamepadCamera);
  36340. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  36341. var StereoscopicFreeCamera = (function (_super) {
  36342. __extends(StereoscopicFreeCamera, _super);
  36343. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  36344. _super.call(this, name, position, scene);
  36345. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36346. }
  36347. return StereoscopicFreeCamera;
  36348. })(BABYLON.FreeCamera);
  36349. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  36350. var StereoscopicArcRotateCamera = (function (_super) {
  36351. __extends(StereoscopicArcRotateCamera, _super);
  36352. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  36353. _super.call(this, name, alpha, beta, radius, target, scene);
  36354. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36355. }
  36356. return StereoscopicArcRotateCamera;
  36357. })(BABYLON.ArcRotateCamera);
  36358. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  36359. var StereoscopicGamepadCamera = (function (_super) {
  36360. __extends(StereoscopicGamepadCamera, _super);
  36361. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  36362. _super.call(this, name, position, scene);
  36363. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36364. }
  36365. return StereoscopicGamepadCamera;
  36366. })(BABYLON.GamepadCamera);
  36367. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  36368. })(BABYLON || (BABYLON = {}));
  36369. var BABYLON;
  36370. (function (BABYLON) {
  36371. var HDRRenderingPipeline = (function (_super) {
  36372. __extends(HDRRenderingPipeline, _super);
  36373. /**
  36374. * @constructor
  36375. * @param {string} name - The rendering pipeline name
  36376. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36377. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  36378. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36379. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36380. */
  36381. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36382. var _this = this;
  36383. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36384. _super.call(this, scene.getEngine(), name);
  36385. /**
  36386. * Public members
  36387. */
  36388. // Gaussian Blur
  36389. /**
  36390. * Gaussian blur coefficient
  36391. * @type {number}
  36392. */
  36393. this.gaussCoeff = 0.3;
  36394. /**
  36395. * Gaussian blur mean
  36396. * @type {number}
  36397. */
  36398. this.gaussMean = 1.0;
  36399. /**
  36400. * Gaussian blur standard deviation
  36401. * @type {number}
  36402. */
  36403. this.gaussStandDev = 0.8;
  36404. /**
  36405. * Gaussian blur multiplier. Multiplies the blur effect
  36406. * @type {number}
  36407. */
  36408. this.gaussMultiplier = 4.0;
  36409. // HDR
  36410. /**
  36411. * Exposure, controls the overall intensity of the pipeline
  36412. * @type {number}
  36413. */
  36414. this.exposure = 1.0;
  36415. /**
  36416. * Minimum luminance that the post-process can output. Luminance is >= 0
  36417. * @type {number}
  36418. */
  36419. this.minimumLuminance = 1.0;
  36420. /**
  36421. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36422. * @type {number}
  36423. */
  36424. this.maximumLuminance = 1e20;
  36425. /**
  36426. * Increase rate for luminance: eye adaptation speed to dark
  36427. * @type {number}
  36428. */
  36429. this.luminanceIncreaserate = 0.5;
  36430. /**
  36431. * Decrease rate for luminance: eye adaptation speed to bright
  36432. * @type {number}
  36433. */
  36434. this.luminanceDecreaseRate = 0.5;
  36435. // Bright pass
  36436. /**
  36437. * Minimum luminance needed to compute HDR
  36438. * @type {number}
  36439. */
  36440. this.brightThreshold = 0.8;
  36441. this._needUpdate = true;
  36442. this._scene = scene;
  36443. // Bright pass
  36444. this._createBrightPassPostProcess(scene, ratio);
  36445. // Down sample X4
  36446. this._createDownSampleX4PostProcess(scene, ratio);
  36447. // Create gaussian blur post-processes
  36448. this._createGaussianBlurPostProcess(scene, ratio);
  36449. // Texture adder
  36450. this._createTextureAdderPostProcess(scene, ratio);
  36451. // Luminance generator
  36452. this._createLuminanceGeneratorPostProcess(scene);
  36453. // HDR
  36454. this._createHDRPostProcess(scene, ratio);
  36455. // Pass postprocess
  36456. if (originalPostProcess === null) {
  36457. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36458. }
  36459. else {
  36460. this._originalPostProcess = originalPostProcess;
  36461. }
  36462. // Configure pipeline
  36463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36464. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36466. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36467. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36468. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36469. var addDownSamplerPostProcess = function (id) {
  36470. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36471. };
  36472. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36473. addDownSamplerPostProcess(i);
  36474. }
  36475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36476. // Finish
  36477. scene.postProcessRenderPipelineManager.addPipeline(this);
  36478. if (cameras !== null) {
  36479. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36480. }
  36481. this.update();
  36482. }
  36483. /**
  36484. * Tells the pipeline to update its post-processes
  36485. */
  36486. HDRRenderingPipeline.prototype.update = function () {
  36487. this._needUpdate = true;
  36488. };
  36489. /**
  36490. * Returns the current calculated luminance
  36491. */
  36492. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36493. return this._hdrCurrentLuminance;
  36494. };
  36495. /**
  36496. * Returns the currently drawn luminance
  36497. */
  36498. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36499. return this._hdrOutputLuminance;
  36500. };
  36501. /**
  36502. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36503. */
  36504. HDRRenderingPipeline.prototype.dispose = function () {
  36505. this._originalPostProcess = undefined;
  36506. this._brightPassPostProcess = undefined;
  36507. this._downSampleX4PostProcess = undefined;
  36508. this._guassianBlurHPostProcess = undefined;
  36509. this._guassianBlurVPostProcess = undefined;
  36510. this._textureAdderPostProcess = undefined;
  36511. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36512. this._downSamplePostProcesses[i] = undefined;
  36513. }
  36514. this._hdrPostProcess = undefined;
  36515. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36516. };
  36517. /**
  36518. * Creates the HDR post-process and computes the luminance adaptation
  36519. */
  36520. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36521. var _this = this;
  36522. var hdrLastLuminance = 0.0;
  36523. this._hdrOutputLuminance = -1.0;
  36524. this._hdrCurrentLuminance = 1.0;
  36525. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36526. this._hdrPostProcess.onApply = function (effect) {
  36527. if (_this._hdrOutputLuminance < 0.0) {
  36528. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36529. }
  36530. else {
  36531. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36532. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36533. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36534. }
  36535. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36536. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36537. }
  36538. else {
  36539. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36540. }
  36541. }
  36542. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36543. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36544. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36545. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36546. effect.setFloat("exposure", _this.exposure);
  36547. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36548. _this._needUpdate = false;
  36549. };
  36550. };
  36551. /**
  36552. * Texture Adder post-process
  36553. */
  36554. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36555. var _this = this;
  36556. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36557. this._textureAdderPostProcess.onApply = function (effect) {
  36558. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36559. };
  36560. };
  36561. /**
  36562. * Down sample X4 post-process
  36563. */
  36564. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36565. var _this = this;
  36566. var downSampleX4Offsets = new Array(32);
  36567. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36568. this._downSampleX4PostProcess.onApply = function (effect) {
  36569. if (_this._needUpdate) {
  36570. var id = 0;
  36571. for (var i = -2; i < 2; i++) {
  36572. for (var j = -2; j < 2; j++) {
  36573. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36574. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36575. id += 2;
  36576. }
  36577. }
  36578. }
  36579. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36580. };
  36581. };
  36582. /**
  36583. * Bright pass post-process
  36584. */
  36585. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36586. var _this = this;
  36587. var brightOffsets = new Array(8);
  36588. var brightPassCallback = function (effect) {
  36589. if (_this._needUpdate) {
  36590. var sU = (1.0 / _this._brightPassPostProcess.width);
  36591. var sV = (1.0 / _this._brightPassPostProcess.height);
  36592. brightOffsets[0] = -0.5 * sU;
  36593. brightOffsets[1] = 0.5 * sV;
  36594. brightOffsets[2] = 0.5 * sU;
  36595. brightOffsets[3] = 0.5 * sV;
  36596. brightOffsets[4] = -0.5 * sU;
  36597. brightOffsets[5] = -0.5 * sV;
  36598. brightOffsets[6] = 0.5 * sU;
  36599. brightOffsets[7] = -0.5 * sV;
  36600. }
  36601. effect.setArray2("dsOffsets", brightOffsets);
  36602. effect.setFloat("brightThreshold", _this.brightThreshold);
  36603. };
  36604. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36605. this._brightPassPostProcess.onApply = brightPassCallback;
  36606. };
  36607. /**
  36608. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36609. */
  36610. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36611. var _this = this;
  36612. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36613. var luminanceOffsets = new Array(8);
  36614. var downSampleOffsets = new Array(18);
  36615. var halfDestPixelSize;
  36616. this._downSamplePostProcesses = new Array(lumSteps);
  36617. // Utils for luminance
  36618. var luminanceUpdateSourceOffsets = function (width, height) {
  36619. var sU = (1.0 / width);
  36620. var sV = (1.0 / height);
  36621. luminanceOffsets[0] = -0.5 * sU;
  36622. luminanceOffsets[1] = 0.5 * sV;
  36623. luminanceOffsets[2] = 0.5 * sU;
  36624. luminanceOffsets[3] = 0.5 * sV;
  36625. luminanceOffsets[4] = -0.5 * sU;
  36626. luminanceOffsets[5] = -0.5 * sV;
  36627. luminanceOffsets[6] = 0.5 * sU;
  36628. luminanceOffsets[7] = -0.5 * sV;
  36629. };
  36630. var luminanceUpdateDestOffsets = function (width, height) {
  36631. var id = 0;
  36632. for (var x = -1; x < 2; x++) {
  36633. for (var y = -1; y < 2; y++) {
  36634. downSampleOffsets[id] = (x) / width;
  36635. downSampleOffsets[id + 1] = (y) / height;
  36636. id += 2;
  36637. }
  36638. }
  36639. };
  36640. // Luminance callback
  36641. var luminanceCallback = function (effect) {
  36642. if (_this._needUpdate) {
  36643. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36644. }
  36645. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36646. effect.setArray2("lumOffsets", luminanceOffsets);
  36647. };
  36648. // Down sample callbacks
  36649. var downSampleCallback = function (indice) {
  36650. var i = indice;
  36651. return function (effect) {
  36652. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36653. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36654. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36655. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36656. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36657. effect.setArray2("dsOffsets", downSampleOffsets);
  36658. };
  36659. };
  36660. var downSampleAfterRenderCallback = function (effect) {
  36661. // Unpack result
  36662. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36663. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  36664. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36665. };
  36666. // Create luminance post-process
  36667. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36668. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  36669. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36670. // Create down sample post-processes
  36671. for (var i = lumSteps - 2; i >= 0; i--) {
  36672. var length = Math.pow(3, i);
  36673. ratio = { width: length, height: length };
  36674. var defines = "#define DOWN_SAMPLE\n";
  36675. if (i === 0) {
  36676. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36677. }
  36678. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36679. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36680. if (i === 0) {
  36681. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36682. }
  36683. }
  36684. };
  36685. /**
  36686. * Gaussian blur post-processes. Horizontal and Vertical
  36687. */
  36688. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36689. var _this = this;
  36690. var blurOffsetsW = new Array(9);
  36691. var blurOffsetsH = new Array(9);
  36692. var blurWeights = new Array(9);
  36693. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36694. // Utils for gaussian blur
  36695. var calculateBlurOffsets = function (height) {
  36696. var lastOutputDimensions = {
  36697. width: scene.getEngine().getRenderWidth(),
  36698. height: scene.getEngine().getRenderHeight()
  36699. };
  36700. for (var i = 0; i < 9; i++) {
  36701. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36702. if (height) {
  36703. blurOffsetsH[i] = value;
  36704. }
  36705. else {
  36706. blurOffsetsW[i] = value;
  36707. }
  36708. }
  36709. };
  36710. var calculateWeights = function () {
  36711. var x = 0.0;
  36712. for (var i = 0; i < 9; i++) {
  36713. x = (i - 4.0) / 4.0;
  36714. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  36715. }
  36716. };
  36717. // Callback
  36718. var gaussianBlurCallback = function (height) {
  36719. return function (effect) {
  36720. if (_this._needUpdate) {
  36721. calculateWeights();
  36722. calculateBlurOffsets(height);
  36723. }
  36724. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36725. effect.setArray("blurWeights", blurWeights);
  36726. effect.setFloat("multiplier", _this.gaussMultiplier);
  36727. };
  36728. };
  36729. // Create horizontal gaussian blur post-processes
  36730. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36731. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36732. // Create vertical gaussian blur post-process
  36733. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36734. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36735. };
  36736. // Luminance generator
  36737. HDRRenderingPipeline.LUM_STEPS = 6;
  36738. return HDRRenderingPipeline;
  36739. })(BABYLON.PostProcessRenderPipeline);
  36740. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36741. })(BABYLON || (BABYLON = {}));
  36742. var BABYLON;
  36743. (function (BABYLON) {
  36744. var FaceAdjacencies = (function () {
  36745. function FaceAdjacencies() {
  36746. this.edges = new Array();
  36747. this.edgesConnectedCount = 0;
  36748. }
  36749. return FaceAdjacencies;
  36750. })();
  36751. var EdgesRenderer = (function () {
  36752. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36753. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36754. if (epsilon === void 0) { epsilon = 0.95; }
  36755. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36756. this.edgesWidthScalerForOrthographic = 1000.0;
  36757. this.edgesWidthScalerForPerspective = 50.0;
  36758. this._linesPositions = new Array();
  36759. this._linesNormals = new Array();
  36760. this._linesIndices = new Array();
  36761. this._buffers = new Array();
  36762. this._checkVerticesInsteadOfIndices = false;
  36763. this._source = source;
  36764. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36765. this._epsilon = epsilon;
  36766. this._prepareRessources();
  36767. this._generateEdgesLines();
  36768. }
  36769. EdgesRenderer.prototype._prepareRessources = function () {
  36770. if (this._lineShader) {
  36771. return;
  36772. }
  36773. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36774. attributes: ["position", "normal"],
  36775. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36776. });
  36777. this._lineShader.disableDepthWrite = true;
  36778. this._lineShader.backFaceCulling = false;
  36779. };
  36780. EdgesRenderer.prototype.dispose = function () {
  36781. this._vb0.dispose();
  36782. this._vb1.dispose();
  36783. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36784. this._lineShader.dispose();
  36785. };
  36786. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36787. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36788. return 0;
  36789. }
  36790. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36791. return 1;
  36792. }
  36793. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36794. return 2;
  36795. }
  36796. return -1;
  36797. };
  36798. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36799. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36800. return 0;
  36801. }
  36802. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36803. return 1;
  36804. }
  36805. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36806. return 2;
  36807. }
  36808. return -1;
  36809. };
  36810. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36811. var needToCreateLine;
  36812. if (edge === undefined) {
  36813. needToCreateLine = true;
  36814. }
  36815. else {
  36816. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36817. needToCreateLine = dotProduct < this._epsilon;
  36818. }
  36819. if (needToCreateLine) {
  36820. var offset = this._linesPositions.length / 3;
  36821. var normal = p0.subtract(p1);
  36822. normal.normalize();
  36823. // Positions
  36824. this._linesPositions.push(p0.x);
  36825. this._linesPositions.push(p0.y);
  36826. this._linesPositions.push(p0.z);
  36827. this._linesPositions.push(p0.x);
  36828. this._linesPositions.push(p0.y);
  36829. this._linesPositions.push(p0.z);
  36830. this._linesPositions.push(p1.x);
  36831. this._linesPositions.push(p1.y);
  36832. this._linesPositions.push(p1.z);
  36833. this._linesPositions.push(p1.x);
  36834. this._linesPositions.push(p1.y);
  36835. this._linesPositions.push(p1.z);
  36836. // Normals
  36837. this._linesNormals.push(p1.x);
  36838. this._linesNormals.push(p1.y);
  36839. this._linesNormals.push(p1.z);
  36840. this._linesNormals.push(-1);
  36841. this._linesNormals.push(p1.x);
  36842. this._linesNormals.push(p1.y);
  36843. this._linesNormals.push(p1.z);
  36844. this._linesNormals.push(1);
  36845. this._linesNormals.push(p0.x);
  36846. this._linesNormals.push(p0.y);
  36847. this._linesNormals.push(p0.z);
  36848. this._linesNormals.push(-1);
  36849. this._linesNormals.push(p0.x);
  36850. this._linesNormals.push(p0.y);
  36851. this._linesNormals.push(p0.z);
  36852. this._linesNormals.push(1);
  36853. // Indices
  36854. this._linesIndices.push(offset);
  36855. this._linesIndices.push(offset + 1);
  36856. this._linesIndices.push(offset + 2);
  36857. this._linesIndices.push(offset);
  36858. this._linesIndices.push(offset + 2);
  36859. this._linesIndices.push(offset + 3);
  36860. }
  36861. };
  36862. EdgesRenderer.prototype._generateEdgesLines = function () {
  36863. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36864. var indices = this._source.getIndices();
  36865. // First let's find adjacencies
  36866. var adjacencies = new Array();
  36867. var faceNormals = new Array();
  36868. var index;
  36869. var faceAdjacencies;
  36870. // Prepare faces
  36871. for (index = 0; index < indices.length; index += 3) {
  36872. faceAdjacencies = new FaceAdjacencies();
  36873. var p0Index = indices[index];
  36874. var p1Index = indices[index + 1];
  36875. var p2Index = indices[index + 2];
  36876. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36877. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36878. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36879. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36880. faceNormal.normalize();
  36881. faceNormals.push(faceNormal);
  36882. adjacencies.push(faceAdjacencies);
  36883. }
  36884. // Scan
  36885. for (index = 0; index < adjacencies.length; index++) {
  36886. faceAdjacencies = adjacencies[index];
  36887. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36888. var otherFaceAdjacencies = adjacencies[otherIndex];
  36889. if (faceAdjacencies.edgesConnectedCount === 3) {
  36890. break;
  36891. }
  36892. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36893. continue;
  36894. }
  36895. var otherP0 = indices[otherIndex * 3];
  36896. var otherP1 = indices[otherIndex * 3 + 1];
  36897. var otherP2 = indices[otherIndex * 3 + 2];
  36898. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36899. var otherEdgeIndex;
  36900. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36901. continue;
  36902. }
  36903. switch (edgeIndex) {
  36904. case 0:
  36905. if (this._checkVerticesInsteadOfIndices) {
  36906. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36907. }
  36908. else {
  36909. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36910. }
  36911. break;
  36912. case 1:
  36913. if (this._checkVerticesInsteadOfIndices) {
  36914. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36915. }
  36916. else {
  36917. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36918. }
  36919. break;
  36920. case 2:
  36921. if (this._checkVerticesInsteadOfIndices) {
  36922. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36923. }
  36924. else {
  36925. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36926. }
  36927. break;
  36928. }
  36929. if (otherEdgeIndex === -1) {
  36930. continue;
  36931. }
  36932. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36933. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36934. faceAdjacencies.edgesConnectedCount++;
  36935. otherFaceAdjacencies.edgesConnectedCount++;
  36936. if (faceAdjacencies.edgesConnectedCount === 3) {
  36937. break;
  36938. }
  36939. }
  36940. }
  36941. }
  36942. // Create lines
  36943. for (index = 0; index < adjacencies.length; index++) {
  36944. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  36945. var current = adjacencies[index];
  36946. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36947. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36948. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36949. }
  36950. // Merge into a single mesh
  36951. var engine = this._source.getScene().getEngine();
  36952. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36953. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36954. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36955. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36956. this._ib = engine.createIndexBuffer(this._linesIndices);
  36957. this._indicesCount = this._linesIndices.length;
  36958. };
  36959. EdgesRenderer.prototype.render = function () {
  36960. if (!this._lineShader.isReady()) {
  36961. return;
  36962. }
  36963. var scene = this._source.getScene();
  36964. var engine = scene.getEngine();
  36965. this._lineShader._preBind();
  36966. // VBOs
  36967. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36968. scene.resetCachedMaterial();
  36969. this._lineShader.setColor4("color", this._source.edgesColor);
  36970. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36971. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36972. }
  36973. else {
  36974. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36975. }
  36976. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36977. this._lineShader.bind(this._source.getWorldMatrix());
  36978. // Draw order
  36979. engine.draw(true, 0, this._indicesCount);
  36980. this._lineShader.unbind();
  36981. engine.setDepthWrite(true);
  36982. };
  36983. return EdgesRenderer;
  36984. })();
  36985. BABYLON.EdgesRenderer = EdgesRenderer;
  36986. })(BABYLON || (BABYLON = {}));
  36987. var BABYLON;
  36988. (function (BABYLON) {
  36989. (function (TonemappingOperator) {
  36990. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36991. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36992. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36993. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36994. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36995. var TonemappingOperator = BABYLON.TonemappingOperator;
  36996. ;
  36997. var TonemapPostProcess = (function (_super) {
  36998. __extends(TonemapPostProcess, _super);
  36999. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37000. var _this = this;
  37001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37002. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37003. this._operator = operator;
  37004. this.exposureAdjustment = exposureAdjustment;
  37005. var params = ["_ExposureAdjustment"];
  37006. var defines = "#define ";
  37007. if (operator === TonemappingOperator.Hable)
  37008. defines += "HABLE_TONEMAPPING";
  37009. else if (operator === TonemappingOperator.Reinhard)
  37010. defines += "REINHARD_TONEMAPPING";
  37011. else if (operator === TonemappingOperator.HejiDawson)
  37012. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37013. else if (operator === TonemappingOperator.Photographic)
  37014. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37015. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37016. this.onApply = function (effect) {
  37017. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37018. };
  37019. }
  37020. return TonemapPostProcess;
  37021. })(BABYLON.PostProcess);
  37022. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37023. })(BABYLON || (BABYLON = {}));
  37024. var BABYLON;
  37025. (function (BABYLON) {
  37026. var ReflectionProbe = (function () {
  37027. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37028. var _this = this;
  37029. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37030. this.name = name;
  37031. this._viewMatrix = BABYLON.Matrix.Identity();
  37032. this._target = BABYLON.Vector3.Zero();
  37033. this._add = BABYLON.Vector3.Zero();
  37034. this.position = BABYLON.Vector3.Zero();
  37035. this._scene = scene;
  37036. this._scene.reflectionProbes.push(this);
  37037. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37038. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37039. switch (faceIndex) {
  37040. case 0:
  37041. _this._add.copyFromFloats(1, 0, 0);
  37042. break;
  37043. case 1:
  37044. _this._add.copyFromFloats(-1, 0, 0);
  37045. break;
  37046. case 2:
  37047. _this._add.copyFromFloats(0, -1, 0);
  37048. break;
  37049. case 3:
  37050. _this._add.copyFromFloats(0, 1, 0);
  37051. break;
  37052. case 4:
  37053. _this._add.copyFromFloats(0, 0, 1);
  37054. break;
  37055. case 5:
  37056. _this._add.copyFromFloats(0, 0, -1);
  37057. break;
  37058. }
  37059. if (_this._attachedMesh) {
  37060. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37061. }
  37062. _this.position.addToRef(_this._add, _this._target);
  37063. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37064. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37065. };
  37066. this._renderTargetTexture.onAfterUnbind = function () {
  37067. scene.updateTransformMatrix(true);
  37068. };
  37069. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37070. }
  37071. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37072. get: function () {
  37073. return this._renderTargetTexture.refreshRate;
  37074. },
  37075. set: function (value) {
  37076. this._renderTargetTexture.refreshRate = value;
  37077. },
  37078. enumerable: true,
  37079. configurable: true
  37080. });
  37081. ReflectionProbe.prototype.getScene = function () {
  37082. return this._scene;
  37083. };
  37084. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37085. get: function () {
  37086. return this._renderTargetTexture;
  37087. },
  37088. enumerable: true,
  37089. configurable: true
  37090. });
  37091. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37092. get: function () {
  37093. return this._renderTargetTexture.renderList;
  37094. },
  37095. enumerable: true,
  37096. configurable: true
  37097. });
  37098. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37099. this._attachedMesh = mesh;
  37100. };
  37101. ReflectionProbe.prototype.dispose = function () {
  37102. var index = this._scene.reflectionProbes.indexOf(this);
  37103. if (index !== -1) {
  37104. // Remove from the scene if found
  37105. this._scene.reflectionProbes.splice(index, 1);
  37106. }
  37107. if (this._renderTargetTexture) {
  37108. this._renderTargetTexture.dispose();
  37109. this._renderTargetTexture = null;
  37110. }
  37111. };
  37112. return ReflectionProbe;
  37113. })();
  37114. BABYLON.ReflectionProbe = ReflectionProbe;
  37115. })(BABYLON || (BABYLON = {}));
  37116. var BABYLON;
  37117. (function (BABYLON) {
  37118. var SolidParticle = (function () {
  37119. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37120. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37121. this.position = BABYLON.Vector3.Zero(); // position
  37122. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37123. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37124. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37125. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37126. this.alive = true; // alive
  37127. this.idx = particleIndex;
  37128. this._pos = positionIndex;
  37129. this._model = model;
  37130. this.shapeId = shapeId;
  37131. this.idxInShape = idxInShape;
  37132. }
  37133. return SolidParticle;
  37134. })();
  37135. BABYLON.SolidParticle = SolidParticle;
  37136. var ModelShape = (function () {
  37137. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37138. this.shapeID = id;
  37139. this._shape = shape;
  37140. this._shapeUV = shapeUV;
  37141. this._positionFunction = posFunction;
  37142. this._vertexFunction = vtxFunction;
  37143. }
  37144. return ModelShape;
  37145. })();
  37146. BABYLON.ModelShape = ModelShape;
  37147. })(BABYLON || (BABYLON = {}));
  37148. var BABYLON;
  37149. (function (BABYLON) {
  37150. /**
  37151. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37152. */
  37153. var SolidParticleSystem = (function () {
  37154. /**
  37155. * Creates a SPS (Solid Particle System) object.
  37156. * @param name the SPS name, this will be the underlying mesh name
  37157. * @param updatable (default true) if the SPS must be updatable or immutable
  37158. * @param isPickable (default false) if the solid particles must be pickable
  37159. */
  37160. function SolidParticleSystem(name, scene, options) {
  37161. // public members
  37162. this.particles = new Array();
  37163. this.nbParticles = 0;
  37164. this.billboard = false;
  37165. this.counter = 0;
  37166. this.vars = {};
  37167. this._positions = new Array();
  37168. this._indices = new Array();
  37169. this._normals = new Array();
  37170. this._colors = new Array();
  37171. this._uvs = new Array();
  37172. this._index = 0; // indices index
  37173. this._updatable = true;
  37174. this._pickable = false;
  37175. this._isVisibilityBoxLocked = false;
  37176. this._alwaysVisible = false;
  37177. this._shapeCounter = 0;
  37178. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37179. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37180. this._computeParticleColor = true;
  37181. this._computeParticleTexture = true;
  37182. this._computeParticleRotation = true;
  37183. this._computeParticleVertex = false;
  37184. this._cam_axisZ = BABYLON.Vector3.Zero();
  37185. this._cam_axisY = BABYLON.Vector3.Zero();
  37186. this._cam_axisX = BABYLON.Vector3.Zero();
  37187. this._axisX = BABYLON.Axis.X;
  37188. this._axisY = BABYLON.Axis.Y;
  37189. this._axisZ = BABYLON.Axis.Z;
  37190. this._fakeCamPos = BABYLON.Vector3.Zero();
  37191. this._rotMatrix = new BABYLON.Matrix();
  37192. this._invertMatrix = new BABYLON.Matrix();
  37193. this._rotated = BABYLON.Vector3.Zero();
  37194. this._quaternion = new BABYLON.Quaternion();
  37195. this._vertex = BABYLON.Vector3.Zero();
  37196. this._normal = BABYLON.Vector3.Zero();
  37197. this._yaw = 0.0;
  37198. this._pitch = 0.0;
  37199. this._roll = 0.0;
  37200. this._halfroll = 0.0;
  37201. this._halfpitch = 0.0;
  37202. this._halfyaw = 0.0;
  37203. this._sinRoll = 0.0;
  37204. this._cosRoll = 0.0;
  37205. this._sinPitch = 0.0;
  37206. this._cosPitch = 0.0;
  37207. this._sinYaw = 0.0;
  37208. this._cosYaw = 0.0;
  37209. this._w = 0.0;
  37210. this.name = name;
  37211. this._scene = scene;
  37212. this._camera = scene.activeCamera;
  37213. this._pickable = options ? options.isPickable : false;
  37214. if (options && options.updatable) {
  37215. this._updatable = options.updatable;
  37216. }
  37217. else {
  37218. this._updatable = true;
  37219. }
  37220. if (this._pickable) {
  37221. this.pickedParticles = [];
  37222. }
  37223. }
  37224. /**
  37225. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37226. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37227. */
  37228. SolidParticleSystem.prototype.buildMesh = function () {
  37229. if (this.nbParticles === 0) {
  37230. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37231. this.addShape(triangle, 1);
  37232. triangle.dispose();
  37233. }
  37234. this._positions32 = new Float32Array(this._positions);
  37235. this._uvs32 = new Float32Array(this._uvs);
  37236. this._colors32 = new Float32Array(this._colors);
  37237. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37238. this._normals32 = new Float32Array(this._normals);
  37239. this._fixedNormal32 = new Float32Array(this._normals);
  37240. var vertexData = new BABYLON.VertexData();
  37241. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37242. vertexData.indices = this._indices;
  37243. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37244. if (this._uvs32) {
  37245. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37246. ;
  37247. }
  37248. if (this._colors32) {
  37249. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37250. }
  37251. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37252. vertexData.applyToMesh(mesh, this._updatable);
  37253. this.mesh = mesh;
  37254. this.mesh.isPickable = this._pickable;
  37255. // free memory
  37256. this._positions = null;
  37257. this._normals = null;
  37258. this._uvs = null;
  37259. this._colors = null;
  37260. if (!this._updatable) {
  37261. this.particles.length = 0;
  37262. }
  37263. return mesh;
  37264. };
  37265. /**
  37266. * Digests the mesh and generates as many solid particles in the system as wanted.
  37267. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37268. * Thus the particles generated from digest() have their property "positiion" yet set.
  37269. * @param mesh the mesh to be digested
  37270. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37271. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37272. */
  37273. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37274. var size = (options && options.facetNb) || 1;
  37275. var number = (options && options.number);
  37276. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37277. var meshInd = mesh.getIndices();
  37278. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37279. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37280. var f = 0; // facet counter
  37281. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37282. // compute size from number
  37283. if (number) {
  37284. number = (number > totalFacets) ? totalFacets : number;
  37285. size = Math.round(totalFacets / number);
  37286. }
  37287. else {
  37288. size = (size > totalFacets) ? totalFacets : size;
  37289. }
  37290. var facetPos = []; // submesh positions
  37291. var facetInd = []; // submesh indices
  37292. var facetUV = []; // submesh UV
  37293. var facetCol = []; // submesh colors
  37294. var barycenter = BABYLON.Tmp.Vector3[0];
  37295. while (f < totalFacets) {
  37296. if (f > totalFacets - size) {
  37297. size = totalFacets - f;
  37298. }
  37299. // reset temp arrays
  37300. facetPos.length = 0;
  37301. facetInd.length = 0;
  37302. facetUV.length = 0;
  37303. facetCol.length = 0;
  37304. // iterate over "size" facets
  37305. var fi = 0;
  37306. for (var j = f * 3; j < (f + size) * 3; j++) {
  37307. facetInd.push(fi);
  37308. var i = meshInd[j];
  37309. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37310. if (meshUV) {
  37311. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37312. }
  37313. if (meshCol) {
  37314. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37315. }
  37316. fi++;
  37317. }
  37318. // create a model shape for each single particle
  37319. var idx = this.nbParticles;
  37320. var shape = this._posToShape(facetPos);
  37321. var shapeUV = this._uvsToShapeUV(facetUV);
  37322. // compute the barycenter of the shape
  37323. var v;
  37324. for (v = 0; v < shape.length; v++) {
  37325. barycenter.addInPlace(shape[v]);
  37326. }
  37327. barycenter.scaleInPlace(1 / shape.length);
  37328. // shift the shape from its barycenter to the origin
  37329. for (v = 0; v < shape.length; v++) {
  37330. shape[v].subtractInPlace(barycenter);
  37331. }
  37332. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37333. // add the particle in the SPS
  37334. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37335. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37336. // initialize the particle position
  37337. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37338. this._index += shape.length;
  37339. idx++;
  37340. this.nbParticles++;
  37341. this._shapeCounter++;
  37342. f += size;
  37343. }
  37344. };
  37345. //reset copy
  37346. SolidParticleSystem.prototype._resetCopy = function () {
  37347. this._copy.position.x = 0;
  37348. this._copy.position.y = 0;
  37349. this._copy.position.z = 0;
  37350. this._copy.rotation.x = 0;
  37351. this._copy.rotation.y = 0;
  37352. this._copy.rotation.z = 0;
  37353. this._copy.quaternion = null;
  37354. this._copy.scale.x = 1;
  37355. this._copy.scale.y = 1;
  37356. this._copy.scale.z = 1;
  37357. this._copy.uvs.x = 0;
  37358. this._copy.uvs.y = 0;
  37359. this._copy.uvs.z = 1;
  37360. this._copy.uvs.w = 1;
  37361. this._copy.color = null;
  37362. };
  37363. // _meshBuilder : inserts the shape model in the global SPS mesh
  37364. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37365. var i;
  37366. var u = 0;
  37367. var c = 0;
  37368. this._resetCopy();
  37369. if (options && options.positionFunction) {
  37370. options.positionFunction(this._copy, idx, idxInShape);
  37371. }
  37372. if (this._copy.quaternion) {
  37373. this._quaternion.x = this._copy.quaternion.x;
  37374. this._quaternion.y = this._copy.quaternion.y;
  37375. this._quaternion.z = this._copy.quaternion.z;
  37376. this._quaternion.w = this._copy.quaternion.w;
  37377. }
  37378. else {
  37379. this._yaw = this._copy.rotation.y;
  37380. this._pitch = this._copy.rotation.x;
  37381. this._roll = this._copy.rotation.z;
  37382. this._quaternionRotationYPR();
  37383. }
  37384. this._quaternionToRotationMatrix();
  37385. for (i = 0; i < shape.length; i++) {
  37386. this._vertex.x = shape[i].x;
  37387. this._vertex.y = shape[i].y;
  37388. this._vertex.z = shape[i].z;
  37389. if (options && options.vertexFunction) {
  37390. options.vertexFunction(this._copy, this._vertex, i);
  37391. }
  37392. this._vertex.x *= this._copy.scale.x;
  37393. this._vertex.y *= this._copy.scale.y;
  37394. this._vertex.z *= this._copy.scale.z;
  37395. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37396. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37397. if (meshUV) {
  37398. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  37399. u += 2;
  37400. }
  37401. if (this._copy.color) {
  37402. this._color = this._copy.color;
  37403. }
  37404. else if (meshCol && meshCol[c]) {
  37405. this._color.r = meshCol[c];
  37406. this._color.g = meshCol[c + 1];
  37407. this._color.b = meshCol[c + 2];
  37408. this._color.a = meshCol[c + 3];
  37409. }
  37410. else {
  37411. this._color.r = 1;
  37412. this._color.g = 1;
  37413. this._color.b = 1;
  37414. this._color.a = 1;
  37415. }
  37416. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37417. c += 4;
  37418. }
  37419. for (i = 0; i < meshInd.length; i++) {
  37420. indices.push(p + meshInd[i]);
  37421. }
  37422. if (this._pickable) {
  37423. var nbfaces = meshInd.length / 3;
  37424. for (i = 0; i < nbfaces; i++) {
  37425. this.pickedParticles.push({ idx: idx, faceId: i });
  37426. }
  37427. }
  37428. };
  37429. // returns a shape array from positions array
  37430. SolidParticleSystem.prototype._posToShape = function (positions) {
  37431. var shape = [];
  37432. for (var i = 0; i < positions.length; i += 3) {
  37433. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37434. }
  37435. return shape;
  37436. };
  37437. // returns a shapeUV array from a Vector4 uvs
  37438. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37439. var shapeUV = [];
  37440. if (uvs) {
  37441. for (var i = 0; i < uvs.length; i++)
  37442. shapeUV.push(uvs[i]);
  37443. }
  37444. return shapeUV;
  37445. };
  37446. // adds a new particle object in the particles array
  37447. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37448. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37449. };
  37450. /**
  37451. * Adds some particles to the SPS from the model shape.
  37452. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37453. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37454. * @param nb the number of particles to be created from this model
  37455. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  37456. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37457. */
  37458. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37459. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37460. var meshInd = mesh.getIndices();
  37461. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37462. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37463. var shape = this._posToShape(meshPos);
  37464. var shapeUV = this._uvsToShapeUV(meshUV);
  37465. var posfunc = options ? options.positionFunction : null;
  37466. var vtxfunc = options ? options.vertexFunction : null;
  37467. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37468. // particles
  37469. var idx = this.nbParticles;
  37470. for (var i = 0; i < nb; i++) {
  37471. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37472. if (this._updatable) {
  37473. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37474. }
  37475. this._index += shape.length;
  37476. idx++;
  37477. }
  37478. this.nbParticles += nb;
  37479. this._shapeCounter++;
  37480. return this._shapeCounter - 1;
  37481. };
  37482. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37483. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37484. this._resetCopy();
  37485. if (particle._model._positionFunction) {
  37486. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37487. }
  37488. if (this._copy.quaternion) {
  37489. this._quaternion.x = this._copy.quaternion.x;
  37490. this._quaternion.y = this._copy.quaternion.y;
  37491. this._quaternion.z = this._copy.quaternion.z;
  37492. this._quaternion.w = this._copy.quaternion.w;
  37493. }
  37494. else {
  37495. this._yaw = this._copy.rotation.y;
  37496. this._pitch = this._copy.rotation.x;
  37497. this._roll = this._copy.rotation.z;
  37498. this._quaternionRotationYPR();
  37499. }
  37500. this._quaternionToRotationMatrix();
  37501. this._shape = particle._model._shape;
  37502. for (var pt = 0; pt < this._shape.length; pt++) {
  37503. this._vertex.x = this._shape[pt].x;
  37504. this._vertex.y = this._shape[pt].y;
  37505. this._vertex.z = this._shape[pt].z;
  37506. if (particle._model._vertexFunction) {
  37507. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37508. }
  37509. this._vertex.x *= this._copy.scale.x;
  37510. this._vertex.y *= this._copy.scale.y;
  37511. this._vertex.z *= this._copy.scale.z;
  37512. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37513. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37514. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37515. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37516. }
  37517. particle.position.x = 0;
  37518. particle.position.y = 0;
  37519. particle.position.z = 0;
  37520. particle.rotation.x = 0;
  37521. particle.rotation.y = 0;
  37522. particle.rotation.z = 0;
  37523. particle.quaternion = null;
  37524. particle.scale.x = 1;
  37525. particle.scale.y = 1;
  37526. particle.scale.z = 1;
  37527. };
  37528. /**
  37529. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37530. */
  37531. SolidParticleSystem.prototype.rebuildMesh = function () {
  37532. for (var p = 0; p < this.particles.length; p++) {
  37533. this._rebuildParticle(this.particles[p]);
  37534. }
  37535. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37536. };
  37537. /**
  37538. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37539. * This method calls updateParticle() for each particles of the SPS.
  37540. * For an animated SPS, it is usually called within the render loop.
  37541. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37542. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37543. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37544. */
  37545. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37546. if (start === void 0) { start = 0; }
  37547. if (end === void 0) { end = this.nbParticles - 1; }
  37548. if (update === void 0) { update = true; }
  37549. if (!this._updatable) {
  37550. return;
  37551. }
  37552. // custom beforeUpdate
  37553. this.beforeUpdateParticles(start, end, update);
  37554. this._cam_axisX.x = 1;
  37555. this._cam_axisX.y = 0;
  37556. this._cam_axisX.z = 0;
  37557. this._cam_axisY.x = 0;
  37558. this._cam_axisY.y = 1;
  37559. this._cam_axisY.z = 0;
  37560. this._cam_axisZ.x = 0;
  37561. this._cam_axisZ.y = 0;
  37562. this._cam_axisZ.z = 1;
  37563. // if the particles will always face the camera
  37564. if (this.billboard) {
  37565. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37566. this._yaw = this.mesh.rotation.y;
  37567. this._pitch = this.mesh.rotation.x;
  37568. this._roll = this.mesh.rotation.z;
  37569. this._quaternionRotationYPR();
  37570. this._quaternionToRotationMatrix();
  37571. this._rotMatrix.invertToRef(this._invertMatrix);
  37572. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37573. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37574. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37575. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37576. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37577. this._cam_axisY.normalize();
  37578. this._cam_axisX.normalize();
  37579. this._cam_axisZ.normalize();
  37580. }
  37581. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37582. var idx = 0;
  37583. var index = 0;
  37584. var colidx = 0;
  37585. var colorIndex = 0;
  37586. var uvidx = 0;
  37587. var uvIndex = 0;
  37588. // particle loop
  37589. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37590. for (var p = start; p <= end; p++) {
  37591. this._particle = this.particles[p];
  37592. this._shape = this._particle._model._shape;
  37593. this._shapeUV = this._particle._model._shapeUV;
  37594. // call to custom user function to update the particle properties
  37595. this.updateParticle(this._particle);
  37596. // particle rotation matrix
  37597. if (this.billboard) {
  37598. this._particle.rotation.x = 0.0;
  37599. this._particle.rotation.y = 0.0;
  37600. }
  37601. if (this._computeParticleRotation) {
  37602. if (this._particle.quaternion) {
  37603. this._quaternion.x = this._particle.quaternion.x;
  37604. this._quaternion.y = this._particle.quaternion.y;
  37605. this._quaternion.z = this._particle.quaternion.z;
  37606. this._quaternion.w = this._particle.quaternion.w;
  37607. }
  37608. else {
  37609. this._yaw = this._particle.rotation.y;
  37610. this._pitch = this._particle.rotation.x;
  37611. this._roll = this._particle.rotation.z;
  37612. this._quaternionRotationYPR();
  37613. }
  37614. this._quaternionToRotationMatrix();
  37615. }
  37616. for (var pt = 0; pt < this._shape.length; pt++) {
  37617. idx = index + pt * 3;
  37618. colidx = colorIndex + pt * 4;
  37619. uvidx = uvIndex + pt * 2;
  37620. this._vertex.x = this._shape[pt].x;
  37621. this._vertex.y = this._shape[pt].y;
  37622. this._vertex.z = this._shape[pt].z;
  37623. if (this._computeParticleVertex) {
  37624. this.updateParticleVertex(this._particle, this._vertex, pt);
  37625. }
  37626. // positions
  37627. this._vertex.x *= this._particle.scale.x;
  37628. this._vertex.y *= this._particle.scale.y;
  37629. this._vertex.z *= this._particle.scale.z;
  37630. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37631. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37632. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37633. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37634. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37635. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  37636. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  37637. // normals : if the particles can't be morphed then just rotate the normals
  37638. if (!this._computeParticleVertex && !this.billboard) {
  37639. this._normal.x = this._fixedNormal32[idx];
  37640. this._normal.y = this._fixedNormal32[idx + 1];
  37641. this._normal.z = this._fixedNormal32[idx + 2];
  37642. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37643. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37644. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37645. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37646. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37647. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  37648. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  37649. }
  37650. if (this._computeParticleColor) {
  37651. this._colors32[colidx] = this._particle.color.r;
  37652. this._colors32[colidx + 1] = this._particle.color.g;
  37653. this._colors32[colidx + 2] = this._particle.color.b;
  37654. this._colors32[colidx + 3] = this._particle.color.a;
  37655. }
  37656. if (this._computeParticleTexture) {
  37657. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37658. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37659. }
  37660. }
  37661. index = idx + 3;
  37662. colorIndex = colidx + 4;
  37663. uvIndex = uvidx + 2;
  37664. }
  37665. if (update) {
  37666. if (this._computeParticleColor) {
  37667. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37668. }
  37669. if (this._computeParticleTexture) {
  37670. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37671. }
  37672. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37673. if (!this.mesh.areNormalsFrozen) {
  37674. if (this._computeParticleVertex || this.billboard) {
  37675. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37676. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37677. for (var i = 0; i < this._normals32.length; i++) {
  37678. this._fixedNormal32[i] = this._normals32[i];
  37679. }
  37680. }
  37681. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37682. }
  37683. }
  37684. this.afterUpdateParticles(start, end, update);
  37685. };
  37686. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37687. this._halfroll = this._roll * 0.5;
  37688. this._halfpitch = this._pitch * 0.5;
  37689. this._halfyaw = this._yaw * 0.5;
  37690. this._sinRoll = Math.sin(this._halfroll);
  37691. this._cosRoll = Math.cos(this._halfroll);
  37692. this._sinPitch = Math.sin(this._halfpitch);
  37693. this._cosPitch = Math.cos(this._halfpitch);
  37694. this._sinYaw = Math.sin(this._halfyaw);
  37695. this._cosYaw = Math.cos(this._halfyaw);
  37696. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37697. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37698. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37699. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37700. };
  37701. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37702. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37703. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37704. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37705. this._rotMatrix.m[3] = 0;
  37706. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37707. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37708. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37709. this._rotMatrix.m[7] = 0;
  37710. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37711. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37712. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37713. this._rotMatrix.m[11] = 0;
  37714. this._rotMatrix.m[12] = 0;
  37715. this._rotMatrix.m[13] = 0;
  37716. this._rotMatrix.m[14] = 0;
  37717. this._rotMatrix.m[15] = 1.0;
  37718. };
  37719. /**
  37720. * Disposes the SPS
  37721. */
  37722. SolidParticleSystem.prototype.dispose = function () {
  37723. this.mesh.dispose();
  37724. this.vars = null;
  37725. // drop references to internal big arrays for the GC
  37726. this._positions = null;
  37727. this._indices = null;
  37728. this._normals = null;
  37729. this._uvs = null;
  37730. this._colors = null;
  37731. this._positions32 = null;
  37732. this._normals32 = null;
  37733. this._fixedNormal32 = null;
  37734. this._uvs32 = null;
  37735. this._colors32 = null;
  37736. this.pickedParticles = null;
  37737. };
  37738. /**
  37739. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37740. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37741. */
  37742. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37743. if (!this._isVisibilityBoxLocked) {
  37744. this.mesh.refreshBoundingInfo();
  37745. }
  37746. };
  37747. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37748. * @param size the size (float) of the visibility box
  37749. * note : this doesn't lock the SPS mesh bounding box.
  37750. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37751. */
  37752. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37753. var vis = size / 2;
  37754. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37755. };
  37756. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37757. // getter and setter
  37758. /**
  37759. * True if the SPS is set as always visible
  37760. */
  37761. get: function () {
  37762. return this._alwaysVisible;
  37763. },
  37764. /**
  37765. * Sets the SPS as always visible or not
  37766. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37767. */
  37768. set: function (val) {
  37769. this._alwaysVisible = val;
  37770. this.mesh.alwaysSelectAsActiveMesh = val;
  37771. },
  37772. enumerable: true,
  37773. configurable: true
  37774. });
  37775. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37776. /**
  37777. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37778. */
  37779. get: function () {
  37780. return this._isVisibilityBoxLocked;
  37781. },
  37782. /**
  37783. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37784. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37785. */
  37786. set: function (val) {
  37787. this._isVisibilityBoxLocked = val;
  37788. this.mesh.getBoundingInfo().isLocked = val;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37794. // getters
  37795. get: function () {
  37796. return this._computeParticleRotation;
  37797. },
  37798. // Optimizer setters
  37799. /**
  37800. * Tells to setParticle() to compute the particle rotations or not.
  37801. * Default value : true. The SPS is faster when it's set to false.
  37802. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37803. */
  37804. set: function (val) {
  37805. this._computeParticleRotation = val;
  37806. },
  37807. enumerable: true,
  37808. configurable: true
  37809. });
  37810. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37811. get: function () {
  37812. return this._computeParticleColor;
  37813. },
  37814. /**
  37815. * Tells to setParticle() to compute the particle colors or not.
  37816. * Default value : true. The SPS is faster when it's set to false.
  37817. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37818. */
  37819. set: function (val) {
  37820. this._computeParticleColor = val;
  37821. },
  37822. enumerable: true,
  37823. configurable: true
  37824. });
  37825. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37826. get: function () {
  37827. return this._computeParticleTexture;
  37828. },
  37829. /**
  37830. * Tells to setParticle() to compute the particle textures or not.
  37831. * Default value : true. The SPS is faster when it's set to false.
  37832. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37833. */
  37834. set: function (val) {
  37835. this._computeParticleTexture = val;
  37836. },
  37837. enumerable: true,
  37838. configurable: true
  37839. });
  37840. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37841. get: function () {
  37842. return this._computeParticleVertex;
  37843. },
  37844. /**
  37845. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37846. * Default value : false. The SPS is faster when it's set to false.
  37847. * Note : the particle custom vertex positions aren't stored values.
  37848. */
  37849. set: function (val) {
  37850. this._computeParticleVertex = val;
  37851. },
  37852. enumerable: true,
  37853. configurable: true
  37854. });
  37855. // =======================================================================
  37856. // Particle behavior logic
  37857. // these following methods may be overwritten by the user to fit his needs
  37858. /**
  37859. * This function does nothing. It may be overwritten to set all the particles first values.
  37860. * The SPS doesn't call this function, you may have to call it by your own.
  37861. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37862. */
  37863. SolidParticleSystem.prototype.initParticles = function () {
  37864. };
  37865. /**
  37866. * This function does nothing. It may be overwritten to recycle a particle.
  37867. * The SPS doesn't call this function, you may have to call it by your own.
  37868. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37869. */
  37870. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37871. return particle;
  37872. };
  37873. /**
  37874. * Updates a particle : this function should be overwritten by the user.
  37875. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37876. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37877. * ex : just set a particle position or velocity and recycle conditions
  37878. */
  37879. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37880. return particle;
  37881. };
  37882. /**
  37883. * Updates a vertex of a particle : it can be overwritten by the user.
  37884. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37885. * @param particle the current particle
  37886. * @param vertex the current index of the current particle
  37887. * @param pt the index of the current vertex in the particle shape
  37888. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37889. * ex : just set a vertex particle position
  37890. */
  37891. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37892. return vertex;
  37893. };
  37894. /**
  37895. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37896. * This does nothing and may be overwritten by the user.
  37897. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37898. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37899. * @param update the boolean update value actually passed to setParticles()
  37900. */
  37901. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37902. };
  37903. /**
  37904. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37905. * This will be passed three parameters.
  37906. * This does nothing and may be overwritten by the user.
  37907. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37908. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37909. * @param update the boolean update value actually passed to setParticles()
  37910. */
  37911. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37912. };
  37913. return SolidParticleSystem;
  37914. })();
  37915. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37916. })(BABYLON || (BABYLON = {}));
  37917. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nuniform vec2 depthValues;\r\n\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  37918. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,y=0,c=0,p=0,l=0,x=0,z=0,w=-1,v=0,g=M.Vector3[0],d=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,g),g.normalize(),i.Dot(h,g)<0&&(w=1),d=i.Dot(e,T),d=Math.min(1,Math.max(-1,d)),c=Math.acos(d)*w,i.Dot(T,a)<0&&(c=Math.PI+c,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,g),g.normalize(),i.Dot(T,g)<0&&(w=1),d=i.Dot(h,R),d=Math.min(1,Math.max(-1,d)),y=Math.acos(d)*w,i.Dot(_,u)<0&&(y=Math.PI+y,v++),w=-1,i.CrossToRef(a,T,g),g.normalize(),i.Dot(g,u)<0&&(w=1),d=i.Dot(T,a),d=Math.min(1,Math.max(-1,d)),m=-Math.acos(d)*w,0>d&&2>v&&(m=Math.PI+m),s.x=y,s.y=m,s.z=c},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,Z=s*x-a*p,I=s*l-h*p,E=s*f-e*p,L=h*c-a*y,q=e*c-a*m,S=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*Z+o*I)*b,t.m[10]=(i*P-n*Z+o*E)*b,t.m[14]=-(i*C-n*I+r*E)*b,t.m[3]=-(n*L-r*q+o*S)*b,t.m[7]=(i*L-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*S-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],Z=t.m[12],I=t.m[13],E=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*g+o*_+s*A+e*I,i[n+2]=r*d+o*M+s*P+e*E,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*g+a*_+u*A+m*I,i[n+6]=h*d+a*M+u*P+m*E,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*g+c*_+p*A+f*I,i[n+10]=y*d+c*M+p*P+f*E,i[n+11]=y*T+c*F+p*C+f*L,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*g+x*_+z*A+w*I,i[n+14]=l*d+x*M+z*P+w*E,i[n+15]=l*T+x*F+z*C+w*L,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0;\n\n},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=a?h/n:h,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=a?h:h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  37919. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37920. module.exports = BABYLON;
  37921. };