babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811
  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 () {
  1306. var result = Vector3.Zero();
  1307. this.toEulerAnglesToRef(result);
  1308. return result;
  1309. };
  1310. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1311. //result is an EulerAngles in the in the z-x-z convention
  1312. var qx = this.x;
  1313. var qy = this.y;
  1314. var qz = this.z;
  1315. var qw = this.w;
  1316. var qxy = qx * qy;
  1317. var qxz = qx * qz;
  1318. var qwy = qw * qy;
  1319. var qwz = qw * qz;
  1320. var qwx = qw * qx;
  1321. var qyz = qy * qz;
  1322. var sqx = qx * qx;
  1323. var sqy = qy * qy;
  1324. var determinant = sqx + sqy;
  1325. if (determinant !== 0.000 && determinant !== 1.000) {
  1326. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1327. result.y = Math.acos(1 - 2 * determinant);
  1328. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1329. }
  1330. else {
  1331. if (determinant === 0.0) {
  1332. result.x = 0.0;
  1333. result.y = 0.0;
  1334. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1335. }
  1336. else {
  1337. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1338. result.y = Math.PI;
  1339. result.z = 0.0;
  1340. }
  1341. }
  1342. return this;
  1343. };
  1344. Quaternion.prototype.toRotationMatrix = function (result) {
  1345. var xx = this.x * this.x;
  1346. var yy = this.y * this.y;
  1347. var zz = this.z * this.z;
  1348. var xy = this.x * this.y;
  1349. var zw = this.z * this.w;
  1350. var zx = this.z * this.x;
  1351. var yw = this.y * this.w;
  1352. var yz = this.y * this.z;
  1353. var xw = this.x * this.w;
  1354. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1355. result.m[1] = 2.0 * (xy + zw);
  1356. result.m[2] = 2.0 * (zx - yw);
  1357. result.m[3] = 0;
  1358. result.m[4] = 2.0 * (xy - zw);
  1359. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1360. result.m[6] = 2.0 * (yz + xw);
  1361. result.m[7] = 0;
  1362. result.m[8] = 2.0 * (zx + yw);
  1363. result.m[9] = 2.0 * (yz - xw);
  1364. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1365. result.m[11] = 0;
  1366. result.m[12] = 0;
  1367. result.m[13] = 0;
  1368. result.m[14] = 0;
  1369. result.m[15] = 1.0;
  1370. return this;
  1371. };
  1372. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1373. Quaternion.FromRotationMatrixToRef(matrix, this);
  1374. return this;
  1375. };
  1376. // Statics
  1377. Quaternion.FromRotationMatrix = function (matrix) {
  1378. var result = new Quaternion();
  1379. Quaternion.FromRotationMatrixToRef(matrix, result);
  1380. return result;
  1381. };
  1382. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1383. var data = matrix.m;
  1384. var m11 = data[0], m12 = data[4], m13 = data[8];
  1385. var m21 = data[1], m22 = data[5], m23 = data[9];
  1386. var m31 = data[2], m32 = data[6], m33 = data[10];
  1387. var trace = m11 + m22 + m33;
  1388. var s;
  1389. if (trace > 0) {
  1390. s = 0.5 / Math.sqrt(trace + 1.0);
  1391. result.w = 0.25 / s;
  1392. result.x = (m32 - m23) * s;
  1393. result.y = (m13 - m31) * s;
  1394. result.z = (m21 - m12) * s;
  1395. }
  1396. else if (m11 > m22 && m11 > m33) {
  1397. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1398. result.w = (m32 - m23) / s;
  1399. result.x = 0.25 * s;
  1400. result.y = (m12 + m21) / s;
  1401. result.z = (m13 + m31) / s;
  1402. }
  1403. else if (m22 > m33) {
  1404. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1405. result.w = (m13 - m31) / s;
  1406. result.x = (m12 + m21) / s;
  1407. result.y = 0.25 * s;
  1408. result.z = (m23 + m32) / s;
  1409. }
  1410. else {
  1411. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1412. result.w = (m21 - m12) / s;
  1413. result.x = (m13 + m31) / s;
  1414. result.y = (m23 + m32) / s;
  1415. result.z = 0.25 * s;
  1416. }
  1417. };
  1418. Quaternion.Inverse = function (q) {
  1419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1420. };
  1421. Quaternion.Identity = function () {
  1422. return new Quaternion(0, 0, 0, 1);
  1423. };
  1424. Quaternion.RotationAxis = function (axis, angle) {
  1425. var result = new Quaternion();
  1426. var sin = Math.sin(angle / 2);
  1427. axis.normalize();
  1428. result.w = Math.cos(angle / 2);
  1429. result.x = axis.x * sin;
  1430. result.y = axis.y * sin;
  1431. result.z = axis.z * sin;
  1432. return result;
  1433. };
  1434. Quaternion.FromArray = function (array, offset) {
  1435. if (!offset) {
  1436. offset = 0;
  1437. }
  1438. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1439. };
  1440. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1441. var result = new Quaternion();
  1442. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1443. return result;
  1444. };
  1445. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1446. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1447. var halfRoll = roll * 0.5;
  1448. var halfPitch = pitch * 0.5;
  1449. var halfYaw = yaw * 0.5;
  1450. var sinRoll = Math.sin(halfRoll);
  1451. var cosRoll = Math.cos(halfRoll);
  1452. var sinPitch = Math.sin(halfPitch);
  1453. var cosPitch = Math.cos(halfPitch);
  1454. var sinYaw = Math.sin(halfYaw);
  1455. var cosYaw = Math.cos(halfYaw);
  1456. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1457. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1458. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1459. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1460. };
  1461. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1462. var result = new Quaternion();
  1463. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1464. return result;
  1465. };
  1466. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1467. // Produces a quaternion from Euler angles in the z-x-z orientation
  1468. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1469. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1470. var halfBeta = beta * 0.5;
  1471. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1472. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1473. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1474. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1475. };
  1476. Quaternion.Slerp = function (left, right, amount) {
  1477. var num2;
  1478. var num3;
  1479. var num = amount;
  1480. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1481. var flag = false;
  1482. if (num4 < 0) {
  1483. flag = true;
  1484. num4 = -num4;
  1485. }
  1486. if (num4 > 0.999999) {
  1487. num3 = 1 - num;
  1488. num2 = flag ? -num : num;
  1489. }
  1490. else {
  1491. var num5 = Math.acos(num4);
  1492. var num6 = (1.0 / Math.sin(num5));
  1493. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1494. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1495. }
  1496. 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));
  1497. };
  1498. return Quaternion;
  1499. })();
  1500. BABYLON.Quaternion = Quaternion;
  1501. var Matrix = (function () {
  1502. function Matrix() {
  1503. this.m = new Float32Array(16);
  1504. }
  1505. // Properties
  1506. Matrix.prototype.isIdentity = function () {
  1507. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1508. return false;
  1509. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1510. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1511. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1512. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1513. return false;
  1514. return true;
  1515. };
  1516. Matrix.prototype.determinant = function () {
  1517. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1518. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1519. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1520. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1521. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1522. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1523. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1524. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1525. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1526. };
  1527. // Methods
  1528. Matrix.prototype.toArray = function () {
  1529. return this.m;
  1530. };
  1531. Matrix.prototype.asArray = function () {
  1532. return this.toArray();
  1533. };
  1534. Matrix.prototype.invert = function () {
  1535. this.invertToRef(this);
  1536. return this;
  1537. };
  1538. Matrix.prototype.reset = function () {
  1539. for (var index = 0; index < 16; index++) {
  1540. this.m[index] = 0;
  1541. }
  1542. return this;
  1543. };
  1544. Matrix.prototype.add = function (other) {
  1545. var result = new Matrix();
  1546. this.addToRef(other, result);
  1547. return result;
  1548. };
  1549. Matrix.prototype.addToRef = function (other, result) {
  1550. for (var index = 0; index < 16; index++) {
  1551. result.m[index] = this.m[index] + other.m[index];
  1552. }
  1553. return this;
  1554. };
  1555. Matrix.prototype.addToSelf = function (other) {
  1556. for (var index = 0; index < 16; index++) {
  1557. this.m[index] += other.m[index];
  1558. }
  1559. return this;
  1560. };
  1561. Matrix.prototype.invertToRef = function (other) {
  1562. var l1 = this.m[0];
  1563. var l2 = this.m[1];
  1564. var l3 = this.m[2];
  1565. var l4 = this.m[3];
  1566. var l5 = this.m[4];
  1567. var l6 = this.m[5];
  1568. var l7 = this.m[6];
  1569. var l8 = this.m[7];
  1570. var l9 = this.m[8];
  1571. var l10 = this.m[9];
  1572. var l11 = this.m[10];
  1573. var l12 = this.m[11];
  1574. var l13 = this.m[12];
  1575. var l14 = this.m[13];
  1576. var l15 = this.m[14];
  1577. var l16 = this.m[15];
  1578. var l17 = (l11 * l16) - (l12 * l15);
  1579. var l18 = (l10 * l16) - (l12 * l14);
  1580. var l19 = (l10 * l15) - (l11 * l14);
  1581. var l20 = (l9 * l16) - (l12 * l13);
  1582. var l21 = (l9 * l15) - (l11 * l13);
  1583. var l22 = (l9 * l14) - (l10 * l13);
  1584. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1585. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1586. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1587. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1588. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1589. var l28 = (l7 * l16) - (l8 * l15);
  1590. var l29 = (l6 * l16) - (l8 * l14);
  1591. var l30 = (l6 * l15) - (l7 * l14);
  1592. var l31 = (l5 * l16) - (l8 * l13);
  1593. var l32 = (l5 * l15) - (l7 * l13);
  1594. var l33 = (l5 * l14) - (l6 * l13);
  1595. var l34 = (l7 * l12) - (l8 * l11);
  1596. var l35 = (l6 * l12) - (l8 * l10);
  1597. var l36 = (l6 * l11) - (l7 * l10);
  1598. var l37 = (l5 * l12) - (l8 * l9);
  1599. var l38 = (l5 * l11) - (l7 * l9);
  1600. var l39 = (l5 * l10) - (l6 * l9);
  1601. other.m[0] = l23 * l27;
  1602. other.m[4] = l24 * l27;
  1603. other.m[8] = l25 * l27;
  1604. other.m[12] = l26 * l27;
  1605. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1606. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1607. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1608. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1609. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1610. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1611. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1612. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1613. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1614. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1615. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1616. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1617. return this;
  1618. };
  1619. Matrix.prototype.setTranslation = function (vector3) {
  1620. this.m[12] = vector3.x;
  1621. this.m[13] = vector3.y;
  1622. this.m[14] = vector3.z;
  1623. return this;
  1624. };
  1625. Matrix.prototype.multiply = function (other) {
  1626. var result = new Matrix();
  1627. this.multiplyToRef(other, result);
  1628. return result;
  1629. };
  1630. Matrix.prototype.copyFrom = function (other) {
  1631. for (var index = 0; index < 16; index++) {
  1632. this.m[index] = other.m[index];
  1633. }
  1634. return this;
  1635. };
  1636. Matrix.prototype.copyToArray = function (array, offset) {
  1637. if (offset === void 0) { offset = 0; }
  1638. for (var index = 0; index < 16; index++) {
  1639. array[offset + index] = this.m[index];
  1640. }
  1641. return this;
  1642. };
  1643. Matrix.prototype.multiplyToRef = function (other, result) {
  1644. this.multiplyToArray(other, result.m, 0);
  1645. return this;
  1646. };
  1647. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1648. var tm0 = this.m[0];
  1649. var tm1 = this.m[1];
  1650. var tm2 = this.m[2];
  1651. var tm3 = this.m[3];
  1652. var tm4 = this.m[4];
  1653. var tm5 = this.m[5];
  1654. var tm6 = this.m[6];
  1655. var tm7 = this.m[7];
  1656. var tm8 = this.m[8];
  1657. var tm9 = this.m[9];
  1658. var tm10 = this.m[10];
  1659. var tm11 = this.m[11];
  1660. var tm12 = this.m[12];
  1661. var tm13 = this.m[13];
  1662. var tm14 = this.m[14];
  1663. var tm15 = this.m[15];
  1664. var om0 = other.m[0];
  1665. var om1 = other.m[1];
  1666. var om2 = other.m[2];
  1667. var om3 = other.m[3];
  1668. var om4 = other.m[4];
  1669. var om5 = other.m[5];
  1670. var om6 = other.m[6];
  1671. var om7 = other.m[7];
  1672. var om8 = other.m[8];
  1673. var om9 = other.m[9];
  1674. var om10 = other.m[10];
  1675. var om11 = other.m[11];
  1676. var om12 = other.m[12];
  1677. var om13 = other.m[13];
  1678. var om14 = other.m[14];
  1679. var om15 = other.m[15];
  1680. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1681. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1682. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1683. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1684. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1685. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1686. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1687. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1688. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1689. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1690. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1691. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1692. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1693. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1694. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1695. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1696. return this;
  1697. };
  1698. Matrix.prototype.equals = function (value) {
  1699. return value &&
  1700. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1701. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1702. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1703. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1704. };
  1705. Matrix.prototype.clone = function () {
  1706. 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]);
  1707. };
  1708. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1709. translation.x = this.m[12];
  1710. translation.y = this.m[13];
  1711. translation.z = this.m[14];
  1712. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1713. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1714. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1715. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1716. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1717. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1718. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1719. rotation.x = 0;
  1720. rotation.y = 0;
  1721. rotation.z = 0;
  1722. rotation.w = 1;
  1723. return false;
  1724. }
  1725. 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);
  1726. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1727. return true;
  1728. };
  1729. // Statics
  1730. Matrix.FromArray = function (array, offset) {
  1731. var result = new Matrix();
  1732. if (!offset) {
  1733. offset = 0;
  1734. }
  1735. Matrix.FromArrayToRef(array, offset, result);
  1736. return result;
  1737. };
  1738. Matrix.FromArrayToRef = function (array, offset, result) {
  1739. for (var index = 0; index < 16; index++) {
  1740. result.m[index] = array[index + offset];
  1741. }
  1742. };
  1743. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1744. for (var index = 0; index < 16; index++) {
  1745. result.m[index] = array[index + offset] * scale;
  1746. }
  1747. };
  1748. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1749. result.m[0] = initialM11;
  1750. result.m[1] = initialM12;
  1751. result.m[2] = initialM13;
  1752. result.m[3] = initialM14;
  1753. result.m[4] = initialM21;
  1754. result.m[5] = initialM22;
  1755. result.m[6] = initialM23;
  1756. result.m[7] = initialM24;
  1757. result.m[8] = initialM31;
  1758. result.m[9] = initialM32;
  1759. result.m[10] = initialM33;
  1760. result.m[11] = initialM34;
  1761. result.m[12] = initialM41;
  1762. result.m[13] = initialM42;
  1763. result.m[14] = initialM43;
  1764. result.m[15] = initialM44;
  1765. };
  1766. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1767. var result = new Matrix();
  1768. result.m[0] = initialM11;
  1769. result.m[1] = initialM12;
  1770. result.m[2] = initialM13;
  1771. result.m[3] = initialM14;
  1772. result.m[4] = initialM21;
  1773. result.m[5] = initialM22;
  1774. result.m[6] = initialM23;
  1775. result.m[7] = initialM24;
  1776. result.m[8] = initialM31;
  1777. result.m[9] = initialM32;
  1778. result.m[10] = initialM33;
  1779. result.m[11] = initialM34;
  1780. result.m[12] = initialM41;
  1781. result.m[13] = initialM42;
  1782. result.m[14] = initialM43;
  1783. result.m[15] = initialM44;
  1784. return result;
  1785. };
  1786. Matrix.Compose = function (scale, rotation, translation) {
  1787. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1788. var rotationMatrix = Matrix.Identity();
  1789. rotation.toRotationMatrix(rotationMatrix);
  1790. result = result.multiply(rotationMatrix);
  1791. result.setTranslation(translation);
  1792. return result;
  1793. };
  1794. Matrix.Identity = function () {
  1795. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1796. };
  1797. Matrix.IdentityToRef = function (result) {
  1798. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1799. };
  1800. Matrix.Zero = function () {
  1801. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1802. };
  1803. Matrix.RotationX = function (angle) {
  1804. var result = new Matrix();
  1805. Matrix.RotationXToRef(angle, result);
  1806. return result;
  1807. };
  1808. Matrix.Invert = function (source) {
  1809. var result = new Matrix();
  1810. source.invertToRef(result);
  1811. return result;
  1812. };
  1813. Matrix.RotationXToRef = function (angle, result) {
  1814. var s = Math.sin(angle);
  1815. var c = Math.cos(angle);
  1816. result.m[0] = 1.0;
  1817. result.m[15] = 1.0;
  1818. result.m[5] = c;
  1819. result.m[10] = c;
  1820. result.m[9] = -s;
  1821. result.m[6] = s;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[7] = 0;
  1827. result.m[8] = 0;
  1828. result.m[11] = 0;
  1829. result.m[12] = 0;
  1830. result.m[13] = 0;
  1831. result.m[14] = 0;
  1832. };
  1833. Matrix.RotationY = function (angle) {
  1834. var result = new Matrix();
  1835. Matrix.RotationYToRef(angle, result);
  1836. return result;
  1837. };
  1838. Matrix.RotationYToRef = function (angle, result) {
  1839. var s = Math.sin(angle);
  1840. var c = Math.cos(angle);
  1841. result.m[5] = 1.0;
  1842. result.m[15] = 1.0;
  1843. result.m[0] = c;
  1844. result.m[2] = -s;
  1845. result.m[8] = s;
  1846. result.m[10] = c;
  1847. result.m[1] = 0;
  1848. result.m[3] = 0;
  1849. result.m[4] = 0;
  1850. result.m[6] = 0;
  1851. result.m[7] = 0;
  1852. result.m[9] = 0;
  1853. result.m[11] = 0;
  1854. result.m[12] = 0;
  1855. result.m[13] = 0;
  1856. result.m[14] = 0;
  1857. };
  1858. Matrix.RotationZ = function (angle) {
  1859. var result = new Matrix();
  1860. Matrix.RotationZToRef(angle, result);
  1861. return result;
  1862. };
  1863. Matrix.RotationZToRef = function (angle, result) {
  1864. var s = Math.sin(angle);
  1865. var c = Math.cos(angle);
  1866. result.m[10] = 1.0;
  1867. result.m[15] = 1.0;
  1868. result.m[0] = c;
  1869. result.m[1] = s;
  1870. result.m[4] = -s;
  1871. result.m[5] = c;
  1872. result.m[2] = 0;
  1873. result.m[3] = 0;
  1874. result.m[6] = 0;
  1875. result.m[7] = 0;
  1876. result.m[8] = 0;
  1877. result.m[9] = 0;
  1878. result.m[11] = 0;
  1879. result.m[12] = 0;
  1880. result.m[13] = 0;
  1881. result.m[14] = 0;
  1882. };
  1883. Matrix.RotationAxis = function (axis, angle) {
  1884. var result = Matrix.Zero();
  1885. Matrix.RotationAxisToRef(axis, angle, result);
  1886. return result;
  1887. };
  1888. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1889. var s = Math.sin(-angle);
  1890. var c = Math.cos(-angle);
  1891. var c1 = 1 - c;
  1892. axis.normalize();
  1893. result.m[0] = (axis.x * axis.x) * c1 + c;
  1894. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1895. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1896. result.m[3] = 0.0;
  1897. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1898. result.m[5] = (axis.y * axis.y) * c1 + c;
  1899. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1900. result.m[7] = 0.0;
  1901. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1902. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1903. result.m[10] = (axis.z * axis.z) * c1 + c;
  1904. result.m[11] = 0.0;
  1905. result.m[15] = 1.0;
  1906. };
  1907. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1908. var result = new Matrix();
  1909. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1910. return result;
  1911. };
  1912. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1913. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1914. this._tempQuaternion.toRotationMatrix(result);
  1915. };
  1916. Matrix.Scaling = function (x, y, z) {
  1917. var result = Matrix.Zero();
  1918. Matrix.ScalingToRef(x, y, z, result);
  1919. return result;
  1920. };
  1921. Matrix.ScalingToRef = function (x, y, z, result) {
  1922. result.m[0] = x;
  1923. result.m[1] = 0;
  1924. result.m[2] = 0;
  1925. result.m[3] = 0;
  1926. result.m[4] = 0;
  1927. result.m[5] = y;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[10] = z;
  1933. result.m[11] = 0;
  1934. result.m[12] = 0;
  1935. result.m[13] = 0;
  1936. result.m[14] = 0;
  1937. result.m[15] = 1.0;
  1938. };
  1939. Matrix.Translation = function (x, y, z) {
  1940. var result = Matrix.Identity();
  1941. Matrix.TranslationToRef(x, y, z, result);
  1942. return result;
  1943. };
  1944. Matrix.TranslationToRef = function (x, y, z, result) {
  1945. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1946. };
  1947. Matrix.Lerp = function (startValue, endValue, gradient) {
  1948. var startScale = new Vector3(0, 0, 0);
  1949. var startRotation = new Quaternion();
  1950. var startTranslation = new Vector3(0, 0, 0);
  1951. startValue.decompose(startScale, startRotation, startTranslation);
  1952. var endScale = new Vector3(0, 0, 0);
  1953. var endRotation = new Quaternion();
  1954. var endTranslation = new Vector3(0, 0, 0);
  1955. endValue.decompose(endScale, endRotation, endTranslation);
  1956. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1957. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1958. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1959. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1960. };
  1961. Matrix.LookAtLH = function (eye, target, up) {
  1962. var result = Matrix.Zero();
  1963. Matrix.LookAtLHToRef(eye, target, up, result);
  1964. return result;
  1965. };
  1966. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1967. // Z axis
  1968. target.subtractToRef(eye, this._zAxis);
  1969. this._zAxis.normalize();
  1970. // X axis
  1971. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1972. if (this._xAxis.lengthSquared() === 0) {
  1973. this._xAxis.x = 1.0;
  1974. }
  1975. else {
  1976. this._xAxis.normalize();
  1977. }
  1978. // Y axis
  1979. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1980. this._yAxis.normalize();
  1981. // Eye angles
  1982. var ex = -Vector3.Dot(this._xAxis, eye);
  1983. var ey = -Vector3.Dot(this._yAxis, eye);
  1984. var ez = -Vector3.Dot(this._zAxis, eye);
  1985. 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);
  1986. };
  1987. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1988. var matrix = Matrix.Zero();
  1989. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1990. return matrix;
  1991. };
  1992. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1993. var hw = 2.0 / width;
  1994. var hh = 2.0 / height;
  1995. var id = 1.0 / (zfar - znear);
  1996. var nid = znear / (znear - zfar);
  1997. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1998. };
  1999. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2000. var matrix = Matrix.Zero();
  2001. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2002. return matrix;
  2003. };
  2004. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2005. result.m[0] = 2.0 / (right - left);
  2006. result.m[1] = result.m[2] = result.m[3] = 0;
  2007. result.m[5] = 2.0 / (top - bottom);
  2008. result.m[4] = result.m[6] = result.m[7] = 0;
  2009. result.m[10] = -1.0 / (znear - zfar);
  2010. result.m[8] = result.m[9] = result.m[11] = 0;
  2011. result.m[12] = (left + right) / (left - right);
  2012. result.m[13] = (top + bottom) / (bottom - top);
  2013. result.m[14] = znear / (znear - zfar);
  2014. result.m[15] = 1.0;
  2015. };
  2016. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2017. var matrix = Matrix.Zero();
  2018. matrix.m[0] = (2.0 * znear) / width;
  2019. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2020. matrix.m[5] = (2.0 * znear) / height;
  2021. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2022. matrix.m[10] = -zfar / (znear - zfar);
  2023. matrix.m[8] = matrix.m[9] = 0.0;
  2024. matrix.m[11] = 1.0;
  2025. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2026. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2027. return matrix;
  2028. };
  2029. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2030. var matrix = Matrix.Zero();
  2031. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2032. return matrix;
  2033. };
  2034. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2035. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2036. var tan = 1.0 / (Math.tan(fov * 0.5));
  2037. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2038. if (v_fixed) {
  2039. result.m[0] = tan / aspect;
  2040. }
  2041. else {
  2042. result.m[0] = tan;
  2043. }
  2044. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2045. if (v_fixed) {
  2046. result.m[5] = tan;
  2047. }
  2048. else {
  2049. result.m[5] = tan * aspect;
  2050. }
  2051. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2052. result.m[8] = result.m[9] = 0.0;
  2053. result.m[10] = -zfar / (znear - zfar);
  2054. result.m[11] = 1.0;
  2055. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2056. result.m[14] = (znear * zfar) / (znear - zfar);
  2057. };
  2058. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2059. var cw = viewport.width;
  2060. var ch = viewport.height;
  2061. var cx = viewport.x;
  2062. var cy = viewport.y;
  2063. 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);
  2064. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2065. };
  2066. Matrix.GetAsMatrix2x2 = function (matrix) {
  2067. return new Float32Array([
  2068. matrix.m[0], matrix.m[1],
  2069. matrix.m[4], matrix.m[5]
  2070. ]);
  2071. };
  2072. Matrix.GetAsMatrix3x3 = function (matrix) {
  2073. return new Float32Array([
  2074. matrix.m[0], matrix.m[1], matrix.m[2],
  2075. matrix.m[4], matrix.m[5], matrix.m[6],
  2076. matrix.m[8], matrix.m[9], matrix.m[10]
  2077. ]);
  2078. };
  2079. Matrix.Transpose = function (matrix) {
  2080. var result = new Matrix();
  2081. result.m[0] = matrix.m[0];
  2082. result.m[1] = matrix.m[4];
  2083. result.m[2] = matrix.m[8];
  2084. result.m[3] = matrix.m[12];
  2085. result.m[4] = matrix.m[1];
  2086. result.m[5] = matrix.m[5];
  2087. result.m[6] = matrix.m[9];
  2088. result.m[7] = matrix.m[13];
  2089. result.m[8] = matrix.m[2];
  2090. result.m[9] = matrix.m[6];
  2091. result.m[10] = matrix.m[10];
  2092. result.m[11] = matrix.m[14];
  2093. result.m[12] = matrix.m[3];
  2094. result.m[13] = matrix.m[7];
  2095. result.m[14] = matrix.m[11];
  2096. result.m[15] = matrix.m[15];
  2097. return result;
  2098. };
  2099. Matrix.Reflection = function (plane) {
  2100. var matrix = new Matrix();
  2101. Matrix.ReflectionToRef(plane, matrix);
  2102. return matrix;
  2103. };
  2104. Matrix.ReflectionToRef = function (plane, result) {
  2105. plane.normalize();
  2106. var x = plane.normal.x;
  2107. var y = plane.normal.y;
  2108. var z = plane.normal.z;
  2109. var temp = -2 * x;
  2110. var temp2 = -2 * y;
  2111. var temp3 = -2 * z;
  2112. result.m[0] = (temp * x) + 1;
  2113. result.m[1] = temp2 * x;
  2114. result.m[2] = temp3 * x;
  2115. result.m[3] = 0.0;
  2116. result.m[4] = temp * y;
  2117. result.m[5] = (temp2 * y) + 1;
  2118. result.m[6] = temp3 * y;
  2119. result.m[7] = 0.0;
  2120. result.m[8] = temp * z;
  2121. result.m[9] = temp2 * z;
  2122. result.m[10] = (temp3 * z) + 1;
  2123. result.m[11] = 0.0;
  2124. result.m[12] = temp * plane.d;
  2125. result.m[13] = temp2 * plane.d;
  2126. result.m[14] = temp3 * plane.d;
  2127. result.m[15] = 1.0;
  2128. };
  2129. Matrix._tempQuaternion = new Quaternion();
  2130. Matrix._xAxis = Vector3.Zero();
  2131. Matrix._yAxis = Vector3.Zero();
  2132. Matrix._zAxis = Vector3.Zero();
  2133. return Matrix;
  2134. })();
  2135. BABYLON.Matrix = Matrix;
  2136. var Plane = (function () {
  2137. function Plane(a, b, c, d) {
  2138. this.normal = new Vector3(a, b, c);
  2139. this.d = d;
  2140. }
  2141. Plane.prototype.asArray = function () {
  2142. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2143. };
  2144. // Methods
  2145. Plane.prototype.clone = function () {
  2146. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2147. };
  2148. Plane.prototype.normalize = function () {
  2149. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2150. var magnitude = 0;
  2151. if (norm !== 0) {
  2152. magnitude = 1.0 / norm;
  2153. }
  2154. this.normal.x *= magnitude;
  2155. this.normal.y *= magnitude;
  2156. this.normal.z *= magnitude;
  2157. this.d *= magnitude;
  2158. return this;
  2159. };
  2160. Plane.prototype.transform = function (transformation) {
  2161. var transposedMatrix = Matrix.Transpose(transformation);
  2162. var x = this.normal.x;
  2163. var y = this.normal.y;
  2164. var z = this.normal.z;
  2165. var d = this.d;
  2166. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2167. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2168. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2169. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2170. return new Plane(normalX, normalY, normalZ, finalD);
  2171. };
  2172. Plane.prototype.dotCoordinate = function (point) {
  2173. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2174. };
  2175. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2176. var x1 = point2.x - point1.x;
  2177. var y1 = point2.y - point1.y;
  2178. var z1 = point2.z - point1.z;
  2179. var x2 = point3.x - point1.x;
  2180. var y2 = point3.y - point1.y;
  2181. var z2 = point3.z - point1.z;
  2182. var yz = (y1 * z2) - (z1 * y2);
  2183. var xz = (z1 * x2) - (x1 * z2);
  2184. var xy = (x1 * y2) - (y1 * x2);
  2185. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2186. var invPyth;
  2187. if (pyth !== 0) {
  2188. invPyth = 1.0 / pyth;
  2189. }
  2190. else {
  2191. invPyth = 0;
  2192. }
  2193. this.normal.x = yz * invPyth;
  2194. this.normal.y = xz * invPyth;
  2195. this.normal.z = xy * invPyth;
  2196. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2197. return this;
  2198. };
  2199. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2200. var dot = Vector3.Dot(this.normal, direction);
  2201. return (dot <= epsilon);
  2202. };
  2203. Plane.prototype.signedDistanceTo = function (point) {
  2204. return Vector3.Dot(point, this.normal) + this.d;
  2205. };
  2206. // Statics
  2207. Plane.FromArray = function (array) {
  2208. return new Plane(array[0], array[1], array[2], array[3]);
  2209. };
  2210. Plane.FromPoints = function (point1, point2, point3) {
  2211. var result = new Plane(0, 0, 0, 0);
  2212. result.copyFromPoints(point1, point2, point3);
  2213. return result;
  2214. };
  2215. Plane.FromPositionAndNormal = function (origin, normal) {
  2216. var result = new Plane(0, 0, 0, 0);
  2217. normal.normalize();
  2218. result.normal = normal;
  2219. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2220. return result;
  2221. };
  2222. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2223. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2224. return Vector3.Dot(point, normal) + d;
  2225. };
  2226. return Plane;
  2227. })();
  2228. BABYLON.Plane = Plane;
  2229. var Viewport = (function () {
  2230. function Viewport(x, y, width, height) {
  2231. this.x = x;
  2232. this.y = y;
  2233. this.width = width;
  2234. this.height = height;
  2235. }
  2236. Viewport.prototype.toGlobal = function (engine) {
  2237. var width = engine.getRenderWidth();
  2238. var height = engine.getRenderHeight();
  2239. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2240. };
  2241. Viewport.prototype.toScreenGlobal = function (engine) {
  2242. var width = engine.getRenderWidth(true);
  2243. var height = engine.getRenderHeight(true);
  2244. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2245. };
  2246. return Viewport;
  2247. })();
  2248. BABYLON.Viewport = Viewport;
  2249. var Frustum = (function () {
  2250. function Frustum() {
  2251. }
  2252. Frustum.GetPlanes = function (transform) {
  2253. var frustumPlanes = [];
  2254. for (var index = 0; index < 6; index++) {
  2255. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2256. }
  2257. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2258. return frustumPlanes;
  2259. };
  2260. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2261. // Near
  2262. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2263. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2264. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2265. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2266. frustumPlanes[0].normalize();
  2267. // Far
  2268. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2269. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2270. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2271. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2272. frustumPlanes[1].normalize();
  2273. // Left
  2274. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2275. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2276. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2277. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2278. frustumPlanes[2].normalize();
  2279. // Right
  2280. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2281. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2282. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2283. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2284. frustumPlanes[3].normalize();
  2285. // Top
  2286. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2287. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2288. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2289. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2290. frustumPlanes[4].normalize();
  2291. // Bottom
  2292. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2293. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2294. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2295. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2296. frustumPlanes[5].normalize();
  2297. };
  2298. return Frustum;
  2299. })();
  2300. BABYLON.Frustum = Frustum;
  2301. var Ray = (function () {
  2302. function Ray(origin, direction, length) {
  2303. if (length === void 0) { length = Number.MAX_VALUE; }
  2304. this.origin = origin;
  2305. this.direction = direction;
  2306. this.length = length;
  2307. }
  2308. // Methods
  2309. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2310. var d = 0.0;
  2311. var maxValue = Number.MAX_VALUE;
  2312. var inv;
  2313. var min;
  2314. var max;
  2315. var temp;
  2316. if (Math.abs(this.direction.x) < 0.0000001) {
  2317. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2318. return false;
  2319. }
  2320. }
  2321. else {
  2322. inv = 1.0 / this.direction.x;
  2323. min = (minimum.x - this.origin.x) * inv;
  2324. max = (maximum.x - this.origin.x) * inv;
  2325. if (max === -Infinity) {
  2326. max = Infinity;
  2327. }
  2328. if (min > max) {
  2329. temp = min;
  2330. min = max;
  2331. max = temp;
  2332. }
  2333. d = Math.max(min, d);
  2334. maxValue = Math.min(max, maxValue);
  2335. if (d > maxValue) {
  2336. return false;
  2337. }
  2338. }
  2339. if (Math.abs(this.direction.y) < 0.0000001) {
  2340. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2341. return false;
  2342. }
  2343. }
  2344. else {
  2345. inv = 1.0 / this.direction.y;
  2346. min = (minimum.y - this.origin.y) * inv;
  2347. max = (maximum.y - this.origin.y) * inv;
  2348. if (max === -Infinity) {
  2349. max = Infinity;
  2350. }
  2351. if (min > max) {
  2352. temp = min;
  2353. min = max;
  2354. max = temp;
  2355. }
  2356. d = Math.max(min, d);
  2357. maxValue = Math.min(max, maxValue);
  2358. if (d > maxValue) {
  2359. return false;
  2360. }
  2361. }
  2362. if (Math.abs(this.direction.z) < 0.0000001) {
  2363. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2364. return false;
  2365. }
  2366. }
  2367. else {
  2368. inv = 1.0 / this.direction.z;
  2369. min = (minimum.z - this.origin.z) * inv;
  2370. max = (maximum.z - this.origin.z) * inv;
  2371. if (max === -Infinity) {
  2372. max = Infinity;
  2373. }
  2374. if (min > max) {
  2375. temp = min;
  2376. min = max;
  2377. max = temp;
  2378. }
  2379. d = Math.max(min, d);
  2380. maxValue = Math.min(max, maxValue);
  2381. if (d > maxValue) {
  2382. return false;
  2383. }
  2384. }
  2385. return true;
  2386. };
  2387. Ray.prototype.intersectsBox = function (box) {
  2388. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2389. };
  2390. Ray.prototype.intersectsSphere = function (sphere) {
  2391. var x = sphere.center.x - this.origin.x;
  2392. var y = sphere.center.y - this.origin.y;
  2393. var z = sphere.center.z - this.origin.z;
  2394. var pyth = (x * x) + (y * y) + (z * z);
  2395. var rr = sphere.radius * sphere.radius;
  2396. if (pyth <= rr) {
  2397. return true;
  2398. }
  2399. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2400. if (dot < 0.0) {
  2401. return false;
  2402. }
  2403. var temp = pyth - (dot * dot);
  2404. return temp <= rr;
  2405. };
  2406. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2407. if (!this._edge1) {
  2408. this._edge1 = Vector3.Zero();
  2409. this._edge2 = Vector3.Zero();
  2410. this._pvec = Vector3.Zero();
  2411. this._tvec = Vector3.Zero();
  2412. this._qvec = Vector3.Zero();
  2413. }
  2414. vertex1.subtractToRef(vertex0, this._edge1);
  2415. vertex2.subtractToRef(vertex0, this._edge2);
  2416. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2417. var det = Vector3.Dot(this._edge1, this._pvec);
  2418. if (det === 0) {
  2419. return null;
  2420. }
  2421. var invdet = 1 / det;
  2422. this.origin.subtractToRef(vertex0, this._tvec);
  2423. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2424. if (bu < 0 || bu > 1.0) {
  2425. return null;
  2426. }
  2427. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2428. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2429. if (bv < 0 || bu + bv > 1.0) {
  2430. return null;
  2431. }
  2432. //check if the distance is longer than the predefined length.
  2433. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2434. if (distance > this.length) {
  2435. return null;
  2436. }
  2437. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2438. };
  2439. // Statics
  2440. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2441. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2442. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2443. var direction = end.subtract(start);
  2444. direction.normalize();
  2445. return new Ray(start, direction);
  2446. };
  2447. /**
  2448. * 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
  2449. * transformed to the given world matrix.
  2450. * @param origin The origin point
  2451. * @param end The end point
  2452. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2453. */
  2454. Ray.CreateNewFromTo = function (origin, end, world) {
  2455. if (world === void 0) { world = Matrix.Identity(); }
  2456. var direction = end.subtract(origin);
  2457. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2458. direction.normalize();
  2459. return Ray.Transform(new Ray(origin, direction, length), world);
  2460. };
  2461. Ray.Transform = function (ray, matrix) {
  2462. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2463. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2464. return new Ray(newOrigin, newDirection, ray.length);
  2465. };
  2466. return Ray;
  2467. })();
  2468. BABYLON.Ray = Ray;
  2469. (function (Space) {
  2470. Space[Space["LOCAL"] = 0] = "LOCAL";
  2471. Space[Space["WORLD"] = 1] = "WORLD";
  2472. })(BABYLON.Space || (BABYLON.Space = {}));
  2473. var Space = BABYLON.Space;
  2474. var Axis = (function () {
  2475. function Axis() {
  2476. }
  2477. Axis.X = new Vector3(1, 0, 0);
  2478. Axis.Y = new Vector3(0, 1, 0);
  2479. Axis.Z = new Vector3(0, 0, 1);
  2480. return Axis;
  2481. })();
  2482. BABYLON.Axis = Axis;
  2483. ;
  2484. var BezierCurve = (function () {
  2485. function BezierCurve() {
  2486. }
  2487. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2488. // Extract X (which is equal to time here)
  2489. var f0 = 1 - 3 * x2 + 3 * x1;
  2490. var f1 = 3 * x2 - 6 * x1;
  2491. var f2 = 3 * x1;
  2492. var refinedT = t;
  2493. for (var i = 0; i < 5; i++) {
  2494. var refinedT2 = refinedT * refinedT;
  2495. var refinedT3 = refinedT2 * refinedT;
  2496. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2497. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2498. refinedT -= (x - t) * slope;
  2499. refinedT = Math.min(1, Math.max(0, refinedT));
  2500. }
  2501. // Resolve cubic bezier for the given x
  2502. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2503. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2504. Math.pow(refinedT, 3);
  2505. };
  2506. return BezierCurve;
  2507. })();
  2508. BABYLON.BezierCurve = BezierCurve;
  2509. (function (Orientation) {
  2510. Orientation[Orientation["CW"] = 0] = "CW";
  2511. Orientation[Orientation["CCW"] = 1] = "CCW";
  2512. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2513. var Orientation = BABYLON.Orientation;
  2514. var Angle = (function () {
  2515. function Angle(radians) {
  2516. var _this = this;
  2517. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2518. this.radians = function () { return _this._radians; };
  2519. this._radians = radians;
  2520. if (this._radians < 0)
  2521. this._radians += (2 * Math.PI);
  2522. }
  2523. Angle.BetweenTwoPoints = function (a, b) {
  2524. var delta = b.subtract(a);
  2525. var theta = Math.atan2(delta.y, delta.x);
  2526. return new Angle(theta);
  2527. };
  2528. Angle.FromRadians = function (radians) {
  2529. return new Angle(radians);
  2530. };
  2531. Angle.FromDegrees = function (degrees) {
  2532. return new Angle(degrees * Math.PI / 180);
  2533. };
  2534. return Angle;
  2535. })();
  2536. BABYLON.Angle = Angle;
  2537. var Arc2 = (function () {
  2538. function Arc2(startPoint, midPoint, endPoint) {
  2539. this.startPoint = startPoint;
  2540. this.midPoint = midPoint;
  2541. this.endPoint = endPoint;
  2542. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2543. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2544. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2545. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2546. 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);
  2547. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2548. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2549. var a1 = this.startAngle.degrees();
  2550. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2551. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2552. // angles correction
  2553. if (a2 - a1 > +180.0)
  2554. a2 -= 360.0;
  2555. if (a2 - a1 < -180.0)
  2556. a2 += 360.0;
  2557. if (a3 - a2 > +180.0)
  2558. a3 -= 360.0;
  2559. if (a3 - a2 < -180.0)
  2560. a3 += 360.0;
  2561. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2562. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2563. }
  2564. return Arc2;
  2565. })();
  2566. BABYLON.Arc2 = Arc2;
  2567. var PathCursor = (function () {
  2568. function PathCursor(path) {
  2569. this.path = path;
  2570. this._onchange = new Array();
  2571. this.value = 0;
  2572. this.animations = new Array();
  2573. }
  2574. PathCursor.prototype.getPoint = function () {
  2575. var point = this.path.getPointAtLengthPosition(this.value);
  2576. return new Vector3(point.x, 0, point.y);
  2577. };
  2578. PathCursor.prototype.moveAhead = function (step) {
  2579. if (step === void 0) { step = 0.002; }
  2580. this.move(step);
  2581. return this;
  2582. };
  2583. PathCursor.prototype.moveBack = function (step) {
  2584. if (step === void 0) { step = 0.002; }
  2585. this.move(-step);
  2586. return this;
  2587. };
  2588. PathCursor.prototype.move = function (step) {
  2589. if (Math.abs(step) > 1) {
  2590. throw "step size should be less than 1.";
  2591. }
  2592. this.value += step;
  2593. this.ensureLimits();
  2594. this.raiseOnChange();
  2595. return this;
  2596. };
  2597. PathCursor.prototype.ensureLimits = function () {
  2598. while (this.value > 1) {
  2599. this.value -= 1;
  2600. }
  2601. while (this.value < 0) {
  2602. this.value += 1;
  2603. }
  2604. return this;
  2605. };
  2606. // used by animation engine
  2607. PathCursor.prototype.markAsDirty = function (propertyName) {
  2608. this.ensureLimits();
  2609. this.raiseOnChange();
  2610. return this;
  2611. };
  2612. PathCursor.prototype.raiseOnChange = function () {
  2613. var _this = this;
  2614. this._onchange.forEach(function (f) { return f(_this); });
  2615. return this;
  2616. };
  2617. PathCursor.prototype.onchange = function (f) {
  2618. this._onchange.push(f);
  2619. return this;
  2620. };
  2621. return PathCursor;
  2622. })();
  2623. BABYLON.PathCursor = PathCursor;
  2624. var Path2 = (function () {
  2625. function Path2(x, y) {
  2626. this._points = new Array();
  2627. this._length = 0;
  2628. this.closed = false;
  2629. this._points.push(new Vector2(x, y));
  2630. }
  2631. Path2.prototype.addLineTo = function (x, y) {
  2632. if (closed) {
  2633. BABYLON.Tools.Error("cannot add lines to closed paths");
  2634. return this;
  2635. }
  2636. var newPoint = new Vector2(x, y);
  2637. var previousPoint = this._points[this._points.length - 1];
  2638. this._points.push(newPoint);
  2639. this._length += newPoint.subtract(previousPoint).length();
  2640. return this;
  2641. };
  2642. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2643. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2644. if (closed) {
  2645. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2646. return this;
  2647. }
  2648. var startPoint = this._points[this._points.length - 1];
  2649. var midPoint = new Vector2(midX, midY);
  2650. var endPoint = new Vector2(endX, endY);
  2651. var arc = new Arc2(startPoint, midPoint, endPoint);
  2652. var increment = arc.angle.radians() / numberOfSegments;
  2653. if (arc.orientation === Orientation.CW)
  2654. increment *= -1;
  2655. var currentAngle = arc.startAngle.radians() + increment;
  2656. for (var i = 0; i < numberOfSegments; i++) {
  2657. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2658. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2659. this.addLineTo(x, y);
  2660. currentAngle += increment;
  2661. }
  2662. return this;
  2663. };
  2664. Path2.prototype.close = function () {
  2665. this.closed = true;
  2666. return this;
  2667. };
  2668. Path2.prototype.length = function () {
  2669. var result = this._length;
  2670. if (!this.closed) {
  2671. var lastPoint = this._points[this._points.length - 1];
  2672. var firstPoint = this._points[0];
  2673. result += (firstPoint.subtract(lastPoint).length());
  2674. }
  2675. return result;
  2676. };
  2677. Path2.prototype.getPoints = function () {
  2678. return this._points;
  2679. };
  2680. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2681. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2682. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2683. return Vector2.Zero();
  2684. }
  2685. var lengthPosition = normalizedLengthPosition * this.length();
  2686. var previousOffset = 0;
  2687. for (var i = 0; i < this._points.length; i++) {
  2688. var j = (i + 1) % this._points.length;
  2689. var a = this._points[i];
  2690. var b = this._points[j];
  2691. var bToA = b.subtract(a);
  2692. var nextOffset = (bToA.length() + previousOffset);
  2693. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2694. var dir = bToA.normalize();
  2695. var localOffset = lengthPosition - previousOffset;
  2696. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2697. }
  2698. previousOffset = nextOffset;
  2699. }
  2700. BABYLON.Tools.Error("internal error");
  2701. return Vector2.Zero();
  2702. };
  2703. Path2.StartingAt = function (x, y) {
  2704. return new Path2(x, y);
  2705. };
  2706. return Path2;
  2707. })();
  2708. BABYLON.Path2 = Path2;
  2709. var Path3D = (function () {
  2710. /**
  2711. * new Path3D(path, normal, raw)
  2712. * path : an array of Vector3, the curve axis of the Path3D
  2713. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2714. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2715. */
  2716. function Path3D(path, firstNormal, raw) {
  2717. this.path = path;
  2718. this._curve = new Array();
  2719. this._distances = new Array();
  2720. this._tangents = new Array();
  2721. this._normals = new Array();
  2722. this._binormals = new Array();
  2723. for (var p = 0; p < path.length; p++) {
  2724. this._curve[p] = path[p].clone(); // hard copy
  2725. }
  2726. this._raw = raw || false;
  2727. this._compute(firstNormal);
  2728. }
  2729. Path3D.prototype.getCurve = function () {
  2730. return this._curve;
  2731. };
  2732. Path3D.prototype.getTangents = function () {
  2733. return this._tangents;
  2734. };
  2735. Path3D.prototype.getNormals = function () {
  2736. return this._normals;
  2737. };
  2738. Path3D.prototype.getBinormals = function () {
  2739. return this._binormals;
  2740. };
  2741. Path3D.prototype.getDistances = function () {
  2742. return this._distances;
  2743. };
  2744. Path3D.prototype.update = function (path, firstNormal) {
  2745. for (var p = 0; p < path.length; p++) {
  2746. this._curve[p].x = path[p].x;
  2747. this._curve[p].y = path[p].y;
  2748. this._curve[p].z = path[p].z;
  2749. }
  2750. this._compute(firstNormal);
  2751. return this;
  2752. };
  2753. // private function compute() : computes tangents, normals and binormals
  2754. Path3D.prototype._compute = function (firstNormal) {
  2755. var l = this._curve.length;
  2756. // first and last tangents
  2757. this._tangents[0] = this._getFirstNonNullVector(0);
  2758. if (!this._raw) {
  2759. this._tangents[0].normalize();
  2760. }
  2761. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2762. if (!this._raw) {
  2763. this._tangents[l - 1].normalize();
  2764. }
  2765. // normals and binormals at first point : arbitrary vector with _normalVector()
  2766. var tg0 = this._tangents[0];
  2767. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2768. this._normals[0] = pp0;
  2769. if (!this._raw) {
  2770. this._normals[0].normalize();
  2771. }
  2772. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2773. if (!this._raw) {
  2774. this._binormals[0].normalize();
  2775. }
  2776. this._distances[0] = 0;
  2777. // normals and binormals : next points
  2778. var prev; // previous vector (segment)
  2779. var cur; // current vector (segment)
  2780. var curTang; // current tangent
  2781. // previous normal
  2782. var prevBinor; // previous binormal
  2783. for (var i = 1; i < l; i++) {
  2784. // tangents
  2785. prev = this._getLastNonNullVector(i);
  2786. if (i < l - 1) {
  2787. cur = this._getFirstNonNullVector(i);
  2788. this._tangents[i] = prev.add(cur);
  2789. this._tangents[i].normalize();
  2790. }
  2791. this._distances[i] = this._distances[i - 1] + prev.length();
  2792. // normals and binormals
  2793. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2794. curTang = this._tangents[i];
  2795. prevBinor = this._binormals[i - 1];
  2796. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2797. if (!this._raw) {
  2798. this._normals[i].normalize();
  2799. }
  2800. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2801. if (!this._raw) {
  2802. this._binormals[i].normalize();
  2803. }
  2804. }
  2805. };
  2806. // private function getFirstNonNullVector(index)
  2807. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2808. Path3D.prototype._getFirstNonNullVector = function (index) {
  2809. var i = 1;
  2810. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2811. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2812. i++;
  2813. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2814. }
  2815. return nNVector;
  2816. };
  2817. // private function getLastNonNullVector(index)
  2818. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2819. Path3D.prototype._getLastNonNullVector = function (index) {
  2820. var i = 1;
  2821. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2822. while (nLVector.length() === 0 && index > i + 1) {
  2823. i++;
  2824. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2825. }
  2826. return nLVector;
  2827. };
  2828. // private function normalVector(v0, vt, va) :
  2829. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2830. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2831. Path3D.prototype._normalVector = function (v0, vt, va) {
  2832. var normal0;
  2833. if (va === undefined || va === null) {
  2834. var point;
  2835. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2836. point = new Vector3(0, -1, 0);
  2837. }
  2838. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2839. point = new Vector3(1, 0, 0);
  2840. }
  2841. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2842. point = new Vector3(0, 0, 1);
  2843. }
  2844. normal0 = Vector3.Cross(vt, point);
  2845. }
  2846. else {
  2847. normal0 = Vector3.Cross(vt, va);
  2848. Vector3.CrossToRef(normal0, vt, normal0);
  2849. }
  2850. normal0.normalize();
  2851. return normal0;
  2852. };
  2853. return Path3D;
  2854. })();
  2855. BABYLON.Path3D = Path3D;
  2856. var Curve3 = (function () {
  2857. function Curve3(points) {
  2858. this._length = 0;
  2859. this._points = points;
  2860. this._length = this._computeLength(points);
  2861. }
  2862. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2863. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2864. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2865. var bez = new Array();
  2866. var equation = function (t, val0, val1, val2) {
  2867. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2868. return res;
  2869. };
  2870. for (var i = 0; i <= nbPoints; i++) {
  2871. 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)));
  2872. }
  2873. return new Curve3(bez);
  2874. };
  2875. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2876. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2877. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2878. var bez = new Array();
  2879. var equation = function (t, val0, val1, val2, val3) {
  2880. 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;
  2881. return res;
  2882. };
  2883. for (var i = 0; i <= nbPoints; i++) {
  2884. 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)));
  2885. }
  2886. return new Curve3(bez);
  2887. };
  2888. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2889. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2890. var hermite = new Array();
  2891. var step = 1 / nbPoints;
  2892. for (var i = 0; i <= nbPoints; i++) {
  2893. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2894. }
  2895. return new Curve3(hermite);
  2896. };
  2897. Curve3.prototype.getPoints = function () {
  2898. return this._points;
  2899. };
  2900. Curve3.prototype.length = function () {
  2901. return this._length;
  2902. };
  2903. Curve3.prototype.continue = function (curve) {
  2904. var lastPoint = this._points[this._points.length - 1];
  2905. var continuedPoints = this._points.slice();
  2906. var curvePoints = curve.getPoints();
  2907. for (var i = 1; i < curvePoints.length; i++) {
  2908. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2909. }
  2910. var continuedCurve = new Curve3(continuedPoints);
  2911. return continuedCurve;
  2912. };
  2913. Curve3.prototype._computeLength = function (path) {
  2914. var l = 0;
  2915. for (var i = 1; i < path.length; i++) {
  2916. l += (path[i].subtract(path[i - 1])).length();
  2917. }
  2918. return l;
  2919. };
  2920. return Curve3;
  2921. })();
  2922. BABYLON.Curve3 = Curve3;
  2923. // Vertex formats
  2924. var PositionNormalVertex = (function () {
  2925. function PositionNormalVertex(position, normal) {
  2926. if (position === void 0) { position = Vector3.Zero(); }
  2927. if (normal === void 0) { normal = Vector3.Up(); }
  2928. this.position = position;
  2929. this.normal = normal;
  2930. }
  2931. PositionNormalVertex.prototype.clone = function () {
  2932. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2933. };
  2934. return PositionNormalVertex;
  2935. })();
  2936. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2937. var PositionNormalTextureVertex = (function () {
  2938. function PositionNormalTextureVertex(position, normal, uv) {
  2939. if (position === void 0) { position = Vector3.Zero(); }
  2940. if (normal === void 0) { normal = Vector3.Up(); }
  2941. if (uv === void 0) { uv = Vector2.Zero(); }
  2942. this.position = position;
  2943. this.normal = normal;
  2944. this.uv = uv;
  2945. }
  2946. PositionNormalTextureVertex.prototype.clone = function () {
  2947. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2948. };
  2949. return PositionNormalTextureVertex;
  2950. })();
  2951. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2952. // Temporary pre-allocated objects for engine internal use
  2953. // usage in any internal function :
  2954. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2955. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2956. var Tmp = (function () {
  2957. function Tmp() {
  2958. }
  2959. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2960. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2961. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  2962. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2963. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2964. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2965. Matrix.Zero(), Matrix.Zero(),
  2966. Matrix.Zero(), Matrix.Zero(),
  2967. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2968. return Tmp;
  2969. })();
  2970. BABYLON.Tmp = Tmp;
  2971. })(BABYLON || (BABYLON = {}));
  2972. var BABYLON;
  2973. (function (BABYLON) {
  2974. var Database = (function () {
  2975. function Database(urlToScene, callbackManifestChecked) {
  2976. // Handling various flavors of prefixed version of IndexedDB
  2977. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2978. this.callbackManifestChecked = callbackManifestChecked;
  2979. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2980. this.db = null;
  2981. this.enableSceneOffline = false;
  2982. this.enableTexturesOffline = false;
  2983. this.manifestVersionFound = 0;
  2984. this.mustUpdateRessources = false;
  2985. this.hasReachedQuota = false;
  2986. if (!Database.IDBStorageEnabled) {
  2987. this.callbackManifestChecked(true);
  2988. }
  2989. else {
  2990. this.checkManifestFile();
  2991. }
  2992. }
  2993. Database.prototype.checkManifestFile = function () {
  2994. var _this = this;
  2995. function noManifestFile() {
  2996. that.enableSceneOffline = false;
  2997. that.enableTexturesOffline = false;
  2998. that.callbackManifestChecked(false);
  2999. }
  3000. var that = this;
  3001. var manifestURL = this.currentSceneUrl + ".manifest";
  3002. var xhr = new XMLHttpRequest();
  3003. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3004. xhr.open("GET", manifestURLTimeStamped, true);
  3005. xhr.addEventListener("load", function () {
  3006. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3007. try {
  3008. var manifestFile = JSON.parse(xhr.response);
  3009. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3010. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3011. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3012. _this.manifestVersionFound = manifestFile.version;
  3013. }
  3014. if (_this.callbackManifestChecked) {
  3015. _this.callbackManifestChecked(true);
  3016. }
  3017. }
  3018. catch (ex) {
  3019. noManifestFile();
  3020. }
  3021. }
  3022. else {
  3023. noManifestFile();
  3024. }
  3025. }, false);
  3026. xhr.addEventListener("error", function (event) {
  3027. noManifestFile();
  3028. }, false);
  3029. try {
  3030. xhr.send();
  3031. }
  3032. catch (ex) {
  3033. BABYLON.Tools.Error("Error on XHR send request.");
  3034. that.callbackManifestChecked(false);
  3035. }
  3036. };
  3037. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3038. var _this = this;
  3039. function handleError() {
  3040. that.isSupported = false;
  3041. if (errorCallback)
  3042. errorCallback();
  3043. }
  3044. var that = this;
  3045. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3046. // Your browser doesn't support IndexedDB
  3047. this.isSupported = false;
  3048. if (errorCallback)
  3049. errorCallback();
  3050. }
  3051. else {
  3052. // If the DB hasn't been opened or created yet
  3053. if (!this.db) {
  3054. this.hasReachedQuota = false;
  3055. this.isSupported = true;
  3056. var request = this.idbFactory.open("babylonjs", 1);
  3057. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3058. request.onerror = function (event) {
  3059. handleError();
  3060. };
  3061. // executes when a version change transaction cannot complete due to other active transactions
  3062. request.onblocked = function (event) {
  3063. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3064. handleError();
  3065. };
  3066. // DB has been opened successfully
  3067. request.onsuccess = function (event) {
  3068. _this.db = request.result;
  3069. successCallback();
  3070. };
  3071. // Initialization of the DB. Creating Scenes & Textures stores
  3072. request.onupgradeneeded = function (event) {
  3073. _this.db = (event.target).result;
  3074. try {
  3075. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3076. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3077. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3078. }
  3079. catch (ex) {
  3080. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3081. handleError();
  3082. }
  3083. };
  3084. }
  3085. else {
  3086. if (successCallback)
  3087. successCallback();
  3088. }
  3089. }
  3090. };
  3091. Database.prototype.loadImageFromDB = function (url, image) {
  3092. var _this = this;
  3093. var completeURL = Database.ReturnFullUrlLocation(url);
  3094. var saveAndLoadImage = function () {
  3095. if (!_this.hasReachedQuota && _this.db !== null) {
  3096. // the texture is not yet in the DB, let's try to save it
  3097. _this._saveImageIntoDBAsync(completeURL, image);
  3098. }
  3099. else {
  3100. image.src = url;
  3101. }
  3102. };
  3103. if (!this.mustUpdateRessources) {
  3104. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3105. }
  3106. else {
  3107. saveAndLoadImage();
  3108. }
  3109. };
  3110. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3111. if (this.isSupported && this.db !== null) {
  3112. var texture;
  3113. var transaction = this.db.transaction(["textures"]);
  3114. transaction.onabort = function (event) {
  3115. image.src = url;
  3116. };
  3117. transaction.oncomplete = function (event) {
  3118. var blobTextureURL;
  3119. if (texture) {
  3120. var URL = window.URL || window.webkitURL;
  3121. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3122. image.onerror = function () {
  3123. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3124. image.src = url;
  3125. };
  3126. image.src = blobTextureURL;
  3127. }
  3128. else {
  3129. notInDBCallback();
  3130. }
  3131. };
  3132. var getRequest = transaction.objectStore("textures").get(url);
  3133. getRequest.onsuccess = function (event) {
  3134. texture = (event.target).result;
  3135. };
  3136. getRequest.onerror = function (event) {
  3137. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3138. image.src = url;
  3139. };
  3140. }
  3141. else {
  3142. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3143. image.src = url;
  3144. }
  3145. };
  3146. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3147. var _this = this;
  3148. if (this.isSupported) {
  3149. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3150. var generateBlobUrl = function () {
  3151. var blobTextureURL;
  3152. if (blob) {
  3153. var URL = window.URL || window.webkitURL;
  3154. try {
  3155. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3156. }
  3157. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3158. catch (ex) {
  3159. blobTextureURL = URL.createObjectURL(blob);
  3160. }
  3161. }
  3162. image.src = blobTextureURL;
  3163. };
  3164. if (Database.IsUASupportingBlobStorage) {
  3165. var xhr = new XMLHttpRequest(), blob;
  3166. xhr.open("GET", url, true);
  3167. xhr.responseType = "blob";
  3168. xhr.addEventListener("load", function () {
  3169. if (xhr.status === 200) {
  3170. // Blob as response (XHR2)
  3171. blob = xhr.response;
  3172. var transaction = _this.db.transaction(["textures"], "readwrite");
  3173. // the transaction could abort because of a QuotaExceededError error
  3174. transaction.onabort = function (event) {
  3175. try {
  3176. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3177. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3178. this.hasReachedQuota = true;
  3179. }
  3180. }
  3181. catch (ex) { }
  3182. generateBlobUrl();
  3183. };
  3184. transaction.oncomplete = function (event) {
  3185. generateBlobUrl();
  3186. };
  3187. var newTexture = { textureUrl: url, data: blob };
  3188. try {
  3189. // Put the blob into the dabase
  3190. var addRequest = transaction.objectStore("textures").put(newTexture);
  3191. addRequest.onsuccess = function (event) {
  3192. };
  3193. addRequest.onerror = function (event) {
  3194. generateBlobUrl();
  3195. };
  3196. }
  3197. catch (ex) {
  3198. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3199. if (ex.code === 25) {
  3200. Database.IsUASupportingBlobStorage = false;
  3201. }
  3202. image.src = url;
  3203. }
  3204. }
  3205. else {
  3206. image.src = url;
  3207. }
  3208. }, false);
  3209. xhr.addEventListener("error", function (event) {
  3210. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3211. image.src = url;
  3212. }, false);
  3213. xhr.send();
  3214. }
  3215. else {
  3216. image.src = url;
  3217. }
  3218. }
  3219. else {
  3220. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3221. image.src = url;
  3222. }
  3223. };
  3224. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3225. var _this = this;
  3226. var updateVersion = function (event) {
  3227. // the version is not yet in the DB or we need to update it
  3228. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3229. };
  3230. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3231. };
  3232. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3233. var _this = this;
  3234. if (this.isSupported) {
  3235. var version;
  3236. try {
  3237. var transaction = this.db.transaction(["versions"]);
  3238. transaction.oncomplete = function (event) {
  3239. if (version) {
  3240. // If the version in the JSON file is > than the version in DB
  3241. if (_this.manifestVersionFound > version.data) {
  3242. _this.mustUpdateRessources = true;
  3243. updateInDBCallback();
  3244. }
  3245. else {
  3246. callback(version.data);
  3247. }
  3248. }
  3249. else {
  3250. _this.mustUpdateRessources = true;
  3251. updateInDBCallback();
  3252. }
  3253. };
  3254. transaction.onabort = function (event) {
  3255. callback(-1);
  3256. };
  3257. var getRequest = transaction.objectStore("versions").get(url);
  3258. getRequest.onsuccess = function (event) {
  3259. version = (event.target).result;
  3260. };
  3261. getRequest.onerror = function (event) {
  3262. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3263. callback(-1);
  3264. };
  3265. }
  3266. catch (ex) {
  3267. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3268. callback(-1);
  3269. }
  3270. }
  3271. else {
  3272. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3273. callback(-1);
  3274. }
  3275. };
  3276. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3277. var _this = this;
  3278. if (this.isSupported && !this.hasReachedQuota) {
  3279. try {
  3280. // Open a transaction to the database
  3281. var transaction = this.db.transaction(["versions"], "readwrite");
  3282. // the transaction could abort because of a QuotaExceededError error
  3283. transaction.onabort = function (event) {
  3284. try {
  3285. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3286. _this.hasReachedQuota = true;
  3287. }
  3288. }
  3289. catch (ex) { }
  3290. callback(-1);
  3291. };
  3292. transaction.oncomplete = function (event) {
  3293. callback(_this.manifestVersionFound);
  3294. };
  3295. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3296. // Put the scene into the database
  3297. var addRequest = transaction.objectStore("versions").put(newVersion);
  3298. addRequest.onsuccess = function (event) {
  3299. };
  3300. addRequest.onerror = function (event) {
  3301. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3302. };
  3303. }
  3304. catch (ex) {
  3305. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3306. callback(-1);
  3307. }
  3308. }
  3309. else {
  3310. callback(-1);
  3311. }
  3312. };
  3313. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3314. var _this = this;
  3315. var completeUrl = Database.ReturnFullUrlLocation(url);
  3316. var saveAndLoadFile = function (event) {
  3317. // the scene is not yet in the DB, let's try to save it
  3318. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3319. };
  3320. this._checkVersionFromDB(completeUrl, function (version) {
  3321. if (version !== -1) {
  3322. if (!_this.mustUpdateRessources) {
  3323. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3324. }
  3325. else {
  3326. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3327. }
  3328. }
  3329. else {
  3330. errorCallback();
  3331. }
  3332. });
  3333. };
  3334. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3335. if (this.isSupported) {
  3336. var targetStore;
  3337. if (url.indexOf(".babylon") !== -1) {
  3338. targetStore = "scenes";
  3339. }
  3340. else {
  3341. targetStore = "textures";
  3342. }
  3343. var file;
  3344. var transaction = this.db.transaction([targetStore]);
  3345. transaction.oncomplete = function (event) {
  3346. if (file) {
  3347. callback(file.data);
  3348. }
  3349. else {
  3350. notInDBCallback();
  3351. }
  3352. };
  3353. transaction.onabort = function (event) {
  3354. notInDBCallback();
  3355. };
  3356. var getRequest = transaction.objectStore(targetStore).get(url);
  3357. getRequest.onsuccess = function (event) {
  3358. file = (event.target).result;
  3359. };
  3360. getRequest.onerror = function (event) {
  3361. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3362. notInDBCallback();
  3363. };
  3364. }
  3365. else {
  3366. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3367. callback();
  3368. }
  3369. };
  3370. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3371. var _this = this;
  3372. if (this.isSupported) {
  3373. var targetStore;
  3374. if (url.indexOf(".babylon") !== -1) {
  3375. targetStore = "scenes";
  3376. }
  3377. else {
  3378. targetStore = "textures";
  3379. }
  3380. // Create XHR
  3381. var xhr = new XMLHttpRequest(), fileData;
  3382. xhr.open("GET", url, true);
  3383. if (useArrayBuffer) {
  3384. xhr.responseType = "arraybuffer";
  3385. }
  3386. xhr.onprogress = progressCallback;
  3387. xhr.addEventListener("load", function () {
  3388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3389. // Blob as response (XHR2)
  3390. //fileData = xhr.responseText;
  3391. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3392. if (!_this.hasReachedQuota) {
  3393. // Open a transaction to the database
  3394. var transaction = _this.db.transaction([targetStore], "readwrite");
  3395. // the transaction could abort because of a QuotaExceededError error
  3396. transaction.onabort = function (event) {
  3397. try {
  3398. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3399. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3400. this.hasReachedQuota = true;
  3401. }
  3402. }
  3403. catch (ex) { }
  3404. callback(fileData);
  3405. };
  3406. transaction.oncomplete = function (event) {
  3407. callback(fileData);
  3408. };
  3409. var newFile;
  3410. if (targetStore === "scenes") {
  3411. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3412. }
  3413. else {
  3414. newFile = { textureUrl: url, data: fileData };
  3415. }
  3416. try {
  3417. // Put the scene into the database
  3418. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3419. addRequest.onsuccess = function (event) {
  3420. };
  3421. addRequest.onerror = function (event) {
  3422. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3423. };
  3424. }
  3425. catch (ex) {
  3426. callback(fileData);
  3427. }
  3428. }
  3429. else {
  3430. callback(fileData);
  3431. }
  3432. }
  3433. else {
  3434. callback();
  3435. }
  3436. }, false);
  3437. xhr.addEventListener("error", function (event) {
  3438. BABYLON.Tools.Error("error on XHR request.");
  3439. callback();
  3440. }, false);
  3441. xhr.send();
  3442. }
  3443. else {
  3444. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3445. callback();
  3446. }
  3447. };
  3448. Database.IsUASupportingBlobStorage = true;
  3449. Database.IDBStorageEnabled = true;
  3450. Database.parseURL = function (url) {
  3451. var a = document.createElement('a');
  3452. a.href = url;
  3453. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3454. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3455. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3456. return absLocation;
  3457. };
  3458. Database.ReturnFullUrlLocation = function (url) {
  3459. if (url.indexOf("http:/") === -1) {
  3460. return (Database.parseURL(window.location.href) + url);
  3461. }
  3462. else {
  3463. return url;
  3464. }
  3465. };
  3466. return Database;
  3467. })();
  3468. BABYLON.Database = Database;
  3469. })(BABYLON || (BABYLON = {}));
  3470. var BABYLON;
  3471. (function (BABYLON) {
  3472. var Internals;
  3473. (function (Internals) {
  3474. /*
  3475. * Based on jsTGALoader - Javascript loader for TGA file
  3476. * By Vincent Thibault
  3477. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3478. */
  3479. var TGATools = (function () {
  3480. function TGATools() {
  3481. }
  3482. TGATools.GetTGAHeader = function (data) {
  3483. var offset = 0;
  3484. var header = {
  3485. id_length: data[offset++],
  3486. colormap_type: data[offset++],
  3487. image_type: data[offset++],
  3488. colormap_index: data[offset++] | data[offset++] << 8,
  3489. colormap_length: data[offset++] | data[offset++] << 8,
  3490. colormap_size: data[offset++],
  3491. origin: [
  3492. data[offset++] | data[offset++] << 8,
  3493. data[offset++] | data[offset++] << 8
  3494. ],
  3495. width: data[offset++] | data[offset++] << 8,
  3496. height: data[offset++] | data[offset++] << 8,
  3497. pixel_size: data[offset++],
  3498. flags: data[offset++]
  3499. };
  3500. return header;
  3501. };
  3502. TGATools.UploadContent = function (gl, data) {
  3503. // Not enough data to contain header ?
  3504. if (data.length < 19) {
  3505. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3506. return;
  3507. }
  3508. // Read Header
  3509. var offset = 18;
  3510. var header = TGATools.GetTGAHeader(data);
  3511. // Assume it's a valid Targa file.
  3512. if (header.id_length + offset > data.length) {
  3513. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3514. return;
  3515. }
  3516. // Skip not needed data
  3517. offset += header.id_length;
  3518. var use_rle = false;
  3519. var use_pal = false;
  3520. var use_rgb = false;
  3521. var use_grey = false;
  3522. // Get some informations.
  3523. switch (header.image_type) {
  3524. case TGATools._TYPE_RLE_INDEXED:
  3525. use_rle = true;
  3526. case TGATools._TYPE_INDEXED:
  3527. use_pal = true;
  3528. break;
  3529. case TGATools._TYPE_RLE_RGB:
  3530. use_rle = true;
  3531. case TGATools._TYPE_RGB:
  3532. use_rgb = true;
  3533. break;
  3534. case TGATools._TYPE_RLE_GREY:
  3535. use_rle = true;
  3536. case TGATools._TYPE_GREY:
  3537. use_grey = true;
  3538. break;
  3539. }
  3540. var pixel_data;
  3541. var numAlphaBits = header.flags & 0xf;
  3542. var pixel_size = header.pixel_size >> 3;
  3543. var pixel_total = header.width * header.height * pixel_size;
  3544. // Read palettes
  3545. var palettes;
  3546. if (use_pal) {
  3547. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3548. }
  3549. // Read LRE
  3550. if (use_rle) {
  3551. pixel_data = new Uint8Array(pixel_total);
  3552. var c, count, i;
  3553. var localOffset = 0;
  3554. var pixels = new Uint8Array(pixel_size);
  3555. while (offset < pixel_total && localOffset < pixel_total) {
  3556. c = data[offset++];
  3557. count = (c & 0x7f) + 1;
  3558. // RLE pixels
  3559. if (c & 0x80) {
  3560. // Bind pixel tmp array
  3561. for (i = 0; i < pixel_size; ++i) {
  3562. pixels[i] = data[offset++];
  3563. }
  3564. // Copy pixel array
  3565. for (i = 0; i < count; ++i) {
  3566. pixel_data.set(pixels, localOffset + i * pixel_size);
  3567. }
  3568. localOffset += pixel_size * count;
  3569. }
  3570. else {
  3571. count *= pixel_size;
  3572. for (i = 0; i < count; ++i) {
  3573. pixel_data[localOffset + i] = data[offset++];
  3574. }
  3575. localOffset += count;
  3576. }
  3577. }
  3578. }
  3579. else {
  3580. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3581. }
  3582. // Load to texture
  3583. var x_start, y_start, x_step, y_step, y_end, x_end;
  3584. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3585. default:
  3586. case TGATools._ORIGIN_UL:
  3587. x_start = 0;
  3588. x_step = 1;
  3589. x_end = header.width;
  3590. y_start = 0;
  3591. y_step = 1;
  3592. y_end = header.height;
  3593. break;
  3594. case TGATools._ORIGIN_BL:
  3595. x_start = 0;
  3596. x_step = 1;
  3597. x_end = header.width;
  3598. y_start = header.height - 1;
  3599. y_step = -1;
  3600. y_end = -1;
  3601. break;
  3602. case TGATools._ORIGIN_UR:
  3603. x_start = header.width - 1;
  3604. x_step = -1;
  3605. x_end = -1;
  3606. y_start = 0;
  3607. y_step = 1;
  3608. y_end = header.height;
  3609. break;
  3610. case TGATools._ORIGIN_BR:
  3611. x_start = header.width - 1;
  3612. x_step = -1;
  3613. x_end = -1;
  3614. y_start = header.height - 1;
  3615. y_step = -1;
  3616. y_end = -1;
  3617. break;
  3618. }
  3619. // Load the specify method
  3620. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3621. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3622. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3623. };
  3624. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3625. var image = pixel_data, colormap = palettes;
  3626. var width = header.width, height = header.height;
  3627. var color, i = 0, x, y;
  3628. var imageData = new Uint8Array(width * height * 4);
  3629. for (y = y_start; y !== y_end; y += y_step) {
  3630. for (x = x_start; x !== x_end; x += x_step, i++) {
  3631. color = image[i];
  3632. imageData[(x + width * y) * 4 + 3] = 255;
  3633. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3634. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3635. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3636. }
  3637. }
  3638. return imageData;
  3639. };
  3640. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3641. var image = pixel_data;
  3642. var width = header.width, height = header.height;
  3643. var color, i = 0, x, y;
  3644. var imageData = new Uint8Array(width * height * 4);
  3645. for (y = y_start; y !== y_end; y += y_step) {
  3646. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3647. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3648. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3649. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3650. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3651. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3652. }
  3653. }
  3654. return imageData;
  3655. };
  3656. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3657. var image = pixel_data;
  3658. var width = header.width, height = header.height;
  3659. var i = 0, x, y;
  3660. var imageData = new Uint8Array(width * height * 4);
  3661. for (y = y_start; y !== y_end; y += y_step) {
  3662. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3663. imageData[(x + width * y) * 4 + 3] = 255;
  3664. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3665. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3666. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3667. }
  3668. }
  3669. return imageData;
  3670. };
  3671. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3672. var image = pixel_data;
  3673. var width = header.width, height = header.height;
  3674. var i = 0, x, y;
  3675. var imageData = new Uint8Array(width * height * 4);
  3676. for (y = y_start; y !== y_end; y += y_step) {
  3677. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3678. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3679. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3680. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3681. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3682. }
  3683. }
  3684. return imageData;
  3685. };
  3686. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3687. var image = pixel_data;
  3688. var width = header.width, height = header.height;
  3689. var color, i = 0, x, y;
  3690. var imageData = new Uint8Array(width * height * 4);
  3691. for (y = y_start; y !== y_end; y += y_step) {
  3692. for (x = x_start; x !== x_end; x += x_step, i++) {
  3693. color = image[i];
  3694. imageData[(x + width * y) * 4 + 0] = color;
  3695. imageData[(x + width * y) * 4 + 1] = color;
  3696. imageData[(x + width * y) * 4 + 2] = color;
  3697. imageData[(x + width * y) * 4 + 3] = 255;
  3698. }
  3699. }
  3700. return imageData;
  3701. };
  3702. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3703. var image = pixel_data;
  3704. var width = header.width, height = header.height;
  3705. var i = 0, x, y;
  3706. var imageData = new Uint8Array(width * height * 4);
  3707. for (y = y_start; y !== y_end; y += y_step) {
  3708. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3709. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3710. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3711. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3712. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3713. }
  3714. }
  3715. return imageData;
  3716. };
  3717. TGATools._TYPE_NO_DATA = 0;
  3718. TGATools._TYPE_INDEXED = 1;
  3719. TGATools._TYPE_RGB = 2;
  3720. TGATools._TYPE_GREY = 3;
  3721. TGATools._TYPE_RLE_INDEXED = 9;
  3722. TGATools._TYPE_RLE_RGB = 10;
  3723. TGATools._TYPE_RLE_GREY = 11;
  3724. TGATools._ORIGIN_MASK = 0x30;
  3725. TGATools._ORIGIN_SHIFT = 0x04;
  3726. TGATools._ORIGIN_BL = 0x00;
  3727. TGATools._ORIGIN_BR = 0x01;
  3728. TGATools._ORIGIN_UL = 0x02;
  3729. TGATools._ORIGIN_UR = 0x03;
  3730. return TGATools;
  3731. })();
  3732. Internals.TGATools = TGATools;
  3733. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3734. })(BABYLON || (BABYLON = {}));
  3735. var BABYLON;
  3736. (function (BABYLON) {
  3737. var SmartArray = (function () {
  3738. function SmartArray(capacity) {
  3739. this.length = 0;
  3740. this._duplicateId = 0;
  3741. this.data = new Array(capacity);
  3742. this._id = SmartArray._GlobalId++;
  3743. }
  3744. SmartArray.prototype.push = function (value) {
  3745. this.data[this.length++] = value;
  3746. if (this.length > this.data.length) {
  3747. this.data.length *= 2;
  3748. }
  3749. if (!value.__smartArrayFlags) {
  3750. value.__smartArrayFlags = {};
  3751. }
  3752. value.__smartArrayFlags[this._id] = this._duplicateId;
  3753. };
  3754. SmartArray.prototype.pushNoDuplicate = function (value) {
  3755. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3756. return;
  3757. }
  3758. this.push(value);
  3759. };
  3760. SmartArray.prototype.sort = function (compareFn) {
  3761. this.data.sort(compareFn);
  3762. };
  3763. SmartArray.prototype.reset = function () {
  3764. this.length = 0;
  3765. this._duplicateId++;
  3766. };
  3767. SmartArray.prototype.concat = function (array) {
  3768. if (array.length === 0) {
  3769. return;
  3770. }
  3771. if (this.length + array.length > this.data.length) {
  3772. this.data.length = (this.length + array.length) * 2;
  3773. }
  3774. for (var index = 0; index < array.length; index++) {
  3775. this.data[this.length++] = (array.data || array)[index];
  3776. }
  3777. };
  3778. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3779. if (array.length === 0) {
  3780. return;
  3781. }
  3782. if (this.length + array.length > this.data.length) {
  3783. this.data.length = (this.length + array.length) * 2;
  3784. }
  3785. for (var index = 0; index < array.length; index++) {
  3786. var item = (array.data || array)[index];
  3787. this.pushNoDuplicate(item);
  3788. }
  3789. };
  3790. SmartArray.prototype.indexOf = function (value) {
  3791. var position = this.data.indexOf(value);
  3792. if (position >= this.length) {
  3793. return -1;
  3794. }
  3795. return position;
  3796. };
  3797. // Statics
  3798. SmartArray._GlobalId = 0;
  3799. return SmartArray;
  3800. })();
  3801. BABYLON.SmartArray = SmartArray;
  3802. })(BABYLON || (BABYLON = {}));
  3803. var BABYLON;
  3804. (function (BABYLON) {
  3805. var SmartCollection = (function () {
  3806. function SmartCollection(capacity) {
  3807. if (capacity === void 0) { capacity = 10; }
  3808. this.count = 0;
  3809. this._initialCapacity = capacity;
  3810. this.items = {};
  3811. this._keys = new Array(this._initialCapacity);
  3812. }
  3813. SmartCollection.prototype.add = function (key, item) {
  3814. if (this.items[key] != undefined) {
  3815. return -1;
  3816. }
  3817. this.items[key] = item;
  3818. //literal keys are always strings, but we keep source type of key in _keys array
  3819. this._keys[this.count++] = key;
  3820. if (this.count > this._keys.length) {
  3821. this._keys.length *= 2;
  3822. }
  3823. return this.count;
  3824. };
  3825. SmartCollection.prototype.remove = function (key) {
  3826. if (this.items[key] == undefined) {
  3827. return -1;
  3828. }
  3829. return this.removeItemOfIndex(this.indexOf(key));
  3830. };
  3831. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3832. if (index < this.count && index > -1) {
  3833. delete this.items[this._keys[index]];
  3834. //here, shifting by hand is better optimised than .splice
  3835. while (index < this.count) {
  3836. this._keys[index] = this._keys[index + 1];
  3837. index++;
  3838. }
  3839. }
  3840. else {
  3841. return -1;
  3842. }
  3843. return --this.count;
  3844. };
  3845. SmartCollection.prototype.indexOf = function (key) {
  3846. for (var i = 0; i !== this.count; i++) {
  3847. if (this._keys[i] === key) {
  3848. return i;
  3849. }
  3850. }
  3851. return -1;
  3852. };
  3853. SmartCollection.prototype.item = function (key) {
  3854. return this.items[key];
  3855. };
  3856. SmartCollection.prototype.getAllKeys = function () {
  3857. if (this.count > 0) {
  3858. var keys = new Array(this.count);
  3859. for (var i = 0; i < this.count; i++) {
  3860. keys[i] = this._keys[i];
  3861. }
  3862. return keys;
  3863. }
  3864. else {
  3865. return undefined;
  3866. }
  3867. };
  3868. SmartCollection.prototype.getKeyByIndex = function (index) {
  3869. if (index < this.count && index > -1) {
  3870. return this._keys[index];
  3871. }
  3872. else {
  3873. return undefined;
  3874. }
  3875. };
  3876. SmartCollection.prototype.getItemByIndex = function (index) {
  3877. if (index < this.count && index > -1) {
  3878. return this.items[this._keys[index]];
  3879. }
  3880. else {
  3881. return undefined;
  3882. }
  3883. };
  3884. SmartCollection.prototype.empty = function () {
  3885. if (this.count > 0) {
  3886. this.count = 0;
  3887. this.items = {};
  3888. this._keys = new Array(this._initialCapacity);
  3889. }
  3890. };
  3891. SmartCollection.prototype.forEach = function (block) {
  3892. var key;
  3893. for (key in this.items) {
  3894. if (this.items.hasOwnProperty(key)) {
  3895. block(this.items[key]);
  3896. }
  3897. }
  3898. };
  3899. return SmartCollection;
  3900. })();
  3901. BABYLON.SmartCollection = SmartCollection;
  3902. })(BABYLON || (BABYLON = {}));
  3903. var BABYLON;
  3904. (function (BABYLON) {
  3905. // Screenshots
  3906. var screenshotCanvas;
  3907. var cloneValue = function (source, destinationObject) {
  3908. if (!source)
  3909. return null;
  3910. if (source instanceof BABYLON.Mesh) {
  3911. return null;
  3912. }
  3913. if (source instanceof BABYLON.SubMesh) {
  3914. return source.clone(destinationObject);
  3915. }
  3916. else if (source.clone) {
  3917. return source.clone();
  3918. }
  3919. return null;
  3920. };
  3921. var Tools = (function () {
  3922. function Tools() {
  3923. }
  3924. Tools.Instantiate = function (className) {
  3925. var arr = className.split(".");
  3926. var fn = (window || this);
  3927. for (var i = 0, len = arr.length; i < len; i++) {
  3928. fn = fn[arr[i]];
  3929. }
  3930. if (typeof fn !== "function") {
  3931. return null;
  3932. }
  3933. return fn;
  3934. };
  3935. Tools.GetConstructorName = function (obj) {
  3936. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3937. var cname = str.match(/function\s(\w*)/)[1];
  3938. var aliases = ["", "anonymous", "Anonymous"];
  3939. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3940. };
  3941. Tools.ToHex = function (i) {
  3942. var str = i.toString(16);
  3943. if (i <= 15) {
  3944. return ("0" + str).toUpperCase();
  3945. }
  3946. return str.toUpperCase();
  3947. };
  3948. Tools.SetImmediate = function (action) {
  3949. if (window.setImmediate) {
  3950. window.setImmediate(action);
  3951. }
  3952. else {
  3953. setTimeout(action, 1);
  3954. }
  3955. };
  3956. Tools.IsExponentOfTwo = function (value) {
  3957. var count = 1;
  3958. do {
  3959. count *= 2;
  3960. } while (count < value);
  3961. return count === value;
  3962. };
  3963. Tools.GetExponentOfTwo = function (value, max) {
  3964. var count = 1;
  3965. do {
  3966. count *= 2;
  3967. } while (count < value);
  3968. if (count > max)
  3969. count = max;
  3970. return count;
  3971. };
  3972. Tools.GetFilename = function (path) {
  3973. var index = path.lastIndexOf("/");
  3974. if (index < 0)
  3975. return path;
  3976. return path.substring(index + 1);
  3977. };
  3978. Tools.GetDOMTextContent = function (element) {
  3979. var result = "";
  3980. var child = element.firstChild;
  3981. while (child) {
  3982. if (child.nodeType === 3) {
  3983. result += child.textContent;
  3984. }
  3985. child = child.nextSibling;
  3986. }
  3987. return result;
  3988. };
  3989. Tools.ToDegrees = function (angle) {
  3990. return angle * 180 / Math.PI;
  3991. };
  3992. Tools.ToRadians = function (angle) {
  3993. return angle * Math.PI / 180;
  3994. };
  3995. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3996. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3997. var output = "";
  3998. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3999. var i = 0;
  4000. var bytes = new Uint8Array(buffer);
  4001. while (i < bytes.length) {
  4002. chr1 = bytes[i++];
  4003. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4004. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4005. enc1 = chr1 >> 2;
  4006. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4007. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4008. enc4 = chr3 & 63;
  4009. if (isNaN(chr2)) {
  4010. enc3 = enc4 = 64;
  4011. }
  4012. else if (isNaN(chr3)) {
  4013. enc4 = 64;
  4014. }
  4015. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4016. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4017. }
  4018. return "data:image/png;base64," + output;
  4019. };
  4020. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4021. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4022. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4023. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4024. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4025. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4026. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4027. }
  4028. return {
  4029. minimum: minimum,
  4030. maximum: maximum
  4031. };
  4032. };
  4033. Tools.ExtractMinAndMax = function (positions, start, count) {
  4034. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4035. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4036. for (var index = start; index < start + count; index++) {
  4037. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4038. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4039. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4040. }
  4041. return {
  4042. minimum: minimum,
  4043. maximum: maximum
  4044. };
  4045. };
  4046. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4047. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4048. return undefined;
  4049. return Array.isArray(obj) ? obj : [obj];
  4050. };
  4051. // Misc.
  4052. Tools.GetPointerPrefix = function () {
  4053. var eventPrefix = "pointer";
  4054. // Check if pointer events are supported
  4055. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4056. eventPrefix = "mouse";
  4057. }
  4058. return eventPrefix;
  4059. };
  4060. Tools.QueueNewFrame = function (func) {
  4061. if (window.requestAnimationFrame)
  4062. window.requestAnimationFrame(func);
  4063. else if (window.msRequestAnimationFrame)
  4064. window.msRequestAnimationFrame(func);
  4065. else if (window.webkitRequestAnimationFrame)
  4066. window.webkitRequestAnimationFrame(func);
  4067. else if (window.mozRequestAnimationFrame)
  4068. window.mozRequestAnimationFrame(func);
  4069. else if (window.oRequestAnimationFrame)
  4070. window.oRequestAnimationFrame(func);
  4071. else {
  4072. window.setTimeout(func, 16);
  4073. }
  4074. };
  4075. Tools.RequestFullscreen = function (element) {
  4076. if (element.requestFullscreen)
  4077. element.requestFullscreen();
  4078. else if (element.msRequestFullscreen)
  4079. element.msRequestFullscreen();
  4080. else if (element.webkitRequestFullscreen)
  4081. element.webkitRequestFullscreen();
  4082. else if (element.mozRequestFullScreen)
  4083. element.mozRequestFullScreen();
  4084. };
  4085. Tools.ExitFullscreen = function () {
  4086. if (document.exitFullscreen) {
  4087. document.exitFullscreen();
  4088. }
  4089. else if (document.mozCancelFullScreen) {
  4090. document.mozCancelFullScreen();
  4091. }
  4092. else if (document.webkitCancelFullScreen) {
  4093. document.webkitCancelFullScreen();
  4094. }
  4095. else if (document.msCancelFullScreen) {
  4096. document.msCancelFullScreen();
  4097. }
  4098. };
  4099. // External files
  4100. Tools.CleanUrl = function (url) {
  4101. url = url.replace(/#/mg, "%23");
  4102. return url;
  4103. };
  4104. Tools.LoadImage = function (url, onload, onerror, database) {
  4105. if (url instanceof ArrayBuffer) {
  4106. url = Tools.EncodeArrayBufferTobase64(url);
  4107. }
  4108. url = Tools.CleanUrl(url);
  4109. var img = new Image();
  4110. if (url.substr(0, 5) !== "data:") {
  4111. if (Tools.CorsBehavior) {
  4112. switch (typeof (Tools.CorsBehavior)) {
  4113. case "function":
  4114. var result = Tools.CorsBehavior(url);
  4115. if (result) {
  4116. img.crossOrigin = result;
  4117. }
  4118. break;
  4119. case "string":
  4120. default:
  4121. img.crossOrigin = Tools.CorsBehavior;
  4122. break;
  4123. }
  4124. }
  4125. }
  4126. img.onload = function () {
  4127. onload(img);
  4128. };
  4129. img.onerror = function (err) {
  4130. Tools.Error("Error while trying to load texture: " + url);
  4131. 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";
  4132. onload(img);
  4133. };
  4134. var noIndexedDB = function () {
  4135. img.src = url;
  4136. };
  4137. var loadFromIndexedDB = function () {
  4138. database.loadImageFromDB(url, img);
  4139. };
  4140. //ANY database to do!
  4141. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4142. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4143. }
  4144. else {
  4145. if (url.indexOf("file:") === -1) {
  4146. noIndexedDB();
  4147. }
  4148. else {
  4149. try {
  4150. var textureName = url.substring(5);
  4151. var blobURL;
  4152. try {
  4153. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4154. }
  4155. catch (ex) {
  4156. // Chrome doesn't support oneTimeOnly parameter
  4157. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4158. }
  4159. img.src = blobURL;
  4160. }
  4161. catch (e) {
  4162. img.src = null;
  4163. }
  4164. }
  4165. }
  4166. return img;
  4167. };
  4168. //ANY
  4169. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4170. url = Tools.CleanUrl(url);
  4171. var noIndexedDB = function () {
  4172. var request = new XMLHttpRequest();
  4173. var loadUrl = Tools.BaseUrl + url;
  4174. request.open('GET', loadUrl, true);
  4175. if (useArrayBuffer) {
  4176. request.responseType = "arraybuffer";
  4177. }
  4178. request.onprogress = progressCallBack;
  4179. request.onreadystatechange = function () {
  4180. if (request.readyState === 4) {
  4181. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4182. callback(!useArrayBuffer ? request.responseText : request.response);
  4183. }
  4184. else {
  4185. if (onError) {
  4186. onError();
  4187. }
  4188. else {
  4189. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4190. }
  4191. }
  4192. }
  4193. };
  4194. request.send(null);
  4195. };
  4196. var loadFromIndexedDB = function () {
  4197. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4198. };
  4199. if (url.indexOf("file:") !== -1) {
  4200. var fileName = url.substring(5);
  4201. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4202. }
  4203. else {
  4204. // Caching all files
  4205. if (database && database.enableSceneOffline) {
  4206. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4207. }
  4208. else {
  4209. noIndexedDB();
  4210. }
  4211. }
  4212. };
  4213. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4214. var reader = new FileReader();
  4215. reader.onload = function (e) {
  4216. //target doesn't have result from ts 1.3
  4217. callback(e.target['result']);
  4218. };
  4219. reader.onprogress = progressCallback;
  4220. reader.readAsDataURL(fileToLoad);
  4221. };
  4222. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4223. var reader = new FileReader();
  4224. reader.onerror = function (e) {
  4225. Tools.Log("Error while reading file: " + fileToLoad.name);
  4226. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4227. };
  4228. reader.onload = function (e) {
  4229. //target doesn't have result from ts 1.3
  4230. callback(e.target['result']);
  4231. };
  4232. reader.onprogress = progressCallBack;
  4233. if (!useArrayBuffer) {
  4234. // Asynchronous read
  4235. reader.readAsText(fileToLoad);
  4236. }
  4237. else {
  4238. reader.readAsArrayBuffer(fileToLoad);
  4239. }
  4240. };
  4241. //returns a downloadable url to a file content.
  4242. Tools.FileAsURL = function (content) {
  4243. var fileBlob = new Blob([content]);
  4244. var url = window.URL || window.webkitURL;
  4245. var link = url.createObjectURL(fileBlob);
  4246. return link;
  4247. };
  4248. // Misc.
  4249. Tools.Clamp = function (value, min, max) {
  4250. if (min === void 0) { min = 0; }
  4251. if (max === void 0) { max = 1; }
  4252. return Math.min(max, Math.max(min, value));
  4253. };
  4254. // Returns -1 when value is a negative number and
  4255. // +1 when value is a positive number.
  4256. Tools.Sign = function (value) {
  4257. value = +value; // convert to a number
  4258. if (value === 0 || isNaN(value))
  4259. return value;
  4260. return value > 0 ? 1 : -1;
  4261. };
  4262. Tools.Format = function (value, decimals) {
  4263. if (decimals === void 0) { decimals = 2; }
  4264. return value.toFixed(decimals);
  4265. };
  4266. Tools.CheckExtends = function (v, min, max) {
  4267. if (v.x < min.x)
  4268. min.x = v.x;
  4269. if (v.y < min.y)
  4270. min.y = v.y;
  4271. if (v.z < min.z)
  4272. min.z = v.z;
  4273. if (v.x > max.x)
  4274. max.x = v.x;
  4275. if (v.y > max.y)
  4276. max.y = v.y;
  4277. if (v.z > max.z)
  4278. max.z = v.z;
  4279. };
  4280. Tools.WithinEpsilon = function (a, b, epsilon) {
  4281. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4282. var num = a - b;
  4283. return -epsilon <= num && num <= epsilon;
  4284. };
  4285. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4286. for (var prop in source) {
  4287. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4288. continue;
  4289. }
  4290. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4291. continue;
  4292. }
  4293. var sourceValue = source[prop];
  4294. var typeOfSourceValue = typeof sourceValue;
  4295. if (typeOfSourceValue === "function") {
  4296. continue;
  4297. }
  4298. if (typeOfSourceValue === "object") {
  4299. if (sourceValue instanceof Array) {
  4300. destination[prop] = [];
  4301. if (sourceValue.length > 0) {
  4302. if (typeof sourceValue[0] == "object") {
  4303. for (var index = 0; index < sourceValue.length; index++) {
  4304. var clonedValue = cloneValue(sourceValue[index], destination);
  4305. if (destination[prop].indexOf(clonedValue) === -1) {
  4306. destination[prop].push(clonedValue);
  4307. }
  4308. }
  4309. }
  4310. else {
  4311. destination[prop] = sourceValue.slice(0);
  4312. }
  4313. }
  4314. }
  4315. else {
  4316. destination[prop] = cloneValue(sourceValue, destination);
  4317. }
  4318. }
  4319. else {
  4320. destination[prop] = sourceValue;
  4321. }
  4322. }
  4323. };
  4324. Tools.IsEmpty = function (obj) {
  4325. for (var i in obj) {
  4326. return false;
  4327. }
  4328. return true;
  4329. };
  4330. Tools.RegisterTopRootEvents = function (events) {
  4331. for (var index = 0; index < events.length; index++) {
  4332. var event = events[index];
  4333. window.addEventListener(event.name, event.handler, false);
  4334. try {
  4335. if (window.parent) {
  4336. window.parent.addEventListener(event.name, event.handler, false);
  4337. }
  4338. }
  4339. catch (e) {
  4340. }
  4341. }
  4342. };
  4343. Tools.UnregisterTopRootEvents = function (events) {
  4344. for (var index = 0; index < events.length; index++) {
  4345. var event = events[index];
  4346. window.removeEventListener(event.name, event.handler);
  4347. try {
  4348. if (window.parent) {
  4349. window.parent.removeEventListener(event.name, event.handler);
  4350. }
  4351. }
  4352. catch (e) {
  4353. }
  4354. }
  4355. };
  4356. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4357. // Read the contents of the framebuffer
  4358. var numberOfChannelsByLine = width * 4;
  4359. var halfHeight = height / 2;
  4360. //Reading datas from WebGL
  4361. var data = engine.readPixels(0, 0, width, height);
  4362. //To flip image on Y axis.
  4363. for (var i = 0; i < halfHeight; i++) {
  4364. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4365. var currentCell = j + i * numberOfChannelsByLine;
  4366. var targetLine = height - i - 1;
  4367. var targetCell = j + targetLine * numberOfChannelsByLine;
  4368. var temp = data[currentCell];
  4369. data[currentCell] = data[targetCell];
  4370. data[targetCell] = temp;
  4371. }
  4372. }
  4373. // Create a 2D canvas to store the result
  4374. if (!screenshotCanvas) {
  4375. screenshotCanvas = document.createElement('canvas');
  4376. }
  4377. screenshotCanvas.width = width;
  4378. screenshotCanvas.height = height;
  4379. var context = screenshotCanvas.getContext('2d');
  4380. // Copy the pixels to a 2D canvas
  4381. var imageData = context.createImageData(width, height);
  4382. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4383. var castData = imageData.data;
  4384. castData.set(data);
  4385. context.putImageData(imageData, 0, 0);
  4386. var base64Image = screenshotCanvas.toDataURL();
  4387. if (successCallback) {
  4388. successCallback(base64Image);
  4389. }
  4390. else {
  4391. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4392. if (("download" in document.createElement("a"))) {
  4393. var a = window.document.createElement("a");
  4394. a.href = base64Image;
  4395. var date = new Date();
  4396. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4397. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4398. window.document.body.appendChild(a);
  4399. a.addEventListener("click", function () {
  4400. a.parentElement.removeChild(a);
  4401. });
  4402. a.click();
  4403. }
  4404. else {
  4405. var newWindow = window.open("");
  4406. var img = newWindow.document.createElement("img");
  4407. img.src = base64Image;
  4408. newWindow.document.body.appendChild(img);
  4409. }
  4410. }
  4411. };
  4412. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4413. var width;
  4414. var height;
  4415. //If a precision value is specified
  4416. if (size.precision) {
  4417. width = Math.round(engine.getRenderWidth() * size.precision);
  4418. height = Math.round(width / engine.getAspectRatio(camera));
  4419. size = { width: width, height: height };
  4420. }
  4421. else if (size.width && size.height) {
  4422. width = size.width;
  4423. height = size.height;
  4424. }
  4425. else if (size.width && !size.height) {
  4426. width = size.width;
  4427. height = Math.round(width / engine.getAspectRatio(camera));
  4428. size = { width: width, height: height };
  4429. }
  4430. else if (size.height && !size.width) {
  4431. height = size.height;
  4432. width = Math.round(height * engine.getAspectRatio(camera));
  4433. size = { width: width, height: height };
  4434. }
  4435. else if (!isNaN(size)) {
  4436. height = size;
  4437. width = size;
  4438. }
  4439. else {
  4440. Tools.Error("Invalid 'size' parameter !");
  4441. return;
  4442. }
  4443. var scene = camera.getScene();
  4444. var previousCamera = null;
  4445. if (scene.activeCamera !== camera) {
  4446. previousCamera = scene.activeCamera;
  4447. scene.activeCamera = camera;
  4448. }
  4449. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4450. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4451. texture.renderList = scene.meshes;
  4452. texture.onAfterRender = function () {
  4453. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4454. };
  4455. scene.incrementRenderId();
  4456. texture.render(true);
  4457. texture.dispose();
  4458. if (previousCamera) {
  4459. scene.activeCamera = previousCamera;
  4460. }
  4461. camera.getProjectionMatrix(true); // Force cache refresh;
  4462. };
  4463. // XHR response validator for local file scenario
  4464. Tools.ValidateXHRData = function (xhr, dataType) {
  4465. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4466. if (dataType === void 0) { dataType = 7; }
  4467. try {
  4468. if (dataType & 1) {
  4469. if (xhr.responseText && xhr.responseText.length > 0) {
  4470. return true;
  4471. }
  4472. else if (dataType === 1) {
  4473. return false;
  4474. }
  4475. }
  4476. if (dataType & 2) {
  4477. // Check header width and height since there is no "TGA" magic number
  4478. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4479. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4480. return true;
  4481. }
  4482. else if (dataType === 2) {
  4483. return false;
  4484. }
  4485. }
  4486. if (dataType & 4) {
  4487. // Check for the "DDS" magic number
  4488. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4489. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4490. return true;
  4491. }
  4492. else {
  4493. return false;
  4494. }
  4495. }
  4496. }
  4497. catch (e) {
  4498. }
  4499. return false;
  4500. };
  4501. Object.defineProperty(Tools, "NoneLogLevel", {
  4502. get: function () {
  4503. return Tools._NoneLogLevel;
  4504. },
  4505. enumerable: true,
  4506. configurable: true
  4507. });
  4508. Object.defineProperty(Tools, "MessageLogLevel", {
  4509. get: function () {
  4510. return Tools._MessageLogLevel;
  4511. },
  4512. enumerable: true,
  4513. configurable: true
  4514. });
  4515. Object.defineProperty(Tools, "WarningLogLevel", {
  4516. get: function () {
  4517. return Tools._WarningLogLevel;
  4518. },
  4519. enumerable: true,
  4520. configurable: true
  4521. });
  4522. Object.defineProperty(Tools, "ErrorLogLevel", {
  4523. get: function () {
  4524. return Tools._ErrorLogLevel;
  4525. },
  4526. enumerable: true,
  4527. configurable: true
  4528. });
  4529. Object.defineProperty(Tools, "AllLogLevel", {
  4530. get: function () {
  4531. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Tools._AddLogEntry = function (entry) {
  4537. Tools._LogCache = entry + Tools._LogCache;
  4538. if (Tools.OnNewCacheEntry) {
  4539. Tools.OnNewCacheEntry(entry);
  4540. }
  4541. };
  4542. Tools._FormatMessage = function (message) {
  4543. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4544. var date = new Date();
  4545. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4546. };
  4547. Tools._LogDisabled = function (message) {
  4548. // nothing to do
  4549. };
  4550. Tools._LogEnabled = function (message) {
  4551. var formattedMessage = Tools._FormatMessage(message);
  4552. console.log("BJS - " + formattedMessage);
  4553. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4554. Tools._AddLogEntry(entry);
  4555. };
  4556. Tools._WarnDisabled = function (message) {
  4557. // nothing to do
  4558. };
  4559. Tools._WarnEnabled = function (message) {
  4560. var formattedMessage = Tools._FormatMessage(message);
  4561. console.warn("BJS - " + formattedMessage);
  4562. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4563. Tools._AddLogEntry(entry);
  4564. };
  4565. Tools._ErrorDisabled = function (message) {
  4566. // nothing to do
  4567. };
  4568. Tools._ErrorEnabled = function (message) {
  4569. Tools.errorsCount++;
  4570. var formattedMessage = Tools._FormatMessage(message);
  4571. console.error("BJS - " + formattedMessage);
  4572. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4573. Tools._AddLogEntry(entry);
  4574. };
  4575. Object.defineProperty(Tools, "LogCache", {
  4576. get: function () {
  4577. return Tools._LogCache;
  4578. },
  4579. enumerable: true,
  4580. configurable: true
  4581. });
  4582. Tools.ClearLogCache = function () {
  4583. Tools._LogCache = "";
  4584. Tools.errorsCount = 0;
  4585. };
  4586. Object.defineProperty(Tools, "LogLevels", {
  4587. set: function (level) {
  4588. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4589. Tools.Log = Tools._LogEnabled;
  4590. }
  4591. else {
  4592. Tools.Log = Tools._LogDisabled;
  4593. }
  4594. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4595. Tools.Warn = Tools._WarnEnabled;
  4596. }
  4597. else {
  4598. Tools.Warn = Tools._WarnDisabled;
  4599. }
  4600. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4601. Tools.Error = Tools._ErrorEnabled;
  4602. }
  4603. else {
  4604. Tools.Error = Tools._ErrorDisabled;
  4605. }
  4606. },
  4607. enumerable: true,
  4608. configurable: true
  4609. });
  4610. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4611. get: function () {
  4612. return Tools._PerformanceNoneLogLevel;
  4613. },
  4614. enumerable: true,
  4615. configurable: true
  4616. });
  4617. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4618. get: function () {
  4619. return Tools._PerformanceUserMarkLogLevel;
  4620. },
  4621. enumerable: true,
  4622. configurable: true
  4623. });
  4624. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4625. get: function () {
  4626. return Tools._PerformanceConsoleLogLevel;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4632. set: function (level) {
  4633. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4634. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4635. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4636. return;
  4637. }
  4638. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4639. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4640. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4641. return;
  4642. }
  4643. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4644. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4645. },
  4646. enumerable: true,
  4647. configurable: true
  4648. });
  4649. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4650. };
  4651. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4652. };
  4653. Tools._StartUserMark = function (counterName, condition) {
  4654. if (condition === void 0) { condition = true; }
  4655. if (!condition || !Tools._performance.mark) {
  4656. return;
  4657. }
  4658. Tools._performance.mark(counterName + "-Begin");
  4659. };
  4660. Tools._EndUserMark = function (counterName, condition) {
  4661. if (condition === void 0) { condition = true; }
  4662. if (!condition || !Tools._performance.mark) {
  4663. return;
  4664. }
  4665. Tools._performance.mark(counterName + "-End");
  4666. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4667. };
  4668. Tools._StartPerformanceConsole = function (counterName, condition) {
  4669. if (condition === void 0) { condition = true; }
  4670. if (!condition) {
  4671. return;
  4672. }
  4673. Tools._StartUserMark(counterName, condition);
  4674. if (console.time) {
  4675. console.time(counterName);
  4676. }
  4677. };
  4678. Tools._EndPerformanceConsole = function (counterName, condition) {
  4679. if (condition === void 0) { condition = true; }
  4680. if (!condition) {
  4681. return;
  4682. }
  4683. Tools._EndUserMark(counterName, condition);
  4684. if (console.time) {
  4685. console.timeEnd(counterName);
  4686. }
  4687. };
  4688. Object.defineProperty(Tools, "Now", {
  4689. get: function () {
  4690. if (window.performance && window.performance.now) {
  4691. return window.performance.now();
  4692. }
  4693. return new Date().getTime();
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. Tools.BaseUrl = "";
  4699. Tools.CorsBehavior = "anonymous";
  4700. // Logs
  4701. Tools._NoneLogLevel = 0;
  4702. Tools._MessageLogLevel = 1;
  4703. Tools._WarningLogLevel = 2;
  4704. Tools._ErrorLogLevel = 4;
  4705. Tools._LogCache = "";
  4706. Tools.errorsCount = 0;
  4707. Tools.Log = Tools._LogEnabled;
  4708. Tools.Warn = Tools._WarnEnabled;
  4709. Tools.Error = Tools._ErrorEnabled;
  4710. // Performances
  4711. Tools._PerformanceNoneLogLevel = 0;
  4712. Tools._PerformanceUserMarkLogLevel = 1;
  4713. Tools._PerformanceConsoleLogLevel = 2;
  4714. Tools._performance = window.performance;
  4715. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4716. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4717. return Tools;
  4718. })();
  4719. BABYLON.Tools = Tools;
  4720. /**
  4721. * An implementation of a loop for asynchronous functions.
  4722. */
  4723. var AsyncLoop = (function () {
  4724. /**
  4725. * Constroctor.
  4726. * @param iterations the number of iterations.
  4727. * @param _fn the function to run each iteration
  4728. * @param _successCallback the callback that will be called upon succesful execution
  4729. * @param offset starting offset.
  4730. */
  4731. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4732. if (offset === void 0) { offset = 0; }
  4733. this.iterations = iterations;
  4734. this._fn = _fn;
  4735. this._successCallback = _successCallback;
  4736. this.index = offset - 1;
  4737. this._done = false;
  4738. }
  4739. /**
  4740. * Execute the next iteration. Must be called after the last iteration was finished.
  4741. */
  4742. AsyncLoop.prototype.executeNext = function () {
  4743. if (!this._done) {
  4744. if (this.index + 1 < this.iterations) {
  4745. ++this.index;
  4746. this._fn(this);
  4747. }
  4748. else {
  4749. this.breakLoop();
  4750. }
  4751. }
  4752. };
  4753. /**
  4754. * Break the loop and run the success callback.
  4755. */
  4756. AsyncLoop.prototype.breakLoop = function () {
  4757. this._done = true;
  4758. this._successCallback();
  4759. };
  4760. /**
  4761. * Helper function
  4762. */
  4763. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4764. if (offset === void 0) { offset = 0; }
  4765. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4766. loop.executeNext();
  4767. return loop;
  4768. };
  4769. /**
  4770. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4771. * @param iterations total number of iterations
  4772. * @param syncedIterations number of synchronous iterations in each async iteration.
  4773. * @param fn the function to call each iteration.
  4774. * @param callback a success call back that will be called when iterating stops.
  4775. * @param breakFunction a break condition (optional)
  4776. * @param timeout timeout settings for the setTimeout function. default - 0.
  4777. * @constructor
  4778. */
  4779. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4780. if (timeout === void 0) { timeout = 0; }
  4781. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4782. if (breakFunction && breakFunction())
  4783. loop.breakLoop();
  4784. else {
  4785. setTimeout(function () {
  4786. for (var i = 0; i < syncedIterations; ++i) {
  4787. var iteration = (loop.index * syncedIterations) + i;
  4788. if (iteration >= iterations)
  4789. break;
  4790. fn(iteration);
  4791. if (breakFunction && breakFunction()) {
  4792. loop.breakLoop();
  4793. break;
  4794. }
  4795. }
  4796. loop.executeNext();
  4797. }, timeout);
  4798. }
  4799. }, callback);
  4800. };
  4801. return AsyncLoop;
  4802. })();
  4803. BABYLON.AsyncLoop = AsyncLoop;
  4804. })(BABYLON || (BABYLON = {}));
  4805. var BABYLON;
  4806. (function (BABYLON) {
  4807. var _DepthCullingState = (function () {
  4808. function _DepthCullingState() {
  4809. this._isDepthTestDirty = false;
  4810. this._isDepthMaskDirty = false;
  4811. this._isDepthFuncDirty = false;
  4812. this._isCullFaceDirty = false;
  4813. this._isCullDirty = false;
  4814. this._isZOffsetDirty = false;
  4815. }
  4816. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4817. get: function () {
  4818. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4824. get: function () {
  4825. return this._zOffset;
  4826. },
  4827. set: function (value) {
  4828. if (this._zOffset === value) {
  4829. return;
  4830. }
  4831. this._zOffset = value;
  4832. this._isZOffsetDirty = true;
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4838. get: function () {
  4839. return this._cullFace;
  4840. },
  4841. set: function (value) {
  4842. if (this._cullFace === value) {
  4843. return;
  4844. }
  4845. this._cullFace = value;
  4846. this._isCullFaceDirty = true;
  4847. },
  4848. enumerable: true,
  4849. configurable: true
  4850. });
  4851. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4852. get: function () {
  4853. return this._cull;
  4854. },
  4855. set: function (value) {
  4856. if (this._cull === value) {
  4857. return;
  4858. }
  4859. this._cull = value;
  4860. this._isCullDirty = true;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4866. get: function () {
  4867. return this._depthFunc;
  4868. },
  4869. set: function (value) {
  4870. if (this._depthFunc === value) {
  4871. return;
  4872. }
  4873. this._depthFunc = value;
  4874. this._isDepthFuncDirty = true;
  4875. },
  4876. enumerable: true,
  4877. configurable: true
  4878. });
  4879. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4880. get: function () {
  4881. return this._depthMask;
  4882. },
  4883. set: function (value) {
  4884. if (this._depthMask === value) {
  4885. return;
  4886. }
  4887. this._depthMask = value;
  4888. this._isDepthMaskDirty = true;
  4889. },
  4890. enumerable: true,
  4891. configurable: true
  4892. });
  4893. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4894. get: function () {
  4895. return this._depthTest;
  4896. },
  4897. set: function (value) {
  4898. if (this._depthTest === value) {
  4899. return;
  4900. }
  4901. this._depthTest = value;
  4902. this._isDepthTestDirty = true;
  4903. },
  4904. enumerable: true,
  4905. configurable: true
  4906. });
  4907. _DepthCullingState.prototype.reset = function () {
  4908. this._depthMask = true;
  4909. this._depthTest = true;
  4910. this._depthFunc = null;
  4911. this._cull = null;
  4912. this._cullFace = null;
  4913. this._zOffset = 0;
  4914. this._isDepthTestDirty = true;
  4915. this._isDepthMaskDirty = true;
  4916. this._isDepthFuncDirty = false;
  4917. this._isCullFaceDirty = false;
  4918. this._isCullDirty = false;
  4919. this._isZOffsetDirty = false;
  4920. };
  4921. _DepthCullingState.prototype.apply = function (gl) {
  4922. if (!this.isDirty) {
  4923. return;
  4924. }
  4925. // Cull
  4926. if (this._isCullDirty) {
  4927. if (this.cull) {
  4928. gl.enable(gl.CULL_FACE);
  4929. }
  4930. else {
  4931. gl.disable(gl.CULL_FACE);
  4932. }
  4933. this._isCullDirty = false;
  4934. }
  4935. // Cull face
  4936. if (this._isCullFaceDirty) {
  4937. gl.cullFace(this.cullFace);
  4938. this._isCullFaceDirty = false;
  4939. }
  4940. // Depth mask
  4941. if (this._isDepthMaskDirty) {
  4942. gl.depthMask(this.depthMask);
  4943. this._isDepthMaskDirty = false;
  4944. }
  4945. // Depth test
  4946. if (this._isDepthTestDirty) {
  4947. if (this.depthTest) {
  4948. gl.enable(gl.DEPTH_TEST);
  4949. }
  4950. else {
  4951. gl.disable(gl.DEPTH_TEST);
  4952. }
  4953. this._isDepthTestDirty = false;
  4954. }
  4955. // Depth func
  4956. if (this._isDepthFuncDirty) {
  4957. gl.depthFunc(this.depthFunc);
  4958. this._isDepthFuncDirty = false;
  4959. }
  4960. // zOffset
  4961. if (this._isZOffsetDirty) {
  4962. if (this.zOffset) {
  4963. gl.enable(gl.POLYGON_OFFSET_FILL);
  4964. gl.polygonOffset(this.zOffset, 0);
  4965. }
  4966. else {
  4967. gl.disable(gl.POLYGON_OFFSET_FILL);
  4968. }
  4969. this._isZOffsetDirty = false;
  4970. }
  4971. };
  4972. return _DepthCullingState;
  4973. })();
  4974. BABYLON._DepthCullingState = _DepthCullingState;
  4975. var _AlphaState = (function () {
  4976. function _AlphaState() {
  4977. this._isAlphaBlendDirty = false;
  4978. this._isBlendFunctionParametersDirty = false;
  4979. this._alphaBlend = false;
  4980. this._blendFunctionParameters = new Array(4);
  4981. }
  4982. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4983. get: function () {
  4984. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4985. },
  4986. enumerable: true,
  4987. configurable: true
  4988. });
  4989. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4990. get: function () {
  4991. return this._alphaBlend;
  4992. },
  4993. set: function (value) {
  4994. if (this._alphaBlend === value) {
  4995. return;
  4996. }
  4997. this._alphaBlend = value;
  4998. this._isAlphaBlendDirty = true;
  4999. },
  5000. enumerable: true,
  5001. configurable: true
  5002. });
  5003. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5004. if (this._blendFunctionParameters[0] === value0 &&
  5005. this._blendFunctionParameters[1] === value1 &&
  5006. this._blendFunctionParameters[2] === value2 &&
  5007. this._blendFunctionParameters[3] === value3) {
  5008. return;
  5009. }
  5010. this._blendFunctionParameters[0] = value0;
  5011. this._blendFunctionParameters[1] = value1;
  5012. this._blendFunctionParameters[2] = value2;
  5013. this._blendFunctionParameters[3] = value3;
  5014. this._isBlendFunctionParametersDirty = true;
  5015. };
  5016. _AlphaState.prototype.reset = function () {
  5017. this._alphaBlend = false;
  5018. this._blendFunctionParameters[0] = null;
  5019. this._blendFunctionParameters[1] = null;
  5020. this._blendFunctionParameters[2] = null;
  5021. this._blendFunctionParameters[3] = null;
  5022. this._isAlphaBlendDirty = true;
  5023. this._isBlendFunctionParametersDirty = false;
  5024. };
  5025. _AlphaState.prototype.apply = function (gl) {
  5026. if (!this.isDirty) {
  5027. return;
  5028. }
  5029. // Alpha blend
  5030. if (this._isAlphaBlendDirty) {
  5031. if (this._alphaBlend) {
  5032. gl.enable(gl.BLEND);
  5033. }
  5034. else {
  5035. gl.disable(gl.BLEND);
  5036. }
  5037. this._isAlphaBlendDirty = false;
  5038. }
  5039. // Alpha function
  5040. if (this._isBlendFunctionParametersDirty) {
  5041. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5042. this._isBlendFunctionParametersDirty = false;
  5043. }
  5044. };
  5045. return _AlphaState;
  5046. })();
  5047. BABYLON._AlphaState = _AlphaState;
  5048. var compileShader = function (gl, source, type, defines) {
  5049. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5050. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5051. gl.compileShader(shader);
  5052. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5053. throw new Error(gl.getShaderInfoLog(shader));
  5054. }
  5055. return shader;
  5056. };
  5057. var getWebGLTextureType = function (gl, type) {
  5058. var textureType = gl.UNSIGNED_BYTE;
  5059. if (type === Engine.TEXTURETYPE_FLOAT)
  5060. textureType = gl.FLOAT;
  5061. return textureType;
  5062. };
  5063. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5064. var magFilter = gl.NEAREST;
  5065. var minFilter = gl.NEAREST;
  5066. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5067. magFilter = gl.LINEAR;
  5068. if (generateMipMaps) {
  5069. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5070. }
  5071. else {
  5072. minFilter = gl.LINEAR;
  5073. }
  5074. }
  5075. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5076. magFilter = gl.LINEAR;
  5077. if (generateMipMaps) {
  5078. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5079. }
  5080. else {
  5081. minFilter = gl.LINEAR;
  5082. }
  5083. }
  5084. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5085. magFilter = gl.NEAREST;
  5086. if (generateMipMaps) {
  5087. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5088. }
  5089. else {
  5090. minFilter = gl.NEAREST;
  5091. }
  5092. }
  5093. return {
  5094. min: minFilter,
  5095. mag: magFilter
  5096. };
  5097. };
  5098. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5100. var engine = scene.getEngine();
  5101. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5102. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5103. gl.bindTexture(gl.TEXTURE_2D, texture);
  5104. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5105. texture._baseWidth = width;
  5106. texture._baseHeight = height;
  5107. texture._width = potWidth;
  5108. texture._height = potHeight;
  5109. texture.isReady = true;
  5110. processFunction(potWidth, potHeight);
  5111. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5114. if (!noMipmap && !isCompressed) {
  5115. gl.generateMipmap(gl.TEXTURE_2D);
  5116. }
  5117. gl.bindTexture(gl.TEXTURE_2D, null);
  5118. engine.resetTextureCache();
  5119. scene._removePendingData(texture);
  5120. };
  5121. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5122. var img;
  5123. var onload = function () {
  5124. loadedImages[index] = img;
  5125. loadedImages._internalCount++;
  5126. scene._removePendingData(img);
  5127. if (loadedImages._internalCount === 6) {
  5128. onfinish(loadedImages);
  5129. }
  5130. };
  5131. var onerror = function () {
  5132. scene._removePendingData(img);
  5133. };
  5134. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5135. scene._addPendingData(img);
  5136. };
  5137. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5138. var loadedImages = [];
  5139. loadedImages._internalCount = 0;
  5140. for (var index = 0; index < 6; index++) {
  5141. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5142. }
  5143. };
  5144. var EngineCapabilities = (function () {
  5145. function EngineCapabilities() {
  5146. }
  5147. return EngineCapabilities;
  5148. })();
  5149. BABYLON.EngineCapabilities = EngineCapabilities;
  5150. /**
  5151. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5152. */
  5153. var Engine = (function () {
  5154. /**
  5155. * @constructor
  5156. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5157. * @param {boolean} [antialias] - enable antialias
  5158. * @param options - further options to be sent to the getContext function
  5159. */
  5160. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5161. var _this = this;
  5162. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5163. // Public members
  5164. this.isFullscreen = false;
  5165. this.isPointerLock = false;
  5166. this.cullBackFaces = true;
  5167. this.renderEvenInBackground = true;
  5168. // To enable/disable IDB support and avoid XHR on .manifest
  5169. this.enableOfflineSupport = true;
  5170. this.scenes = new Array();
  5171. this._windowIsBackground = false;
  5172. this._drawCalls = 0;
  5173. this._renderingQueueLaunched = false;
  5174. this._activeRenderLoops = [];
  5175. // FPS
  5176. this.fpsRange = 60;
  5177. this.previousFramesDuration = [];
  5178. this.fps = 60;
  5179. this.deltaTime = 0;
  5180. // States
  5181. this._depthCullingState = new _DepthCullingState();
  5182. this._alphaState = new _AlphaState();
  5183. this._alphaMode = Engine.ALPHA_DISABLE;
  5184. // Cache
  5185. this._loadedTexturesCache = new Array();
  5186. this._maxTextureChannels = 16;
  5187. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5188. this._compiledEffects = {};
  5189. this._uintIndicesCurrentlySet = false;
  5190. this._renderingCanvas = canvas;
  5191. options = options || {};
  5192. options.antialias = antialias;
  5193. if (options.preserveDrawingBuffer === undefined) {
  5194. options.preserveDrawingBuffer = false;
  5195. }
  5196. // GL
  5197. try {
  5198. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5199. }
  5200. catch (e) {
  5201. throw new Error("WebGL not supported");
  5202. }
  5203. if (!this._gl) {
  5204. throw new Error("WebGL not supported");
  5205. }
  5206. this._onBlur = function () {
  5207. _this._windowIsBackground = true;
  5208. };
  5209. this._onFocus = function () {
  5210. _this._windowIsBackground = false;
  5211. };
  5212. window.addEventListener("blur", this._onBlur);
  5213. window.addEventListener("focus", this._onFocus);
  5214. // Viewport
  5215. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5216. this.resize();
  5217. // Caps
  5218. this._caps = new EngineCapabilities();
  5219. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5220. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5221. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5222. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5223. // Infos
  5224. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5225. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5226. if (rendererInfo != null) {
  5227. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5228. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5229. }
  5230. if (!this._glVendor) {
  5231. this._glVendor = "Unknown vendor";
  5232. }
  5233. if (!this._glRenderer) {
  5234. this._glRenderer = "Unknown renderer";
  5235. }
  5236. // Extensions
  5237. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5238. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5239. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5240. 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');
  5241. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5242. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5243. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5244. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5245. this._caps.highPrecisionShaderSupported = true;
  5246. if (this._gl.getShaderPrecisionFormat) {
  5247. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5248. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5249. }
  5250. // Depth buffer
  5251. this.setDepthBuffer(true);
  5252. this.setDepthFunctionToLessOrEqual();
  5253. this.setDepthWrite(true);
  5254. // Fullscreen
  5255. this._onFullscreenChange = function () {
  5256. if (document.fullscreen !== undefined) {
  5257. _this.isFullscreen = document.fullscreen;
  5258. }
  5259. else if (document.mozFullScreen !== undefined) {
  5260. _this.isFullscreen = document.mozFullScreen;
  5261. }
  5262. else if (document.webkitIsFullScreen !== undefined) {
  5263. _this.isFullscreen = document.webkitIsFullScreen;
  5264. }
  5265. else if (document.msIsFullScreen !== undefined) {
  5266. _this.isFullscreen = document.msIsFullScreen;
  5267. }
  5268. // Pointer lock
  5269. if (_this.isFullscreen && _this._pointerLockRequested) {
  5270. canvas.requestPointerLock = canvas.requestPointerLock ||
  5271. canvas.msRequestPointerLock ||
  5272. canvas.mozRequestPointerLock ||
  5273. canvas.webkitRequestPointerLock;
  5274. if (canvas.requestPointerLock) {
  5275. canvas.requestPointerLock();
  5276. }
  5277. }
  5278. };
  5279. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5280. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5281. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5282. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5283. // Pointer lock
  5284. this._onPointerLockChange = function () {
  5285. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5286. document.webkitPointerLockElement === canvas ||
  5287. document.msPointerLockElement === canvas ||
  5288. document.pointerLockElement === canvas);
  5289. };
  5290. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5291. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5292. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5293. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5294. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5295. Engine.audioEngine = new BABYLON.AudioEngine();
  5296. }
  5297. //default loading screen
  5298. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5299. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5300. }
  5301. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5302. get: function () {
  5303. return Engine._ALPHA_DISABLE;
  5304. },
  5305. enumerable: true,
  5306. configurable: true
  5307. });
  5308. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5309. get: function () {
  5310. return Engine._ALPHA_ONEONE;
  5311. },
  5312. enumerable: true,
  5313. configurable: true
  5314. });
  5315. Object.defineProperty(Engine, "ALPHA_ADD", {
  5316. get: function () {
  5317. return Engine._ALPHA_ADD;
  5318. },
  5319. enumerable: true,
  5320. configurable: true
  5321. });
  5322. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5323. get: function () {
  5324. return Engine._ALPHA_COMBINE;
  5325. },
  5326. enumerable: true,
  5327. configurable: true
  5328. });
  5329. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5330. get: function () {
  5331. return Engine._ALPHA_SUBTRACT;
  5332. },
  5333. enumerable: true,
  5334. configurable: true
  5335. });
  5336. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5337. get: function () {
  5338. return Engine._ALPHA_MULTIPLY;
  5339. },
  5340. enumerable: true,
  5341. configurable: true
  5342. });
  5343. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5344. get: function () {
  5345. return Engine._ALPHA_MAXIMIZED;
  5346. },
  5347. enumerable: true,
  5348. configurable: true
  5349. });
  5350. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5351. get: function () {
  5352. return Engine._DELAYLOADSTATE_NONE;
  5353. },
  5354. enumerable: true,
  5355. configurable: true
  5356. });
  5357. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5358. get: function () {
  5359. return Engine._DELAYLOADSTATE_LOADED;
  5360. },
  5361. enumerable: true,
  5362. configurable: true
  5363. });
  5364. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5365. get: function () {
  5366. return Engine._DELAYLOADSTATE_LOADING;
  5367. },
  5368. enumerable: true,
  5369. configurable: true
  5370. });
  5371. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5372. get: function () {
  5373. return Engine._DELAYLOADSTATE_NOTLOADED;
  5374. },
  5375. enumerable: true,
  5376. configurable: true
  5377. });
  5378. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5379. get: function () {
  5380. return Engine._TEXTUREFORMAT_ALPHA;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5386. get: function () {
  5387. return Engine._TEXTUREFORMAT_LUMINANCE;
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5393. get: function () {
  5394. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5400. get: function () {
  5401. return Engine._TEXTUREFORMAT_RGB;
  5402. },
  5403. enumerable: true,
  5404. configurable: true
  5405. });
  5406. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5407. get: function () {
  5408. return Engine._TEXTUREFORMAT_RGBA;
  5409. },
  5410. enumerable: true,
  5411. configurable: true
  5412. });
  5413. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5414. get: function () {
  5415. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5416. },
  5417. enumerable: true,
  5418. configurable: true
  5419. });
  5420. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5421. get: function () {
  5422. return Engine._TEXTURETYPE_FLOAT;
  5423. },
  5424. enumerable: true,
  5425. configurable: true
  5426. });
  5427. Object.defineProperty(Engine, "Version", {
  5428. get: function () {
  5429. return "2.3.0-beta";
  5430. },
  5431. enumerable: true,
  5432. configurable: true
  5433. });
  5434. Engine.prototype._prepareWorkingCanvas = function () {
  5435. if (this._workingCanvas) {
  5436. return;
  5437. }
  5438. this._workingCanvas = document.createElement("canvas");
  5439. this._workingContext = this._workingCanvas.getContext("2d");
  5440. };
  5441. Engine.prototype.resetTextureCache = function () {
  5442. for (var index = 0; index < this._maxTextureChannels; index++) {
  5443. this._activeTexturesCache[index] = null;
  5444. }
  5445. };
  5446. Engine.prototype.getGlInfo = function () {
  5447. return {
  5448. vendor: this._glVendor,
  5449. renderer: this._glRenderer,
  5450. version: this._glVersion
  5451. };
  5452. };
  5453. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5454. if (useScreen === void 0) { useScreen = false; }
  5455. var viewport = camera.viewport;
  5456. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5457. };
  5458. Engine.prototype.getRenderWidth = function (useScreen) {
  5459. if (useScreen === void 0) { useScreen = false; }
  5460. if (!useScreen && this._currentRenderTarget) {
  5461. return this._currentRenderTarget._width;
  5462. }
  5463. return this._renderingCanvas.width;
  5464. };
  5465. Engine.prototype.getRenderHeight = function (useScreen) {
  5466. if (useScreen === void 0) { useScreen = false; }
  5467. if (!useScreen && this._currentRenderTarget) {
  5468. return this._currentRenderTarget._height;
  5469. }
  5470. return this._renderingCanvas.height;
  5471. };
  5472. Engine.prototype.getRenderingCanvas = function () {
  5473. return this._renderingCanvas;
  5474. };
  5475. Engine.prototype.getRenderingCanvasClientRect = function () {
  5476. return this._renderingCanvas.getBoundingClientRect();
  5477. };
  5478. Engine.prototype.setHardwareScalingLevel = function (level) {
  5479. this._hardwareScalingLevel = level;
  5480. this.resize();
  5481. };
  5482. Engine.prototype.getHardwareScalingLevel = function () {
  5483. return this._hardwareScalingLevel;
  5484. };
  5485. Engine.prototype.getLoadedTexturesCache = function () {
  5486. return this._loadedTexturesCache;
  5487. };
  5488. Engine.prototype.getCaps = function () {
  5489. return this._caps;
  5490. };
  5491. Object.defineProperty(Engine.prototype, "drawCalls", {
  5492. get: function () {
  5493. return this._drawCalls;
  5494. },
  5495. enumerable: true,
  5496. configurable: true
  5497. });
  5498. // Methods
  5499. Engine.prototype.resetDrawCalls = function () {
  5500. this._drawCalls = 0;
  5501. };
  5502. Engine.prototype.setDepthFunctionToGreater = function () {
  5503. this._depthCullingState.depthFunc = this._gl.GREATER;
  5504. };
  5505. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5506. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5507. };
  5508. Engine.prototype.setDepthFunctionToLess = function () {
  5509. this._depthCullingState.depthFunc = this._gl.LESS;
  5510. };
  5511. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5512. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5513. };
  5514. /**
  5515. * stop executing a render loop function and remove it from the execution array
  5516. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5517. */
  5518. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5519. if (!renderFunction) {
  5520. this._activeRenderLoops = [];
  5521. return;
  5522. }
  5523. var index = this._activeRenderLoops.indexOf(renderFunction);
  5524. if (index >= 0) {
  5525. this._activeRenderLoops.splice(index, 1);
  5526. }
  5527. };
  5528. Engine.prototype._renderLoop = function () {
  5529. var shouldRender = true;
  5530. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5531. shouldRender = false;
  5532. }
  5533. if (shouldRender) {
  5534. // Start new frame
  5535. this.beginFrame();
  5536. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5537. var renderFunction = this._activeRenderLoops[index];
  5538. renderFunction();
  5539. }
  5540. // Present
  5541. this.endFrame();
  5542. }
  5543. if (this._activeRenderLoops.length > 0) {
  5544. // Register new frame
  5545. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5546. }
  5547. else {
  5548. this._renderingQueueLaunched = false;
  5549. }
  5550. };
  5551. /**
  5552. * Register and execute a render loop. The engine can have more than one render function.
  5553. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5554. * @example
  5555. * engine.runRenderLoop(function () {
  5556. * scene.render()
  5557. * })
  5558. */
  5559. Engine.prototype.runRenderLoop = function (renderFunction) {
  5560. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5561. return;
  5562. }
  5563. this._activeRenderLoops.push(renderFunction);
  5564. if (!this._renderingQueueLaunched) {
  5565. this._renderingQueueLaunched = true;
  5566. this._bindedRenderFunction = this._renderLoop.bind(this);
  5567. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5568. }
  5569. };
  5570. /**
  5571. * Toggle full screen mode.
  5572. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5573. */
  5574. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5575. if (this.isFullscreen) {
  5576. BABYLON.Tools.ExitFullscreen();
  5577. }
  5578. else {
  5579. this._pointerLockRequested = requestPointerLock;
  5580. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5581. }
  5582. };
  5583. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5584. this.applyStates();
  5585. if (backBuffer) {
  5586. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5587. }
  5588. if (depthStencil && this._depthCullingState.depthMask) {
  5589. this._gl.clearDepth(1.0);
  5590. }
  5591. var mode = 0;
  5592. if (backBuffer) {
  5593. mode |= this._gl.COLOR_BUFFER_BIT;
  5594. }
  5595. if (depthStencil && this._depthCullingState.depthMask) {
  5596. mode |= this._gl.DEPTH_BUFFER_BIT;
  5597. }
  5598. this._gl.clear(mode);
  5599. };
  5600. /**
  5601. * Set the WebGL's viewport
  5602. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5603. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5604. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5605. */
  5606. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5607. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5608. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5609. var x = viewport.x || 0;
  5610. var y = viewport.y || 0;
  5611. this._cachedViewport = viewport;
  5612. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5613. };
  5614. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5615. this._cachedViewport = null;
  5616. this._gl.viewport(x, y, width, height);
  5617. };
  5618. Engine.prototype.beginFrame = function () {
  5619. this._measureFps();
  5620. };
  5621. Engine.prototype.endFrame = function () {
  5622. //this.flushFramebuffer();
  5623. };
  5624. /**
  5625. * resize the view according to the canvas' size.
  5626. * @example
  5627. * window.addEventListener("resize", function () {
  5628. * engine.resize();
  5629. * });
  5630. */
  5631. Engine.prototype.resize = function () {
  5632. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5633. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5634. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5635. for (var index = 0; index < this.scenes.length; index++) {
  5636. var scene = this.scenes[index];
  5637. if (scene.debugLayer.isVisible()) {
  5638. scene.debugLayer._syncPositions();
  5639. }
  5640. }
  5641. };
  5642. /**
  5643. * force a specific size of the canvas
  5644. * @param {number} width - the new canvas' width
  5645. * @param {number} height - the new canvas' height
  5646. */
  5647. Engine.prototype.setSize = function (width, height) {
  5648. this._renderingCanvas.width = width;
  5649. this._renderingCanvas.height = height;
  5650. for (var index = 0; index < this.scenes.length; index++) {
  5651. var scene = this.scenes[index];
  5652. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5653. var cam = scene.cameras[camIndex];
  5654. cam._currentRenderId = 0;
  5655. }
  5656. }
  5657. };
  5658. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5659. this._currentRenderTarget = texture;
  5660. var gl = this._gl;
  5661. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5662. if (texture.isCube) {
  5663. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5664. }
  5665. else {
  5666. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5667. }
  5668. this._gl.viewport(0, 0, texture._width, texture._height);
  5669. this.wipeCaches();
  5670. };
  5671. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5672. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5673. this._currentRenderTarget = null;
  5674. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5675. var gl = this._gl;
  5676. gl.bindTexture(gl.TEXTURE_2D, texture);
  5677. gl.generateMipmap(gl.TEXTURE_2D);
  5678. gl.bindTexture(gl.TEXTURE_2D, null);
  5679. }
  5680. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5681. };
  5682. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5683. if (texture.generateMipMaps) {
  5684. var gl = this._gl;
  5685. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5686. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5687. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5688. }
  5689. };
  5690. Engine.prototype.flushFramebuffer = function () {
  5691. this._gl.flush();
  5692. };
  5693. Engine.prototype.restoreDefaultFramebuffer = function () {
  5694. this._currentRenderTarget = null;
  5695. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5696. this.setViewport(this._cachedViewport);
  5697. this.wipeCaches();
  5698. };
  5699. // VBOs
  5700. Engine.prototype._resetVertexBufferBinding = function () {
  5701. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5702. this._cachedVertexBuffers = null;
  5703. };
  5704. Engine.prototype.createVertexBuffer = function (vertices) {
  5705. var vbo = this._gl.createBuffer();
  5706. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5707. if (vertices instanceof Float32Array) {
  5708. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5709. }
  5710. else {
  5711. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5712. }
  5713. this._resetVertexBufferBinding();
  5714. vbo.references = 1;
  5715. return vbo;
  5716. };
  5717. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5718. var vbo = this._gl.createBuffer();
  5719. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5720. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5721. this._resetVertexBufferBinding();
  5722. vbo.references = 1;
  5723. return vbo;
  5724. };
  5725. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5726. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5727. if (offset === undefined) {
  5728. offset = 0;
  5729. }
  5730. if (vertices instanceof Float32Array) {
  5731. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5732. }
  5733. else {
  5734. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5735. }
  5736. this._resetVertexBufferBinding();
  5737. };
  5738. Engine.prototype._resetIndexBufferBinding = function () {
  5739. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5740. this._cachedIndexBuffer = null;
  5741. };
  5742. Engine.prototype.createIndexBuffer = function (indices) {
  5743. var vbo = this._gl.createBuffer();
  5744. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5745. // Check for 32 bits indices
  5746. var arrayBuffer;
  5747. var need32Bits = false;
  5748. if (this._caps.uintIndices) {
  5749. for (var index = 0; index < indices.length; index++) {
  5750. if (indices[index] > 65535) {
  5751. need32Bits = true;
  5752. break;
  5753. }
  5754. }
  5755. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5756. }
  5757. else {
  5758. arrayBuffer = new Uint16Array(indices);
  5759. }
  5760. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5761. this._resetIndexBufferBinding();
  5762. vbo.references = 1;
  5763. vbo.is32Bits = need32Bits;
  5764. return vbo;
  5765. };
  5766. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5767. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5768. this._cachedVertexBuffers = vertexBuffer;
  5769. this._cachedEffectForVertexBuffers = effect;
  5770. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5771. var offset = 0;
  5772. for (var index = 0; index < vertexDeclaration.length; index++) {
  5773. var order = effect.getAttributeLocation(index);
  5774. if (order >= 0) {
  5775. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5776. }
  5777. offset += vertexDeclaration[index] * 4;
  5778. }
  5779. }
  5780. if (this._cachedIndexBuffer !== indexBuffer) {
  5781. this._cachedIndexBuffer = indexBuffer;
  5782. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5783. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5784. }
  5785. };
  5786. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5787. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5788. this._cachedVertexBuffers = vertexBuffers;
  5789. this._cachedEffectForVertexBuffers = effect;
  5790. var attributes = effect.getAttributesNames();
  5791. for (var index = 0; index < attributes.length; index++) {
  5792. var order = effect.getAttributeLocation(index);
  5793. if (order >= 0) {
  5794. var vertexBuffer = vertexBuffers[attributes[index]];
  5795. if (!vertexBuffer) {
  5796. continue;
  5797. }
  5798. var stride = vertexBuffer.getStrideSize();
  5799. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5800. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5801. }
  5802. }
  5803. }
  5804. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5805. this._cachedIndexBuffer = indexBuffer;
  5806. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5807. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5808. }
  5809. };
  5810. Engine.prototype._releaseBuffer = function (buffer) {
  5811. buffer.references--;
  5812. if (buffer.references === 0) {
  5813. this._gl.deleteBuffer(buffer);
  5814. return true;
  5815. }
  5816. return false;
  5817. };
  5818. Engine.prototype.createInstancesBuffer = function (capacity) {
  5819. var buffer = this._gl.createBuffer();
  5820. buffer.capacity = capacity;
  5821. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5822. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5823. return buffer;
  5824. };
  5825. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5826. this._gl.deleteBuffer(buffer);
  5827. };
  5828. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5830. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5831. for (var index = 0; index < 4; index++) {
  5832. var offsetLocation = offsetLocations[index];
  5833. this._gl.enableVertexAttribArray(offsetLocation);
  5834. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5835. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5836. }
  5837. };
  5838. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5839. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5840. for (var index = 0; index < 4; index++) {
  5841. var offsetLocation = offsetLocations[index];
  5842. this._gl.disableVertexAttribArray(offsetLocation);
  5843. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5844. }
  5845. };
  5846. Engine.prototype.applyStates = function () {
  5847. this._depthCullingState.apply(this._gl);
  5848. this._alphaState.apply(this._gl);
  5849. };
  5850. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5851. // Apply states
  5852. this.applyStates();
  5853. this._drawCalls++;
  5854. // Render
  5855. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5856. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5857. if (instancesCount) {
  5858. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5859. return;
  5860. }
  5861. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5862. };
  5863. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5864. // Apply states
  5865. this.applyStates();
  5866. this._drawCalls++;
  5867. if (instancesCount) {
  5868. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5869. return;
  5870. }
  5871. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5872. };
  5873. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5874. // Apply states
  5875. this.applyStates();
  5876. this._drawCalls++;
  5877. if (instancesCount) {
  5878. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5879. return;
  5880. }
  5881. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5882. };
  5883. // Shaders
  5884. Engine.prototype._releaseEffect = function (effect) {
  5885. if (this._compiledEffects[effect._key]) {
  5886. delete this._compiledEffects[effect._key];
  5887. if (effect.getProgram()) {
  5888. this._gl.deleteProgram(effect.getProgram());
  5889. }
  5890. }
  5891. };
  5892. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5893. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5894. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5895. var name = vertex + "+" + fragment + "@" + defines;
  5896. if (this._compiledEffects[name]) {
  5897. return this._compiledEffects[name];
  5898. }
  5899. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5900. effect._key = name;
  5901. this._compiledEffects[name] = effect;
  5902. return effect;
  5903. };
  5904. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5905. if (uniformsNames === void 0) { uniformsNames = []; }
  5906. if (samplers === void 0) { samplers = []; }
  5907. if (defines === void 0) { defines = ""; }
  5908. return this.createEffect({
  5909. vertex: "particles",
  5910. fragmentElement: fragmentName
  5911. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5912. };
  5913. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5914. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5915. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5916. var shaderProgram = this._gl.createProgram();
  5917. this._gl.attachShader(shaderProgram, vertexShader);
  5918. this._gl.attachShader(shaderProgram, fragmentShader);
  5919. this._gl.linkProgram(shaderProgram);
  5920. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5921. if (!linked) {
  5922. var error = this._gl.getProgramInfoLog(shaderProgram);
  5923. if (error) {
  5924. throw new Error(error);
  5925. }
  5926. }
  5927. this._gl.deleteShader(vertexShader);
  5928. this._gl.deleteShader(fragmentShader);
  5929. return shaderProgram;
  5930. };
  5931. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5932. var results = [];
  5933. for (var index = 0; index < uniformsNames.length; index++) {
  5934. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5935. }
  5936. return results;
  5937. };
  5938. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5939. var results = [];
  5940. for (var index = 0; index < attributesNames.length; index++) {
  5941. try {
  5942. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5943. }
  5944. catch (e) {
  5945. results.push(-1);
  5946. }
  5947. }
  5948. return results;
  5949. };
  5950. Engine.prototype.enableEffect = function (effect) {
  5951. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5952. if (effect && effect.onBind) {
  5953. effect.onBind(effect);
  5954. }
  5955. return;
  5956. }
  5957. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5958. // Use program
  5959. this._gl.useProgram(effect.getProgram());
  5960. for (var i in this._vertexAttribArrays) {
  5961. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5962. continue;
  5963. }
  5964. this._vertexAttribArrays[i] = false;
  5965. this._gl.disableVertexAttribArray(i);
  5966. }
  5967. var attributesCount = effect.getAttributesCount();
  5968. for (var index = 0; index < attributesCount; index++) {
  5969. // Attributes
  5970. var order = effect.getAttributeLocation(index);
  5971. if (order >= 0) {
  5972. this._vertexAttribArrays[order] = true;
  5973. this._gl.enableVertexAttribArray(order);
  5974. }
  5975. }
  5976. this._currentEffect = effect;
  5977. if (effect.onBind) {
  5978. effect.onBind(effect);
  5979. }
  5980. };
  5981. Engine.prototype.setArray = function (uniform, array) {
  5982. if (!uniform)
  5983. return;
  5984. this._gl.uniform1fv(uniform, array);
  5985. };
  5986. Engine.prototype.setArray2 = function (uniform, array) {
  5987. if (!uniform || array.length % 2 !== 0)
  5988. return;
  5989. this._gl.uniform2fv(uniform, array);
  5990. };
  5991. Engine.prototype.setArray3 = function (uniform, array) {
  5992. if (!uniform || array.length % 3 !== 0)
  5993. return;
  5994. this._gl.uniform3fv(uniform, array);
  5995. };
  5996. Engine.prototype.setArray4 = function (uniform, array) {
  5997. if (!uniform || array.length % 4 !== 0)
  5998. return;
  5999. this._gl.uniform4fv(uniform, array);
  6000. };
  6001. Engine.prototype.setMatrices = function (uniform, matrices) {
  6002. if (!uniform)
  6003. return;
  6004. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6005. };
  6006. Engine.prototype.setMatrix = function (uniform, matrix) {
  6007. if (!uniform)
  6008. return;
  6009. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6010. };
  6011. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6012. if (!uniform)
  6013. return;
  6014. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6015. };
  6016. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6017. if (!uniform)
  6018. return;
  6019. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6020. };
  6021. Engine.prototype.setFloat = function (uniform, value) {
  6022. if (!uniform)
  6023. return;
  6024. this._gl.uniform1f(uniform, value);
  6025. };
  6026. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6027. if (!uniform)
  6028. return;
  6029. this._gl.uniform2f(uniform, x, y);
  6030. };
  6031. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6032. if (!uniform)
  6033. return;
  6034. this._gl.uniform3f(uniform, x, y, z);
  6035. };
  6036. Engine.prototype.setBool = function (uniform, bool) {
  6037. if (!uniform)
  6038. return;
  6039. this._gl.uniform1i(uniform, bool);
  6040. };
  6041. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6042. if (!uniform)
  6043. return;
  6044. this._gl.uniform4f(uniform, x, y, z, w);
  6045. };
  6046. Engine.prototype.setColor3 = function (uniform, color3) {
  6047. if (!uniform)
  6048. return;
  6049. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6050. };
  6051. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6052. if (!uniform)
  6053. return;
  6054. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6055. };
  6056. // States
  6057. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6058. if (zOffset === void 0) { zOffset = 0; }
  6059. if (reverseSide === void 0) { reverseSide = false; }
  6060. // Culling
  6061. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6062. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6063. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6064. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6065. if (culling) {
  6066. this._depthCullingState.cullFace = cullFace;
  6067. this._depthCullingState.cull = true;
  6068. }
  6069. else {
  6070. this._depthCullingState.cull = false;
  6071. }
  6072. }
  6073. // Z offset
  6074. this._depthCullingState.zOffset = zOffset;
  6075. };
  6076. Engine.prototype.setDepthBuffer = function (enable) {
  6077. this._depthCullingState.depthTest = enable;
  6078. };
  6079. Engine.prototype.getDepthWrite = function () {
  6080. return this._depthCullingState.depthMask;
  6081. };
  6082. Engine.prototype.setDepthWrite = function (enable) {
  6083. this._depthCullingState.depthMask = enable;
  6084. };
  6085. Engine.prototype.setColorWrite = function (enable) {
  6086. this._gl.colorMask(enable, enable, enable, enable);
  6087. };
  6088. Engine.prototype.setAlphaMode = function (mode) {
  6089. if (this._alphaMode === mode) {
  6090. return;
  6091. }
  6092. switch (mode) {
  6093. case Engine.ALPHA_DISABLE:
  6094. this.setDepthWrite(true);
  6095. this._alphaState.alphaBlend = false;
  6096. break;
  6097. case Engine.ALPHA_COMBINE:
  6098. this.setDepthWrite(false);
  6099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6100. this._alphaState.alphaBlend = true;
  6101. break;
  6102. case Engine.ALPHA_ONEONE:
  6103. this.setDepthWrite(false);
  6104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6105. this._alphaState.alphaBlend = true;
  6106. break;
  6107. case Engine.ALPHA_ADD:
  6108. this.setDepthWrite(false);
  6109. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6110. this._alphaState.alphaBlend = true;
  6111. break;
  6112. case Engine.ALPHA_SUBTRACT:
  6113. this.setDepthWrite(false);
  6114. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6115. this._alphaState.alphaBlend = true;
  6116. break;
  6117. case Engine.ALPHA_MULTIPLY:
  6118. this.setDepthWrite(false);
  6119. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6120. this._alphaState.alphaBlend = true;
  6121. break;
  6122. case Engine.ALPHA_MAXIMIZED:
  6123. this.setDepthWrite(false);
  6124. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6125. this._alphaState.alphaBlend = true;
  6126. break;
  6127. }
  6128. this._alphaMode = mode;
  6129. };
  6130. Engine.prototype.getAlphaMode = function () {
  6131. return this._alphaMode;
  6132. };
  6133. Engine.prototype.setAlphaTesting = function (enable) {
  6134. this._alphaTest = enable;
  6135. };
  6136. Engine.prototype.getAlphaTesting = function () {
  6137. return this._alphaTest;
  6138. };
  6139. // Textures
  6140. Engine.prototype.wipeCaches = function () {
  6141. this.resetTextureCache();
  6142. this._currentEffect = null;
  6143. this._depthCullingState.reset();
  6144. this._alphaState.reset();
  6145. this._cachedVertexBuffers = null;
  6146. this._cachedIndexBuffer = null;
  6147. this._cachedEffectForVertexBuffers = null;
  6148. };
  6149. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6150. var gl = this._gl;
  6151. gl.bindTexture(gl.TEXTURE_2D, texture);
  6152. var magFilter = gl.NEAREST;
  6153. var minFilter = gl.NEAREST;
  6154. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6155. magFilter = gl.LINEAR;
  6156. minFilter = gl.LINEAR;
  6157. }
  6158. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6159. magFilter = gl.LINEAR;
  6160. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6161. }
  6162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6164. gl.bindTexture(gl.TEXTURE_2D, null);
  6165. texture.samplingMode = samplingMode;
  6166. };
  6167. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6168. var _this = this;
  6169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6170. if (onLoad === void 0) { onLoad = null; }
  6171. if (onError === void 0) { onError = null; }
  6172. if (buffer === void 0) { buffer = null; }
  6173. var texture = this._gl.createTexture();
  6174. var extension;
  6175. var fromData = false;
  6176. if (url.substr(0, 5) === "data:") {
  6177. fromData = true;
  6178. }
  6179. if (!fromData)
  6180. extension = url.substr(url.length - 4, 4).toLowerCase();
  6181. else {
  6182. var oldUrl = url;
  6183. fromData = oldUrl.split(':');
  6184. url = oldUrl;
  6185. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6186. }
  6187. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6188. var isTGA = (extension === ".tga");
  6189. scene._addPendingData(texture);
  6190. texture.url = url;
  6191. texture.noMipmap = noMipmap;
  6192. texture.references = 1;
  6193. texture.samplingMode = samplingMode;
  6194. this._loadedTexturesCache.push(texture);
  6195. var onerror = function () {
  6196. scene._removePendingData(texture);
  6197. if (onError) {
  6198. onError();
  6199. }
  6200. };
  6201. var callback;
  6202. if (isTGA) {
  6203. callback = function (arrayBuffer) {
  6204. var data = new Uint8Array(arrayBuffer);
  6205. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6206. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6207. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6208. if (onLoad) {
  6209. onLoad();
  6210. }
  6211. }, samplingMode);
  6212. };
  6213. if (!(fromData instanceof Array))
  6214. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6215. callback(arrayBuffer);
  6216. }, onerror, scene.database, true);
  6217. else
  6218. callback(buffer);
  6219. }
  6220. else if (isDDS) {
  6221. callback = function (data) {
  6222. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6223. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6224. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6225. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6226. if (onLoad) {
  6227. onLoad();
  6228. }
  6229. }, samplingMode);
  6230. };
  6231. if (!(fromData instanceof Array))
  6232. BABYLON.Tools.LoadFile(url, function (data) {
  6233. callback(data);
  6234. }, onerror, scene.database, true);
  6235. else
  6236. callback(buffer);
  6237. }
  6238. else {
  6239. var onload = function (img) {
  6240. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6241. var isPot = (img.width === potWidth && img.height === potHeight);
  6242. if (!isPot) {
  6243. _this._prepareWorkingCanvas();
  6244. _this._workingCanvas.width = potWidth;
  6245. _this._workingCanvas.height = potHeight;
  6246. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6247. _this._workingContext.imageSmoothingEnabled = false;
  6248. _this._workingContext.mozImageSmoothingEnabled = false;
  6249. _this._workingContext.oImageSmoothingEnabled = false;
  6250. _this._workingContext.webkitImageSmoothingEnabled = false;
  6251. _this._workingContext.msImageSmoothingEnabled = false;
  6252. }
  6253. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6254. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6255. _this._workingContext.imageSmoothingEnabled = true;
  6256. _this._workingContext.mozImageSmoothingEnabled = true;
  6257. _this._workingContext.oImageSmoothingEnabled = true;
  6258. _this._workingContext.webkitImageSmoothingEnabled = true;
  6259. _this._workingContext.msImageSmoothingEnabled = true;
  6260. }
  6261. }
  6262. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6263. if (onLoad) {
  6264. onLoad();
  6265. }
  6266. }, samplingMode);
  6267. };
  6268. if (!(fromData instanceof Array))
  6269. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6270. else
  6271. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6272. }
  6273. return texture;
  6274. };
  6275. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6276. if (compression === void 0) { compression = null; }
  6277. var internalFormat = this._gl.RGBA;
  6278. switch (format) {
  6279. case Engine.TEXTUREFORMAT_ALPHA:
  6280. internalFormat = this._gl.ALPHA;
  6281. break;
  6282. case Engine.TEXTUREFORMAT_LUMINANCE:
  6283. internalFormat = this._gl.LUMINANCE;
  6284. break;
  6285. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6286. internalFormat = this._gl.LUMINANCE_ALPHA;
  6287. break;
  6288. case Engine.TEXTUREFORMAT_RGB:
  6289. internalFormat = this._gl.RGB;
  6290. break;
  6291. case Engine.TEXTUREFORMAT_RGBA:
  6292. internalFormat = this._gl.RGBA;
  6293. break;
  6294. }
  6295. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6296. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6297. if (compression) {
  6298. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6299. }
  6300. else {
  6301. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6302. }
  6303. if (texture.generateMipMaps) {
  6304. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6305. }
  6306. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6307. this.resetTextureCache();
  6308. texture.isReady = true;
  6309. };
  6310. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6311. if (compression === void 0) { compression = null; }
  6312. var texture = this._gl.createTexture();
  6313. texture._baseWidth = width;
  6314. texture._baseHeight = height;
  6315. texture._width = width;
  6316. texture._height = height;
  6317. texture.references = 1;
  6318. this.updateRawTexture(texture, data, format, invertY, compression);
  6319. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6320. // Filters
  6321. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6322. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6324. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6325. texture.samplingMode = samplingMode;
  6326. this._loadedTexturesCache.push(texture);
  6327. return texture;
  6328. };
  6329. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6330. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6331. var texture = this._gl.createTexture();
  6332. texture._baseWidth = width;
  6333. texture._baseHeight = height;
  6334. if (forceExponantOfTwo) {
  6335. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6336. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6337. }
  6338. this.resetTextureCache();
  6339. texture._width = width;
  6340. texture._height = height;
  6341. texture.isReady = false;
  6342. texture.generateMipMaps = generateMipMaps;
  6343. texture.references = 1;
  6344. texture.samplingMode = samplingMode;
  6345. this.updateTextureSamplingMode(samplingMode, texture);
  6346. this._loadedTexturesCache.push(texture);
  6347. return texture;
  6348. };
  6349. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6350. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6351. if (texture.isCube) {
  6352. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6353. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6354. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6355. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6356. }
  6357. else {
  6358. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6359. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6360. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6361. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6362. }
  6363. };
  6364. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6365. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6366. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6368. if (texture.generateMipMaps) {
  6369. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6370. }
  6371. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6372. this.resetTextureCache();
  6373. texture.isReady = true;
  6374. };
  6375. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6376. if (texture._isDisabled) {
  6377. return;
  6378. }
  6379. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6380. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6381. try {
  6382. // Testing video texture support
  6383. if (this._videoTextureSupported === undefined) {
  6384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6385. if (this._gl.getError() !== 0) {
  6386. this._videoTextureSupported = false;
  6387. }
  6388. else {
  6389. this._videoTextureSupported = true;
  6390. }
  6391. }
  6392. // Copy video through the current working canvas if video texture is not supported
  6393. if (!this._videoTextureSupported) {
  6394. if (!texture._workingCanvas) {
  6395. texture._workingCanvas = document.createElement("canvas");
  6396. texture._workingContext = texture._workingCanvas.getContext("2d");
  6397. texture._workingCanvas.width = texture._width;
  6398. texture._workingCanvas.height = texture._height;
  6399. }
  6400. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6401. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6402. }
  6403. else {
  6404. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6405. }
  6406. if (texture.generateMipMaps) {
  6407. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6408. }
  6409. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6410. this.resetTextureCache();
  6411. texture.isReady = true;
  6412. }
  6413. catch (ex) {
  6414. // Something unexpected
  6415. // Let's disable the texture
  6416. texture._isDisabled = true;
  6417. }
  6418. };
  6419. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6420. // old version had a "generateMipMaps" arg instead of options.
  6421. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6422. // in the same way, generateDepthBuffer is defaulted to true
  6423. var generateMipMaps = false;
  6424. var generateDepthBuffer = true;
  6425. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6426. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6427. if (options !== undefined) {
  6428. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6429. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6430. type = options.type === undefined ? type : options.type;
  6431. if (options.samplingMode !== undefined) {
  6432. samplingMode = options.samplingMode;
  6433. }
  6434. if (type === Engine.TEXTURETYPE_FLOAT) {
  6435. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6436. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6437. }
  6438. }
  6439. var gl = this._gl;
  6440. var texture = gl.createTexture();
  6441. gl.bindTexture(gl.TEXTURE_2D, texture);
  6442. var width = size.width || size;
  6443. var height = size.height || size;
  6444. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6445. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6446. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6447. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6448. }
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6453. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6454. var depthBuffer;
  6455. // Create the depth buffer
  6456. if (generateDepthBuffer) {
  6457. depthBuffer = gl.createRenderbuffer();
  6458. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6459. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6460. }
  6461. // Create the framebuffer
  6462. var framebuffer = gl.createFramebuffer();
  6463. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6464. if (generateDepthBuffer) {
  6465. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6466. }
  6467. if (generateMipMaps) {
  6468. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6469. }
  6470. // Unbind
  6471. gl.bindTexture(gl.TEXTURE_2D, null);
  6472. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6473. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6474. texture._framebuffer = framebuffer;
  6475. if (generateDepthBuffer) {
  6476. texture._depthBuffer = depthBuffer;
  6477. }
  6478. texture._width = width;
  6479. texture._height = height;
  6480. texture.isReady = true;
  6481. texture.generateMipMaps = generateMipMaps;
  6482. texture.references = 1;
  6483. texture.samplingMode = samplingMode;
  6484. this.resetTextureCache();
  6485. this._loadedTexturesCache.push(texture);
  6486. return texture;
  6487. };
  6488. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6489. var gl = this._gl;
  6490. var texture = gl.createTexture();
  6491. var generateMipMaps = true;
  6492. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6493. if (options !== undefined) {
  6494. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6495. if (options.samplingMode !== undefined) {
  6496. samplingMode = options.samplingMode;
  6497. }
  6498. }
  6499. texture.isCube = true;
  6500. texture.references = 1;
  6501. texture.generateMipMaps = generateMipMaps;
  6502. texture.references = 1;
  6503. texture.samplingMode = samplingMode;
  6504. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6505. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6506. for (var face = 0; face < 6; face++) {
  6507. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6508. }
  6509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6513. // Create the depth buffer
  6514. var depthBuffer = gl.createRenderbuffer();
  6515. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6516. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6517. // Create the framebuffer
  6518. var framebuffer = gl.createFramebuffer();
  6519. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6520. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6521. // mipmaps
  6522. if (texture.generateMipMaps) {
  6523. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6524. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6525. }
  6526. // Unbind
  6527. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6528. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6529. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6530. texture._framebuffer = framebuffer;
  6531. texture._depthBuffer = depthBuffer;
  6532. this.resetTextureCache();
  6533. texture._width = size;
  6534. texture._height = size;
  6535. texture.isReady = true;
  6536. return texture;
  6537. };
  6538. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6539. var _this = this;
  6540. var gl = this._gl;
  6541. var texture = gl.createTexture();
  6542. texture.isCube = true;
  6543. texture.url = rootUrl;
  6544. texture.references = 1;
  6545. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6546. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6547. if (isDDS) {
  6548. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6549. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6550. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6551. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6552. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6553. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6554. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6555. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6556. }
  6557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6561. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6562. _this.resetTextureCache();
  6563. texture._width = info.width;
  6564. texture._height = info.height;
  6565. texture.isReady = true;
  6566. }, null, null, true);
  6567. }
  6568. else {
  6569. cascadeLoad(rootUrl, scene, function (imgs) {
  6570. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6571. var height = width;
  6572. _this._prepareWorkingCanvas();
  6573. _this._workingCanvas.width = width;
  6574. _this._workingCanvas.height = height;
  6575. var faces = [
  6576. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6577. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6578. ];
  6579. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6580. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6581. for (var index = 0; index < faces.length; index++) {
  6582. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6583. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6584. }
  6585. if (!noMipmap) {
  6586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6587. }
  6588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6592. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6593. _this.resetTextureCache();
  6594. texture._width = width;
  6595. texture._height = height;
  6596. texture.isReady = true;
  6597. }, extensions);
  6598. }
  6599. return texture;
  6600. };
  6601. Engine.prototype._releaseTexture = function (texture) {
  6602. var gl = this._gl;
  6603. if (texture._framebuffer) {
  6604. gl.deleteFramebuffer(texture._framebuffer);
  6605. }
  6606. if (texture._depthBuffer) {
  6607. gl.deleteRenderbuffer(texture._depthBuffer);
  6608. }
  6609. gl.deleteTexture(texture);
  6610. // Unbind channels
  6611. this.unbindAllTextures();
  6612. var index = this._loadedTexturesCache.indexOf(texture);
  6613. if (index !== -1) {
  6614. this._loadedTexturesCache.splice(index, 1);
  6615. }
  6616. };
  6617. Engine.prototype.bindSamplers = function (effect) {
  6618. this._gl.useProgram(effect.getProgram());
  6619. var samplers = effect.getSamplers();
  6620. for (var index = 0; index < samplers.length; index++) {
  6621. var uniform = effect.getUniform(samplers[index]);
  6622. this._gl.uniform1i(uniform, index);
  6623. }
  6624. this._currentEffect = null;
  6625. };
  6626. Engine.prototype._bindTexture = function (channel, texture) {
  6627. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6628. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6629. this._activeTexturesCache[channel] = null;
  6630. };
  6631. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6632. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6633. };
  6634. Engine.prototype.unbindAllTextures = function () {
  6635. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6636. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6637. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6638. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6639. this._activeTexturesCache[channel] = null;
  6640. }
  6641. };
  6642. Engine.prototype.setTexture = function (channel, texture) {
  6643. if (channel < 0) {
  6644. return;
  6645. }
  6646. // Not ready?
  6647. if (!texture || !texture.isReady()) {
  6648. if (this._activeTexturesCache[channel] != null) {
  6649. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6650. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6651. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6652. this._activeTexturesCache[channel] = null;
  6653. }
  6654. return;
  6655. }
  6656. // Video
  6657. var alreadyActivated = false;
  6658. if (texture instanceof BABYLON.VideoTexture) {
  6659. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6660. alreadyActivated = true;
  6661. texture.update();
  6662. }
  6663. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6664. texture.delayLoad();
  6665. return;
  6666. }
  6667. if (this._activeTexturesCache[channel] === texture) {
  6668. return;
  6669. }
  6670. this._activeTexturesCache[channel] = texture;
  6671. var internalTexture = texture.getInternalTexture();
  6672. if (!alreadyActivated) {
  6673. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6674. }
  6675. if (internalTexture.isCube) {
  6676. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6677. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6678. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6679. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6680. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6681. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6682. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6683. }
  6684. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6685. }
  6686. else {
  6687. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6688. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6689. internalTexture._cachedWrapU = texture.wrapU;
  6690. switch (texture.wrapU) {
  6691. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6693. break;
  6694. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6696. break;
  6697. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6699. break;
  6700. }
  6701. }
  6702. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6703. internalTexture._cachedWrapV = texture.wrapV;
  6704. switch (texture.wrapV) {
  6705. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6707. break;
  6708. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6710. break;
  6711. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6713. break;
  6714. }
  6715. }
  6716. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6717. }
  6718. };
  6719. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6720. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6721. var value = texture.anisotropicFilteringLevel;
  6722. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6723. value = 1;
  6724. }
  6725. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6726. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6727. texture._cachedAnisotropicFilteringLevel = value;
  6728. }
  6729. };
  6730. Engine.prototype.readPixels = function (x, y, width, height) {
  6731. var data = new Uint8Array(height * width * 4);
  6732. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6733. return data;
  6734. };
  6735. Engine.prototype.releaseInternalTexture = function (texture) {
  6736. if (!texture) {
  6737. return;
  6738. }
  6739. texture.references--;
  6740. // Final reference ?
  6741. if (texture.references === 0) {
  6742. var texturesCache = this.getLoadedTexturesCache();
  6743. var index = texturesCache.indexOf(texture);
  6744. if (index > -1) {
  6745. texturesCache.splice(index, 1);
  6746. }
  6747. this._releaseTexture(texture);
  6748. }
  6749. };
  6750. // Dispose
  6751. Engine.prototype.dispose = function () {
  6752. this.hideLoadingUI();
  6753. this.stopRenderLoop();
  6754. // Release scenes
  6755. while (this.scenes.length) {
  6756. this.scenes[0].dispose();
  6757. }
  6758. // Release audio engine
  6759. Engine.audioEngine.dispose();
  6760. // Release effects
  6761. for (var name in this._compiledEffects) {
  6762. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6763. }
  6764. // Unbind
  6765. for (var i in this._vertexAttribArrays) {
  6766. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6767. continue;
  6768. }
  6769. this._gl.disableVertexAttribArray(i);
  6770. }
  6771. this._gl = null;
  6772. // Events
  6773. window.removeEventListener("blur", this._onBlur);
  6774. window.removeEventListener("focus", this._onFocus);
  6775. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6776. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6777. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6778. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6779. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6780. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6781. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6782. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6783. };
  6784. // Loading screen
  6785. Engine.prototype.displayLoadingUI = function () {
  6786. this._loadingScreen.displayLoadingUI();
  6787. };
  6788. Engine.prototype.hideLoadingUI = function () {
  6789. this._loadingScreen.hideLoadingUI();
  6790. };
  6791. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6792. get: function () {
  6793. return this._loadingScreen;
  6794. },
  6795. set: function (loadingScreen) {
  6796. this._loadingScreen = loadingScreen;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6802. set: function (text) {
  6803. this._loadingScreen.loadingUIText = text;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6809. set: function (color) {
  6810. this._loadingScreen.loadingUIBackgroundColor = color;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. // FPS
  6816. Engine.prototype.getFps = function () {
  6817. return this.fps;
  6818. };
  6819. Engine.prototype.getDeltaTime = function () {
  6820. return this.deltaTime;
  6821. };
  6822. Engine.prototype._measureFps = function () {
  6823. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6824. var length = this.previousFramesDuration.length;
  6825. if (length >= 2) {
  6826. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6827. }
  6828. if (length >= this.fpsRange) {
  6829. if (length > this.fpsRange) {
  6830. this.previousFramesDuration.splice(0, 1);
  6831. length = this.previousFramesDuration.length;
  6832. }
  6833. var sum = 0;
  6834. for (var id = 0; id < length - 1; id++) {
  6835. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6836. }
  6837. this.fps = 1000.0 / (sum / (length - 1));
  6838. }
  6839. };
  6840. // Statics
  6841. Engine.isSupported = function () {
  6842. try {
  6843. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6844. if (navigator.isCocoonJS) {
  6845. return true;
  6846. }
  6847. var tempcanvas = document.createElement("canvas");
  6848. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6849. return gl != null && !!window.WebGLRenderingContext;
  6850. }
  6851. catch (e) {
  6852. return false;
  6853. }
  6854. };
  6855. // Const statics
  6856. Engine._ALPHA_DISABLE = 0;
  6857. Engine._ALPHA_ADD = 1;
  6858. Engine._ALPHA_COMBINE = 2;
  6859. Engine._ALPHA_SUBTRACT = 3;
  6860. Engine._ALPHA_MULTIPLY = 4;
  6861. Engine._ALPHA_MAXIMIZED = 5;
  6862. Engine._ALPHA_ONEONE = 6;
  6863. Engine._DELAYLOADSTATE_NONE = 0;
  6864. Engine._DELAYLOADSTATE_LOADED = 1;
  6865. Engine._DELAYLOADSTATE_LOADING = 2;
  6866. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6867. Engine._TEXTUREFORMAT_ALPHA = 0;
  6868. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6869. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6870. Engine._TEXTUREFORMAT_RGB = 4;
  6871. Engine._TEXTUREFORMAT_RGBA = 5;
  6872. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6873. Engine._TEXTURETYPE_FLOAT = 1;
  6874. // Updatable statics so stick with vars here
  6875. Engine.Epsilon = 0.001;
  6876. Engine.CollisionsEpsilon = 0.001;
  6877. Engine.CodeRepository = "src/";
  6878. Engine.ShadersRepository = "src/Shaders/";
  6879. return Engine;
  6880. })();
  6881. BABYLON.Engine = Engine;
  6882. })(BABYLON || (BABYLON = {}));
  6883. var BABYLON;
  6884. (function (BABYLON) {
  6885. /**
  6886. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6887. */
  6888. var Node = (function () {
  6889. /**
  6890. * @constructor
  6891. * @param {string} name - the name and id to be given to this node
  6892. * @param {BABYLON.Scene} the scene this node will be added to
  6893. */
  6894. function Node(name, scene) {
  6895. this.state = "";
  6896. this.animations = new Array();
  6897. this._ranges = {};
  6898. this._childrenFlag = -1;
  6899. this._isEnabled = true;
  6900. this._isReady = true;
  6901. this._currentRenderId = -1;
  6902. this._parentRenderId = -1;
  6903. this.name = name;
  6904. this.id = name;
  6905. this._scene = scene;
  6906. this._initCache();
  6907. }
  6908. Node.prototype.getScene = function () {
  6909. return this._scene;
  6910. };
  6911. Node.prototype.getEngine = function () {
  6912. return this._scene.getEngine();
  6913. };
  6914. // override it in derived class
  6915. Node.prototype.getWorldMatrix = function () {
  6916. return BABYLON.Matrix.Identity();
  6917. };
  6918. // override it in derived class if you add new variables to the cache
  6919. // and call the parent class method
  6920. Node.prototype._initCache = function () {
  6921. this._cache = {};
  6922. this._cache.parent = undefined;
  6923. };
  6924. Node.prototype.updateCache = function (force) {
  6925. if (!force && this.isSynchronized())
  6926. return;
  6927. this._cache.parent = this.parent;
  6928. this._updateCache();
  6929. };
  6930. // override it in derived class if you add new variables to the cache
  6931. // and call the parent class method if !ignoreParentClass
  6932. Node.prototype._updateCache = function (ignoreParentClass) {
  6933. };
  6934. // override it in derived class if you add new variables to the cache
  6935. Node.prototype._isSynchronized = function () {
  6936. return true;
  6937. };
  6938. Node.prototype._markSyncedWithParent = function () {
  6939. this._parentRenderId = this.parent._currentRenderId;
  6940. };
  6941. Node.prototype.isSynchronizedWithParent = function () {
  6942. if (!this.parent) {
  6943. return true;
  6944. }
  6945. if (this._parentRenderId !== this.parent._currentRenderId) {
  6946. return false;
  6947. }
  6948. return this.parent.isSynchronized();
  6949. };
  6950. Node.prototype.isSynchronized = function (updateCache) {
  6951. var check = this.hasNewParent();
  6952. check = check || !this.isSynchronizedWithParent();
  6953. check = check || !this._isSynchronized();
  6954. if (updateCache)
  6955. this.updateCache(true);
  6956. return !check;
  6957. };
  6958. Node.prototype.hasNewParent = function (update) {
  6959. if (this._cache.parent === this.parent)
  6960. return false;
  6961. if (update)
  6962. this._cache.parent = this.parent;
  6963. return true;
  6964. };
  6965. /**
  6966. * Is this node ready to be used/rendered
  6967. * @return {boolean} is it ready
  6968. */
  6969. Node.prototype.isReady = function () {
  6970. return this._isReady;
  6971. };
  6972. /**
  6973. * Is this node enabled.
  6974. * If the node has a parent and is enabled, the parent will be inspected as well.
  6975. * @return {boolean} whether this node (and its parent) is enabled.
  6976. * @see setEnabled
  6977. */
  6978. Node.prototype.isEnabled = function () {
  6979. if (!this._isEnabled) {
  6980. return false;
  6981. }
  6982. if (this.parent) {
  6983. return this.parent.isEnabled();
  6984. }
  6985. return true;
  6986. };
  6987. /**
  6988. * Set the enabled state of this node.
  6989. * @param {boolean} value - the new enabled state
  6990. * @see isEnabled
  6991. */
  6992. Node.prototype.setEnabled = function (value) {
  6993. this._isEnabled = value;
  6994. };
  6995. /**
  6996. * Is this node a descendant of the given node.
  6997. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6998. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6999. * @see parent
  7000. */
  7001. Node.prototype.isDescendantOf = function (ancestor) {
  7002. if (this.parent) {
  7003. if (this.parent === ancestor) {
  7004. return true;
  7005. }
  7006. return this.parent.isDescendantOf(ancestor);
  7007. }
  7008. return false;
  7009. };
  7010. Node.prototype._getDescendants = function (list, results) {
  7011. for (var index = 0; index < list.length; index++) {
  7012. var item = list[index];
  7013. if (item.isDescendantOf(this)) {
  7014. results.push(item);
  7015. }
  7016. }
  7017. };
  7018. /**
  7019. * Will return all nodes that have this node as parent.
  7020. * @return {BABYLON.Node[]} all children nodes of all types.
  7021. */
  7022. Node.prototype.getDescendants = function () {
  7023. var results = [];
  7024. this._getDescendants(this._scene.meshes, results);
  7025. this._getDescendants(this._scene.lights, results);
  7026. this._getDescendants(this._scene.cameras, results);
  7027. return results;
  7028. };
  7029. Node.prototype._setReady = function (state) {
  7030. if (state === this._isReady) {
  7031. return;
  7032. }
  7033. if (!state) {
  7034. this._isReady = false;
  7035. return;
  7036. }
  7037. this._isReady = true;
  7038. if (this.onReady) {
  7039. this.onReady(this);
  7040. }
  7041. };
  7042. Node.prototype.getAnimationByName = function (name) {
  7043. for (var i = 0; i < this.animations.length; i++) {
  7044. var animation = this.animations[i];
  7045. if (animation.name === name) {
  7046. return animation;
  7047. }
  7048. }
  7049. return null;
  7050. };
  7051. Node.prototype.createAnimationRange = function (name, from, to) {
  7052. // check name not already in use
  7053. if (!this._ranges[name]) {
  7054. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7055. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7056. if (this.animations[i]) {
  7057. this.animations[i].createRange(name, from, to);
  7058. }
  7059. }
  7060. }
  7061. };
  7062. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7063. if (deleteFrames === void 0) { deleteFrames = true; }
  7064. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7065. if (this.animations[i]) {
  7066. this.animations[i].deleteRange(name, deleteFrames);
  7067. }
  7068. }
  7069. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7070. };
  7071. Node.prototype.getAnimationRange = function (name) {
  7072. return this._ranges[name];
  7073. };
  7074. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7075. var range = this.getAnimationRange(name);
  7076. if (!range) {
  7077. return null;
  7078. }
  7079. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7080. };
  7081. Node.prototype.serializeAnimationRanges = function () {
  7082. var serializationRanges = [];
  7083. for (var name in this._ranges) {
  7084. var range = {};
  7085. range.name = name;
  7086. range.from = this._ranges[name].from;
  7087. range.to = this._ranges[name].to;
  7088. serializationRanges.push(range);
  7089. }
  7090. return serializationRanges;
  7091. };
  7092. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7093. if (parsedNode.ranges) {
  7094. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7095. var data = parsedNode.ranges[index];
  7096. node.createAnimationRange(data.name, data.from, data.to);
  7097. }
  7098. }
  7099. };
  7100. return Node;
  7101. })();
  7102. BABYLON.Node = Node;
  7103. })(BABYLON || (BABYLON = {}));
  7104. var BABYLON;
  7105. (function (BABYLON) {
  7106. var FilesInput = (function () {
  7107. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7108. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7109. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7110. this._engine = p_engine;
  7111. this._canvas = p_canvas;
  7112. this._currentScene = p_scene;
  7113. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7114. this._progressCallback = p_progressCallback;
  7115. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7116. this._textureLoadingCallback = p_textureLoadingCallback;
  7117. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7118. }
  7119. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7120. var _this = this;
  7121. if (p_elementToMonitor) {
  7122. this._elementToMonitor = p_elementToMonitor;
  7123. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7124. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7125. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7126. }
  7127. };
  7128. FilesInput.prototype.renderFunction = function () {
  7129. if (this._additionnalRenderLoopLogicCallback) {
  7130. this._additionnalRenderLoopLogicCallback();
  7131. }
  7132. if (this._currentScene) {
  7133. if (this._textureLoadingCallback) {
  7134. var remaining = this._currentScene.getWaitingItemsCount();
  7135. if (remaining > 0) {
  7136. this._textureLoadingCallback(remaining);
  7137. }
  7138. }
  7139. this._currentScene.render();
  7140. }
  7141. };
  7142. FilesInput.prototype.drag = function (e) {
  7143. e.stopPropagation();
  7144. e.preventDefault();
  7145. };
  7146. FilesInput.prototype.drop = function (eventDrop) {
  7147. eventDrop.stopPropagation();
  7148. eventDrop.preventDefault();
  7149. this.loadFiles(eventDrop);
  7150. };
  7151. FilesInput.prototype.loadFiles = function (event) {
  7152. if (this._startingProcessingFilesCallback)
  7153. this._startingProcessingFilesCallback();
  7154. // Handling data transfer via drag'n'drop
  7155. if (event && event.dataTransfer && event.dataTransfer.files) {
  7156. this._filesToLoad = event.dataTransfer.files;
  7157. }
  7158. // Handling files from input files
  7159. if (event && event.target && event.target.files) {
  7160. this._filesToLoad = event.target.files;
  7161. }
  7162. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7163. for (var i = 0; i < this._filesToLoad.length; i++) {
  7164. switch (this._filesToLoad[i].type) {
  7165. case "image/jpeg":
  7166. case "image/png":
  7167. case "image/bmp":
  7168. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7169. break;
  7170. case "image/targa":
  7171. case "image/vnd.ms-dds":
  7172. case "audio/wav":
  7173. case "audio/x-wav":
  7174. case "audio/mp3":
  7175. case "audio/mpeg":
  7176. case "audio/mpeg3":
  7177. case "audio/x-mpeg-3":
  7178. case "audio/ogg":
  7179. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7180. break;
  7181. default:
  7182. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7183. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7184. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7185. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7186. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7187. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7188. this._sceneFileToLoad = this._filesToLoad[i];
  7189. }
  7190. break;
  7191. }
  7192. }
  7193. this.reload();
  7194. }
  7195. };
  7196. FilesInput.prototype.reload = function () {
  7197. var _this = this;
  7198. var that = this;
  7199. // If a ".babylon" file has been provided
  7200. if (this._sceneFileToLoad) {
  7201. if (this._currentScene) {
  7202. if (BABYLON.Tools.errorsCount > 0) {
  7203. BABYLON.Tools.ClearLogCache();
  7204. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7205. }
  7206. this._engine.stopRenderLoop();
  7207. this._currentScene.dispose();
  7208. }
  7209. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7210. that._currentScene = newScene;
  7211. // Wait for textures and shaders to be ready
  7212. that._currentScene.executeWhenReady(function () {
  7213. // Attach camera to canvas inputs
  7214. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7215. that._currentScene.createDefaultCameraOrLight();
  7216. }
  7217. that._currentScene.activeCamera.attachControl(that._canvas);
  7218. if (that._sceneLoadedCallback) {
  7219. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7220. }
  7221. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7222. });
  7223. }, function (progress) {
  7224. if (_this._progressCallback) {
  7225. _this._progressCallback(progress);
  7226. }
  7227. });
  7228. }
  7229. else {
  7230. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7231. }
  7232. };
  7233. FilesInput.FilesTextures = new Array();
  7234. FilesInput.FilesToLoad = new Array();
  7235. return FilesInput;
  7236. })();
  7237. BABYLON.FilesInput = FilesInput;
  7238. })(BABYLON || (BABYLON = {}));
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var IntersectionInfo = (function () {
  7242. function IntersectionInfo(bu, bv, distance) {
  7243. this.bu = bu;
  7244. this.bv = bv;
  7245. this.distance = distance;
  7246. this.faceId = 0;
  7247. this.subMeshId = 0;
  7248. }
  7249. return IntersectionInfo;
  7250. })();
  7251. BABYLON.IntersectionInfo = IntersectionInfo;
  7252. var PickingInfo = (function () {
  7253. function PickingInfo() {
  7254. this.hit = false;
  7255. this.distance = 0;
  7256. this.pickedPoint = null;
  7257. this.pickedMesh = null;
  7258. this.bu = 0;
  7259. this.bv = 0;
  7260. this.faceId = -1;
  7261. this.subMeshId = 0;
  7262. this.pickedSprite = null;
  7263. }
  7264. // Methods
  7265. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7266. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7267. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7268. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7269. return null;
  7270. }
  7271. var indices = this.pickedMesh.getIndices();
  7272. var result;
  7273. if (useVerticesNormals) {
  7274. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7275. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7276. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7277. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7278. normal0 = normal0.scale(this.bu);
  7279. normal1 = normal1.scale(this.bv);
  7280. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7281. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7282. }
  7283. else {
  7284. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7285. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7286. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7287. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7288. var p1p2 = vertex1.subtract(vertex2);
  7289. var p3p2 = vertex3.subtract(vertex2);
  7290. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7291. }
  7292. if (useWorldCoordinates) {
  7293. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7294. }
  7295. return BABYLON.Vector3.Normalize(result);
  7296. };
  7297. PickingInfo.prototype.getTextureCoordinates = function () {
  7298. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7299. return null;
  7300. }
  7301. var indices = this.pickedMesh.getIndices();
  7302. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7303. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7304. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7305. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7306. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7307. uv1 = uv1.scale(this.bu);
  7308. uv2 = uv2.scale(this.bv);
  7309. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7310. };
  7311. return PickingInfo;
  7312. })();
  7313. BABYLON.PickingInfo = PickingInfo;
  7314. })(BABYLON || (BABYLON = {}));
  7315. var BABYLON;
  7316. (function (BABYLON) {
  7317. var BoundingSphere = (function () {
  7318. function BoundingSphere(minimum, maximum) {
  7319. this.minimum = minimum;
  7320. this.maximum = maximum;
  7321. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7322. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7323. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7324. this.radius = distance * 0.5;
  7325. this.centerWorld = BABYLON.Vector3.Zero();
  7326. this._update(BABYLON.Matrix.Identity());
  7327. }
  7328. // Methods
  7329. BoundingSphere.prototype._update = function (world) {
  7330. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7331. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7332. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7333. };
  7334. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7335. for (var i = 0; i < 6; i++) {
  7336. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7337. return false;
  7338. }
  7339. return true;
  7340. };
  7341. BoundingSphere.prototype.intersectsPoint = function (point) {
  7342. var x = this.centerWorld.x - point.x;
  7343. var y = this.centerWorld.y - point.y;
  7344. var z = this.centerWorld.z - point.z;
  7345. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7346. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7347. return false;
  7348. return true;
  7349. };
  7350. // Statics
  7351. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7352. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7353. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7354. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7355. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7356. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7357. return false;
  7358. return true;
  7359. };
  7360. return BoundingSphere;
  7361. })();
  7362. BABYLON.BoundingSphere = BoundingSphere;
  7363. })(BABYLON || (BABYLON = {}));
  7364. var BABYLON;
  7365. (function (BABYLON) {
  7366. var BoundingBox = (function () {
  7367. function BoundingBox(minimum, maximum) {
  7368. this.minimum = minimum;
  7369. this.maximum = maximum;
  7370. this.vectors = new Array();
  7371. this.vectorsWorld = new Array();
  7372. // Bounding vectors
  7373. this.vectors.push(this.minimum.clone());
  7374. this.vectors.push(this.maximum.clone());
  7375. this.vectors.push(this.minimum.clone());
  7376. this.vectors[2].x = this.maximum.x;
  7377. this.vectors.push(this.minimum.clone());
  7378. this.vectors[3].y = this.maximum.y;
  7379. this.vectors.push(this.minimum.clone());
  7380. this.vectors[4].z = this.maximum.z;
  7381. this.vectors.push(this.maximum.clone());
  7382. this.vectors[5].z = this.minimum.z;
  7383. this.vectors.push(this.maximum.clone());
  7384. this.vectors[6].x = this.minimum.x;
  7385. this.vectors.push(this.maximum.clone());
  7386. this.vectors[7].y = this.minimum.y;
  7387. // OBB
  7388. this.center = this.maximum.add(this.minimum).scale(0.5);
  7389. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7390. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7391. // World
  7392. for (var index = 0; index < this.vectors.length; index++) {
  7393. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7394. }
  7395. this.minimumWorld = BABYLON.Vector3.Zero();
  7396. this.maximumWorld = BABYLON.Vector3.Zero();
  7397. this._update(BABYLON.Matrix.Identity());
  7398. }
  7399. // Methods
  7400. BoundingBox.prototype.getWorldMatrix = function () {
  7401. return this._worldMatrix;
  7402. };
  7403. BoundingBox.prototype._update = function (world) {
  7404. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7405. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7406. for (var index = 0; index < this.vectors.length; index++) {
  7407. var v = this.vectorsWorld[index];
  7408. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7409. if (v.x < this.minimumWorld.x)
  7410. this.minimumWorld.x = v.x;
  7411. if (v.y < this.minimumWorld.y)
  7412. this.minimumWorld.y = v.y;
  7413. if (v.z < this.minimumWorld.z)
  7414. this.minimumWorld.z = v.z;
  7415. if (v.x > this.maximumWorld.x)
  7416. this.maximumWorld.x = v.x;
  7417. if (v.y > this.maximumWorld.y)
  7418. this.maximumWorld.y = v.y;
  7419. if (v.z > this.maximumWorld.z)
  7420. this.maximumWorld.z = v.z;
  7421. }
  7422. // OBB
  7423. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7424. this.center.scaleInPlace(0.5);
  7425. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7426. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7427. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7428. this._worldMatrix = world;
  7429. };
  7430. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7431. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7432. };
  7433. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7434. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7435. };
  7436. BoundingBox.prototype.intersectsPoint = function (point) {
  7437. var delta = -BABYLON.Engine.Epsilon;
  7438. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7439. return false;
  7440. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7441. return false;
  7442. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7443. return false;
  7444. return true;
  7445. };
  7446. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7447. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7448. };
  7449. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7450. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7451. return false;
  7452. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7453. return false;
  7454. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7455. return false;
  7456. return true;
  7457. };
  7458. // Statics
  7459. BoundingBox.Intersects = function (box0, box1) {
  7460. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7461. return false;
  7462. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7463. return false;
  7464. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7465. return false;
  7466. return true;
  7467. };
  7468. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7469. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7470. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7471. return (num <= (sphereRadius * sphereRadius));
  7472. };
  7473. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7474. for (var p = 0; p < 6; p++) {
  7475. for (var i = 0; i < 8; i++) {
  7476. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7477. return false;
  7478. }
  7479. }
  7480. }
  7481. return true;
  7482. };
  7483. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7484. for (var p = 0; p < 6; p++) {
  7485. var inCount = 8;
  7486. for (var i = 0; i < 8; i++) {
  7487. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7488. --inCount;
  7489. }
  7490. else {
  7491. break;
  7492. }
  7493. }
  7494. if (inCount === 0)
  7495. return false;
  7496. }
  7497. return true;
  7498. };
  7499. return BoundingBox;
  7500. })();
  7501. BABYLON.BoundingBox = BoundingBox;
  7502. })(BABYLON || (BABYLON = {}));
  7503. var BABYLON;
  7504. (function (BABYLON) {
  7505. var computeBoxExtents = function (axis, box) {
  7506. var p = BABYLON.Vector3.Dot(box.center, axis);
  7507. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7508. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7509. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7510. var r = r0 + r1 + r2;
  7511. return {
  7512. min: p - r,
  7513. max: p + r
  7514. };
  7515. };
  7516. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7517. var axisOverlap = function (axis, box0, box1) {
  7518. var result0 = computeBoxExtents(axis, box0);
  7519. var result1 = computeBoxExtents(axis, box1);
  7520. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7521. };
  7522. var BoundingInfo = (function () {
  7523. function BoundingInfo(minimum, maximum) {
  7524. this.minimum = minimum;
  7525. this.maximum = maximum;
  7526. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7527. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7528. }
  7529. // Methods
  7530. BoundingInfo.prototype._update = function (world) {
  7531. this.boundingBox._update(world);
  7532. this.boundingSphere._update(world);
  7533. };
  7534. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7535. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7536. return false;
  7537. return this.boundingBox.isInFrustum(frustumPlanes);
  7538. };
  7539. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7540. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7541. };
  7542. BoundingInfo.prototype._checkCollision = function (collider) {
  7543. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7544. };
  7545. BoundingInfo.prototype.intersectsPoint = function (point) {
  7546. if (!this.boundingSphere.centerWorld) {
  7547. return false;
  7548. }
  7549. if (!this.boundingSphere.intersectsPoint(point)) {
  7550. return false;
  7551. }
  7552. if (!this.boundingBox.intersectsPoint(point)) {
  7553. return false;
  7554. }
  7555. return true;
  7556. };
  7557. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7558. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7559. return false;
  7560. }
  7561. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7562. return false;
  7563. }
  7564. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7565. return false;
  7566. }
  7567. if (!precise) {
  7568. return true;
  7569. }
  7570. var box0 = this.boundingBox;
  7571. var box1 = boundingInfo.boundingBox;
  7572. if (!axisOverlap(box0.directions[0], box0, box1))
  7573. return false;
  7574. if (!axisOverlap(box0.directions[1], box0, box1))
  7575. return false;
  7576. if (!axisOverlap(box0.directions[2], box0, box1))
  7577. return false;
  7578. if (!axisOverlap(box1.directions[0], box0, box1))
  7579. return false;
  7580. if (!axisOverlap(box1.directions[1], box0, box1))
  7581. return false;
  7582. if (!axisOverlap(box1.directions[2], box0, box1))
  7583. return false;
  7584. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7585. return false;
  7586. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7587. return false;
  7588. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7589. return false;
  7590. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7591. return false;
  7592. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7593. return false;
  7594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7595. return false;
  7596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7597. return false;
  7598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7599. return false;
  7600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7601. return false;
  7602. return true;
  7603. };
  7604. return BoundingInfo;
  7605. })();
  7606. BABYLON.BoundingInfo = BoundingInfo;
  7607. })(BABYLON || (BABYLON = {}));
  7608. var BABYLON;
  7609. (function (BABYLON) {
  7610. var AbstractMesh = (function (_super) {
  7611. __extends(AbstractMesh, _super);
  7612. function AbstractMesh(name, scene) {
  7613. var _this = this;
  7614. _super.call(this, name, scene);
  7615. // Properties
  7616. this.definedFacingForward = true; // orientation for POV movement & rotation
  7617. this.position = new BABYLON.Vector3(0, 0, 0);
  7618. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7619. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7620. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7621. this.visibility = 1.0;
  7622. this.alphaIndex = Number.MAX_VALUE;
  7623. this.infiniteDistance = false;
  7624. this.isVisible = true;
  7625. this.isPickable = true;
  7626. this.showBoundingBox = false;
  7627. this.showSubMeshesBoundingBox = false;
  7628. this.onDispose = null;
  7629. this.isBlocker = false;
  7630. this.renderingGroupId = 0;
  7631. this.receiveShadows = false;
  7632. this.renderOutline = false;
  7633. this.outlineColor = BABYLON.Color3.Red();
  7634. this.outlineWidth = 0.02;
  7635. this.renderOverlay = false;
  7636. this.overlayColor = BABYLON.Color3.Red();
  7637. this.overlayAlpha = 0.5;
  7638. this.hasVertexAlpha = false;
  7639. this.useVertexColors = true;
  7640. this.applyFog = true;
  7641. this.computeBonesUsingShaders = true;
  7642. this.scalingDeterminant = 1;
  7643. this.numBoneInfluencers = 4;
  7644. this.useOctreeForRenderingSelection = true;
  7645. this.useOctreeForPicking = true;
  7646. this.useOctreeForCollisions = true;
  7647. this.layerMask = 0x0FFFFFFF;
  7648. this.alwaysSelectAsActiveMesh = false;
  7649. // Physics
  7650. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7651. // Collisions
  7652. this._checkCollisions = false;
  7653. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7654. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7655. this._collider = new BABYLON.Collider();
  7656. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7657. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7658. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7659. // Edges
  7660. this.edgesWidth = 1;
  7661. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7662. // Cache
  7663. this._localWorld = BABYLON.Matrix.Zero();
  7664. this._worldMatrix = BABYLON.Matrix.Zero();
  7665. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7666. this._absolutePosition = BABYLON.Vector3.Zero();
  7667. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7668. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7669. this._isDirty = false;
  7670. this._pivotMatrix = BABYLON.Matrix.Identity();
  7671. this._isDisposed = false;
  7672. this._renderId = 0;
  7673. this._intersectionsInProgress = new Array();
  7674. this._onAfterWorldMatrixUpdate = new Array();
  7675. this._isWorldMatrixFrozen = false;
  7676. this._unIndexed = false;
  7677. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7678. if (collidedMesh === void 0) { collidedMesh = null; }
  7679. //TODO move this to the collision coordinator!
  7680. if (_this.getScene().workerCollisions)
  7681. newPosition.multiplyInPlace(_this._collider.radius);
  7682. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7683. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7684. _this.position.addInPlace(_this._diffPositionForCollisions);
  7685. }
  7686. if (_this.onCollide && collidedMesh) {
  7687. _this.onCollide(collidedMesh);
  7688. }
  7689. if (_this.onCollisionPositionChange) {
  7690. _this.onCollisionPositionChange(_this.position);
  7691. }
  7692. };
  7693. scene.addMesh(this);
  7694. }
  7695. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7696. get: function () {
  7697. return AbstractMesh._BILLBOARDMODE_NONE;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7703. get: function () {
  7704. return AbstractMesh._BILLBOARDMODE_X;
  7705. },
  7706. enumerable: true,
  7707. configurable: true
  7708. });
  7709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7710. get: function () {
  7711. return AbstractMesh._BILLBOARDMODE_Y;
  7712. },
  7713. enumerable: true,
  7714. configurable: true
  7715. });
  7716. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7717. get: function () {
  7718. return AbstractMesh._BILLBOARDMODE_Z;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7724. get: function () {
  7725. return AbstractMesh._BILLBOARDMODE_ALL;
  7726. },
  7727. enumerable: true,
  7728. configurable: true
  7729. });
  7730. // Methods
  7731. AbstractMesh.prototype.disableEdgesRendering = function () {
  7732. if (this._edgesRenderer !== undefined) {
  7733. this._edgesRenderer.dispose();
  7734. this._edgesRenderer = undefined;
  7735. }
  7736. };
  7737. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7738. if (epsilon === void 0) { epsilon = 0.95; }
  7739. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7740. this.disableEdgesRendering();
  7741. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7742. };
  7743. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7744. get: function () {
  7745. return false;
  7746. },
  7747. enumerable: true,
  7748. configurable: true
  7749. });
  7750. AbstractMesh.prototype.getLOD = function (camera) {
  7751. return this;
  7752. };
  7753. AbstractMesh.prototype.getTotalVertices = function () {
  7754. return 0;
  7755. };
  7756. AbstractMesh.prototype.getIndices = function () {
  7757. return null;
  7758. };
  7759. AbstractMesh.prototype.getVerticesData = function (kind) {
  7760. return null;
  7761. };
  7762. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7763. return false;
  7764. };
  7765. AbstractMesh.prototype.getBoundingInfo = function () {
  7766. if (this._masterMesh) {
  7767. return this._masterMesh.getBoundingInfo();
  7768. }
  7769. if (!this._boundingInfo) {
  7770. this._updateBoundingInfo();
  7771. }
  7772. return this._boundingInfo;
  7773. };
  7774. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7775. get: function () {
  7776. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. AbstractMesh.prototype._preActivate = function () {
  7782. };
  7783. AbstractMesh.prototype._activate = function (renderId) {
  7784. this._renderId = renderId;
  7785. };
  7786. AbstractMesh.prototype.getWorldMatrix = function () {
  7787. if (this._masterMesh) {
  7788. return this._masterMesh.getWorldMatrix();
  7789. }
  7790. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7791. this.computeWorldMatrix();
  7792. }
  7793. return this._worldMatrix;
  7794. };
  7795. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7796. get: function () {
  7797. return this._worldMatrix;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7803. get: function () {
  7804. return this._absolutePosition;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7810. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7811. this.computeWorldMatrix(true);
  7812. this._isWorldMatrixFrozen = true;
  7813. };
  7814. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7815. this._isWorldMatrixFrozen = false;
  7816. this.computeWorldMatrix(true);
  7817. };
  7818. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7819. get: function () {
  7820. return this._isWorldMatrixFrozen;
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7826. axis.normalize();
  7827. if (!this.rotationQuaternion) {
  7828. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7829. this.rotation = BABYLON.Vector3.Zero();
  7830. }
  7831. var rotationQuaternion;
  7832. if (!space || space === BABYLON.Space.LOCAL) {
  7833. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7834. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7835. }
  7836. else {
  7837. if (this.parent) {
  7838. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7839. invertParentWorldMatrix.invert();
  7840. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7841. }
  7842. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7843. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7844. }
  7845. };
  7846. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7847. var displacementVector = axis.scale(distance);
  7848. if (!space || space === BABYLON.Space.LOCAL) {
  7849. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7850. this.setPositionWithLocalVector(tempV3);
  7851. }
  7852. else {
  7853. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7854. }
  7855. };
  7856. AbstractMesh.prototype.getAbsolutePosition = function () {
  7857. this.computeWorldMatrix();
  7858. return this._absolutePosition;
  7859. };
  7860. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7861. if (!absolutePosition) {
  7862. return;
  7863. }
  7864. var absolutePositionX;
  7865. var absolutePositionY;
  7866. var absolutePositionZ;
  7867. if (absolutePosition.x === undefined) {
  7868. if (arguments.length < 3) {
  7869. return;
  7870. }
  7871. absolutePositionX = arguments[0];
  7872. absolutePositionY = arguments[1];
  7873. absolutePositionZ = arguments[2];
  7874. }
  7875. else {
  7876. absolutePositionX = absolutePosition.x;
  7877. absolutePositionY = absolutePosition.y;
  7878. absolutePositionZ = absolutePosition.z;
  7879. }
  7880. if (this.parent) {
  7881. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7882. invertParentWorldMatrix.invert();
  7883. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7884. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7885. }
  7886. else {
  7887. this.position.x = absolutePositionX;
  7888. this.position.y = absolutePositionY;
  7889. this.position.z = absolutePositionZ;
  7890. }
  7891. };
  7892. // ================================== Point of View Movement =================================
  7893. /**
  7894. * Perform relative position change from the point of view of behind the front of the mesh.
  7895. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7896. * Supports definition of mesh facing forward or backward.
  7897. * @param {number} amountRight
  7898. * @param {number} amountUp
  7899. * @param {number} amountForward
  7900. */
  7901. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7902. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7903. };
  7904. /**
  7905. * Calculate relative position change from the point of view of behind the front of the mesh.
  7906. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7907. * Supports definition of mesh facing forward or backward.
  7908. * @param {number} amountRight
  7909. * @param {number} amountUp
  7910. * @param {number} amountForward
  7911. */
  7912. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7913. var rotMatrix = new BABYLON.Matrix();
  7914. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7915. rotQuaternion.toRotationMatrix(rotMatrix);
  7916. var translationDelta = BABYLON.Vector3.Zero();
  7917. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7918. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7919. return translationDelta;
  7920. };
  7921. // ================================== Point of View Rotation =================================
  7922. /**
  7923. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7924. * Supports definition of mesh facing forward or backward.
  7925. * @param {number} flipBack
  7926. * @param {number} twirlClockwise
  7927. * @param {number} tiltRight
  7928. */
  7929. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7930. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7931. };
  7932. /**
  7933. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7934. * Supports definition of mesh facing forward or backward.
  7935. * @param {number} flipBack
  7936. * @param {number} twirlClockwise
  7937. * @param {number} tiltRight
  7938. */
  7939. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7940. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7941. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7942. };
  7943. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7944. this._pivotMatrix = matrix;
  7945. this._cache.pivotMatrixUpdated = true;
  7946. };
  7947. AbstractMesh.prototype.getPivotMatrix = function () {
  7948. return this._pivotMatrix;
  7949. };
  7950. AbstractMesh.prototype._isSynchronized = function () {
  7951. if (this._isDirty) {
  7952. return false;
  7953. }
  7954. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7955. return false;
  7956. if (this._cache.pivotMatrixUpdated) {
  7957. return false;
  7958. }
  7959. if (this.infiniteDistance) {
  7960. return false;
  7961. }
  7962. if (!this._cache.position.equals(this.position))
  7963. return false;
  7964. if (this.rotationQuaternion) {
  7965. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7966. return false;
  7967. }
  7968. else {
  7969. if (!this._cache.rotation.equals(this.rotation))
  7970. return false;
  7971. }
  7972. if (!this._cache.scaling.equals(this.scaling))
  7973. return false;
  7974. return true;
  7975. };
  7976. AbstractMesh.prototype._initCache = function () {
  7977. _super.prototype._initCache.call(this);
  7978. this._cache.localMatrixUpdated = false;
  7979. this._cache.position = BABYLON.Vector3.Zero();
  7980. this._cache.scaling = BABYLON.Vector3.Zero();
  7981. this._cache.rotation = BABYLON.Vector3.Zero();
  7982. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7983. this._cache.billboardMode = -1;
  7984. };
  7985. AbstractMesh.prototype.markAsDirty = function (property) {
  7986. if (property === "rotation") {
  7987. this.rotationQuaternion = null;
  7988. }
  7989. this._currentRenderId = Number.MAX_VALUE;
  7990. this._isDirty = true;
  7991. };
  7992. AbstractMesh.prototype._updateBoundingInfo = function () {
  7993. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7994. this._boundingInfo._update(this.worldMatrixFromCache);
  7995. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7996. };
  7997. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7998. if (!this.subMeshes) {
  7999. return;
  8000. }
  8001. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8002. var subMesh = this.subMeshes[subIndex];
  8003. if (!subMesh.IsGlobal) {
  8004. subMesh.updateBoundingInfo(matrix);
  8005. }
  8006. }
  8007. };
  8008. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8009. if (this._isWorldMatrixFrozen) {
  8010. return this._worldMatrix;
  8011. }
  8012. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8013. this._currentRenderId = this.getScene().getRenderId();
  8014. return this._worldMatrix;
  8015. }
  8016. this._cache.position.copyFrom(this.position);
  8017. this._cache.scaling.copyFrom(this.scaling);
  8018. this._cache.pivotMatrixUpdated = false;
  8019. this._cache.billboardMode = this.billboardMode;
  8020. this._currentRenderId = this.getScene().getRenderId();
  8021. this._isDirty = false;
  8022. // Scaling
  8023. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8024. // Rotation
  8025. if (this.rotationQuaternion) {
  8026. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8027. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8028. }
  8029. else {
  8030. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8031. this._cache.rotation.copyFrom(this.rotation);
  8032. }
  8033. // Translation
  8034. if (this.infiniteDistance && !this.parent) {
  8035. var camera = this.getScene().activeCamera;
  8036. if (camera) {
  8037. var cameraWorldMatrix = camera.getWorldMatrix();
  8038. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8039. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8040. }
  8041. }
  8042. else {
  8043. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8044. }
  8045. // Composing transformations
  8046. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8047. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8048. // Billboarding
  8049. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8050. var localPosition = this.position.clone();
  8051. var zero = this.getScene().activeCamera.globalPosition.clone();
  8052. if (this.parent && this.parent.position) {
  8053. localPosition.addInPlace(this.parent.position);
  8054. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8055. }
  8056. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8057. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8058. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8059. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8060. zero.y = localPosition.y + 0.001;
  8061. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8062. zero.z = localPosition.z + 0.001;
  8063. }
  8064. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8065. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8066. BABYLON.Tmp.Matrix[3].invert();
  8067. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8068. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8069. }
  8070. // Local world
  8071. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8072. // Parent
  8073. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8074. this._markSyncedWithParent();
  8075. if (this._meshToBoneReferal) {
  8076. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8077. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8078. }
  8079. else {
  8080. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8081. }
  8082. }
  8083. else {
  8084. this._worldMatrix.copyFrom(this._localWorld);
  8085. }
  8086. // Bounding info
  8087. this._updateBoundingInfo();
  8088. // Absolute position
  8089. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8090. // Callbacks
  8091. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8092. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8093. }
  8094. return this._worldMatrix;
  8095. };
  8096. /**
  8097. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8098. * @param func: callback function to add
  8099. */
  8100. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8101. this._onAfterWorldMatrixUpdate.push(func);
  8102. };
  8103. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8104. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8105. if (index > -1) {
  8106. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8107. }
  8108. };
  8109. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8110. this.computeWorldMatrix();
  8111. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8112. };
  8113. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8114. this.computeWorldMatrix();
  8115. var invLocalWorldMatrix = this._localWorld.clone();
  8116. invLocalWorldMatrix.invert();
  8117. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8118. };
  8119. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8120. this.computeWorldMatrix(true);
  8121. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8122. };
  8123. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8124. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8125. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8126. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8127. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8128. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8129. /// <returns>Mesh oriented towards targetMesh</returns>
  8130. yawCor = yawCor || 0; // default to zero if undefined
  8131. pitchCor = pitchCor || 0;
  8132. rollCor = rollCor || 0;
  8133. var dv = targetPoint.subtract(this.position);
  8134. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8135. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8136. var pitch = Math.atan2(dv.y, len);
  8137. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8138. };
  8139. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8140. this._meshToBoneReferal = affectedMesh;
  8141. this.parent = bone;
  8142. if (bone.getWorldMatrix().determinant() < 0) {
  8143. this.scalingDeterminant *= -1;
  8144. }
  8145. };
  8146. AbstractMesh.prototype.detachFromBone = function () {
  8147. if (this.parent.getWorldMatrix().determinant() < 0) {
  8148. this.scalingDeterminant *= -1;
  8149. }
  8150. this._meshToBoneReferal = null;
  8151. this.parent = null;
  8152. };
  8153. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8154. return this._boundingInfo.isInFrustum(frustumPlanes);
  8155. };
  8156. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8157. if (!camera) {
  8158. camera = this.getScene().activeCamera;
  8159. }
  8160. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8161. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8162. return false;
  8163. }
  8164. return true;
  8165. };
  8166. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8167. if (!this._boundingInfo || !mesh._boundingInfo) {
  8168. return false;
  8169. }
  8170. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8171. };
  8172. AbstractMesh.prototype.intersectsPoint = function (point) {
  8173. if (!this._boundingInfo) {
  8174. return false;
  8175. }
  8176. return this._boundingInfo.intersectsPoint(point);
  8177. };
  8178. // Physics
  8179. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8180. var physicsEngine = this.getScene().getPhysicsEngine();
  8181. if (!physicsEngine) {
  8182. return null;
  8183. }
  8184. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8185. if (impostor.impostor) {
  8186. // Old API
  8187. options = impostor;
  8188. impostor = impostor.impostor;
  8189. }
  8190. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8191. physicsEngine._unregisterMesh(this);
  8192. return null;
  8193. }
  8194. if (!options) {
  8195. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8196. }
  8197. else {
  8198. if (!options.mass && options.mass !== 0)
  8199. options.mass = 0;
  8200. if (!options.friction && options.friction !== 0)
  8201. options.friction = 0.2;
  8202. if (!options.restitution && options.restitution !== 0)
  8203. options.restitution = 0.2;
  8204. }
  8205. this._physicImpostor = impostor;
  8206. this._physicsMass = options.mass;
  8207. this._physicsFriction = options.friction;
  8208. this._physicRestitution = options.restitution;
  8209. return physicsEngine._registerMesh(this, impostor, options);
  8210. };
  8211. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8212. if (!this._physicImpostor) {
  8213. return BABYLON.PhysicsEngine.NoImpostor;
  8214. }
  8215. return this._physicImpostor;
  8216. };
  8217. AbstractMesh.prototype.getPhysicsMass = function () {
  8218. if (!this._physicsMass) {
  8219. return 0;
  8220. }
  8221. return this._physicsMass;
  8222. };
  8223. AbstractMesh.prototype.getPhysicsFriction = function () {
  8224. if (!this._physicsFriction) {
  8225. return 0;
  8226. }
  8227. return this._physicsFriction;
  8228. };
  8229. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8230. if (!this._physicRestitution) {
  8231. return 0;
  8232. }
  8233. return this._physicRestitution;
  8234. };
  8235. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8236. if (!camera) {
  8237. camera = this.getScene().activeCamera;
  8238. }
  8239. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8240. };
  8241. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8242. if (!camera) {
  8243. camera = this.getScene().activeCamera;
  8244. }
  8245. return this.absolutePosition.subtract(camera.position).length();
  8246. };
  8247. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8248. if (!this._physicImpostor) {
  8249. return;
  8250. }
  8251. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8252. };
  8253. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8254. if (!this._physicImpostor) {
  8255. return;
  8256. }
  8257. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8258. };
  8259. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8260. if (!this._physicImpostor) {
  8261. return;
  8262. }
  8263. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8264. };
  8265. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8266. // Collisions
  8267. get: function () {
  8268. return this._checkCollisions;
  8269. },
  8270. set: function (collisionEnabled) {
  8271. this._checkCollisions = collisionEnabled;
  8272. if (this.getScene().workerCollisions) {
  8273. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8274. }
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8280. var globalPosition = this.getAbsolutePosition();
  8281. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8282. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8283. this._collider.radius = this.ellipsoid;
  8284. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8285. };
  8286. // Submeshes octree
  8287. /**
  8288. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8289. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8290. */
  8291. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8292. if (maxCapacity === void 0) { maxCapacity = 64; }
  8293. if (maxDepth === void 0) { maxDepth = 2; }
  8294. if (!this._submeshesOctree) {
  8295. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8296. }
  8297. this.computeWorldMatrix(true);
  8298. // Update octree
  8299. var bbox = this.getBoundingInfo().boundingBox;
  8300. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8301. return this._submeshesOctree;
  8302. };
  8303. // Collisions
  8304. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8305. this._generatePointsArray();
  8306. // Transformation
  8307. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8308. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8309. subMesh._lastColliderWorldVertices = [];
  8310. subMesh._trianglePlanes = [];
  8311. var start = subMesh.verticesStart;
  8312. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8313. for (var i = start; i < end; i++) {
  8314. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8315. }
  8316. }
  8317. // Collide
  8318. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8319. if (collider.collisionFound) {
  8320. collider.collidedMesh = this;
  8321. }
  8322. };
  8323. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8324. var subMeshes;
  8325. var len;
  8326. // Octrees
  8327. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8328. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8329. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8330. len = intersections.length;
  8331. subMeshes = intersections.data;
  8332. }
  8333. else {
  8334. subMeshes = this.subMeshes;
  8335. len = subMeshes.length;
  8336. }
  8337. for (var index = 0; index < len; index++) {
  8338. var subMesh = subMeshes[index];
  8339. // Bounding test
  8340. if (len > 1 && !subMesh._checkCollision(collider))
  8341. continue;
  8342. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8343. }
  8344. };
  8345. AbstractMesh.prototype._checkCollision = function (collider) {
  8346. // Bounding box test
  8347. if (!this._boundingInfo._checkCollision(collider))
  8348. return;
  8349. // Transformation matrix
  8350. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8351. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8352. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8353. };
  8354. // Picking
  8355. AbstractMesh.prototype._generatePointsArray = function () {
  8356. return false;
  8357. };
  8358. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8359. var pickingInfo = new BABYLON.PickingInfo();
  8360. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8361. return pickingInfo;
  8362. }
  8363. if (!this._generatePointsArray()) {
  8364. return pickingInfo;
  8365. }
  8366. var intersectInfo = null;
  8367. // Octrees
  8368. var subMeshes;
  8369. var len;
  8370. if (this._submeshesOctree && this.useOctreeForPicking) {
  8371. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8372. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8373. len = intersections.length;
  8374. subMeshes = intersections.data;
  8375. }
  8376. else {
  8377. subMeshes = this.subMeshes;
  8378. len = subMeshes.length;
  8379. }
  8380. for (var index = 0; index < len; index++) {
  8381. var subMesh = subMeshes[index];
  8382. // Bounding test
  8383. if (len > 1 && !subMesh.canIntersects(ray))
  8384. continue;
  8385. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8386. if (currentIntersectInfo) {
  8387. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8388. intersectInfo = currentIntersectInfo;
  8389. intersectInfo.subMeshId = index;
  8390. if (fastCheck) {
  8391. break;
  8392. }
  8393. }
  8394. }
  8395. }
  8396. if (intersectInfo) {
  8397. // Get picked point
  8398. var world = this.getWorldMatrix();
  8399. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8400. var direction = ray.direction.clone();
  8401. direction = direction.scale(intersectInfo.distance);
  8402. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8403. var pickedPoint = worldOrigin.add(worldDirection);
  8404. // Return result
  8405. pickingInfo.hit = true;
  8406. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8407. pickingInfo.pickedPoint = pickedPoint;
  8408. pickingInfo.pickedMesh = this;
  8409. pickingInfo.bu = intersectInfo.bu;
  8410. pickingInfo.bv = intersectInfo.bv;
  8411. pickingInfo.faceId = intersectInfo.faceId;
  8412. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8413. return pickingInfo;
  8414. }
  8415. return pickingInfo;
  8416. };
  8417. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8418. return null;
  8419. };
  8420. AbstractMesh.prototype.releaseSubMeshes = function () {
  8421. if (this.subMeshes) {
  8422. while (this.subMeshes.length) {
  8423. this.subMeshes[0].dispose();
  8424. }
  8425. }
  8426. else {
  8427. this.subMeshes = new Array();
  8428. }
  8429. };
  8430. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8431. var index;
  8432. // Animations
  8433. this.getScene().stopAnimation(this);
  8434. // Physics
  8435. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8436. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8437. }
  8438. // Intersections in progress
  8439. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8440. var other = this._intersectionsInProgress[index];
  8441. var pos = other._intersectionsInProgress.indexOf(this);
  8442. other._intersectionsInProgress.splice(pos, 1);
  8443. }
  8444. this._intersectionsInProgress = [];
  8445. // Edges
  8446. if (this._edgesRenderer) {
  8447. this._edgesRenderer.dispose();
  8448. this._edgesRenderer = null;
  8449. }
  8450. // SubMeshes
  8451. this.releaseSubMeshes();
  8452. // Remove from scene
  8453. this.getScene().removeMesh(this);
  8454. if (!doNotRecurse) {
  8455. // Particles
  8456. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8457. if (this.getScene().particleSystems[index].emitter === this) {
  8458. this.getScene().particleSystems[index].dispose();
  8459. index--;
  8460. }
  8461. }
  8462. // Children
  8463. var objects = this.getScene().meshes.slice(0);
  8464. for (index = 0; index < objects.length; index++) {
  8465. if (objects[index].parent === this) {
  8466. objects[index].dispose();
  8467. }
  8468. }
  8469. }
  8470. else {
  8471. for (index = 0; index < this.getScene().meshes.length; index++) {
  8472. var obj = this.getScene().meshes[index];
  8473. if (obj.parent === this) {
  8474. obj.parent = null;
  8475. obj.computeWorldMatrix(true);
  8476. }
  8477. }
  8478. }
  8479. this._onAfterWorldMatrixUpdate = [];
  8480. this._isDisposed = true;
  8481. // Callback
  8482. if (this.onDispose) {
  8483. this.onDispose();
  8484. }
  8485. };
  8486. // Statics
  8487. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8488. AbstractMesh._BILLBOARDMODE_X = 1;
  8489. AbstractMesh._BILLBOARDMODE_Y = 2;
  8490. AbstractMesh._BILLBOARDMODE_Z = 4;
  8491. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8492. return AbstractMesh;
  8493. })(BABYLON.Node);
  8494. BABYLON.AbstractMesh = AbstractMesh;
  8495. })(BABYLON || (BABYLON = {}));
  8496. var BABYLON;
  8497. (function (BABYLON) {
  8498. var Light = (function (_super) {
  8499. __extends(Light, _super);
  8500. function Light(name, scene) {
  8501. _super.call(this, name, scene);
  8502. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8503. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8504. this.intensity = 1.0;
  8505. this.range = Number.MAX_VALUE;
  8506. this.includeOnlyWithLayerMask = 0;
  8507. this.includedOnlyMeshes = new Array();
  8508. this.excludedMeshes = new Array();
  8509. this.excludeWithLayerMask = 0;
  8510. this._excludedMeshesIds = new Array();
  8511. this._includedOnlyMeshesIds = new Array();
  8512. scene.addLight(this);
  8513. }
  8514. Light.prototype.getShadowGenerator = function () {
  8515. return this._shadowGenerator;
  8516. };
  8517. Light.prototype.getAbsolutePosition = function () {
  8518. return BABYLON.Vector3.Zero();
  8519. };
  8520. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8521. };
  8522. Light.prototype._getWorldMatrix = function () {
  8523. return BABYLON.Matrix.Identity();
  8524. };
  8525. Light.prototype.canAffectMesh = function (mesh) {
  8526. if (!mesh) {
  8527. return true;
  8528. }
  8529. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8530. return false;
  8531. }
  8532. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8533. return false;
  8534. }
  8535. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8536. return false;
  8537. }
  8538. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8539. return false;
  8540. }
  8541. return true;
  8542. };
  8543. Light.prototype.getWorldMatrix = function () {
  8544. this._currentRenderId = this.getScene().getRenderId();
  8545. var worldMatrix = this._getWorldMatrix();
  8546. if (this.parent && this.parent.getWorldMatrix) {
  8547. if (!this._parentedWorldMatrix) {
  8548. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8549. }
  8550. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8551. this._markSyncedWithParent();
  8552. return this._parentedWorldMatrix;
  8553. }
  8554. return worldMatrix;
  8555. };
  8556. Light.prototype.dispose = function () {
  8557. if (this._shadowGenerator) {
  8558. this._shadowGenerator.dispose();
  8559. this._shadowGenerator = null;
  8560. }
  8561. // Animations
  8562. this.getScene().stopAnimation(this);
  8563. // Remove from scene
  8564. this.getScene().removeLight(this);
  8565. };
  8566. Light.prototype.serialize = function () {
  8567. var serializationObject = {};
  8568. serializationObject.name = this.name;
  8569. serializationObject.id = this.id;
  8570. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8571. if (this.intensity) {
  8572. serializationObject.intensity = this.intensity;
  8573. }
  8574. serializationObject.range = this.range;
  8575. serializationObject.diffuse = this.diffuse.asArray();
  8576. serializationObject.specular = this.specular.asArray();
  8577. return serializationObject;
  8578. };
  8579. Light.Parse = function (parsedLight, scene) {
  8580. var light;
  8581. switch (parsedLight.type) {
  8582. case 0:
  8583. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8584. break;
  8585. case 1:
  8586. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8587. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8588. break;
  8589. case 2:
  8590. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8591. break;
  8592. case 3:
  8593. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8594. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8595. break;
  8596. }
  8597. light.id = parsedLight.id;
  8598. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8599. if (parsedLight.intensity !== undefined) {
  8600. light.intensity = parsedLight.intensity;
  8601. }
  8602. if (parsedLight.range) {
  8603. light.range = parsedLight.range;
  8604. }
  8605. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8606. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8607. if (parsedLight.excludedMeshesIds) {
  8608. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8609. }
  8610. // Parent
  8611. if (parsedLight.parentId) {
  8612. light._waitingParentId = parsedLight.parentId;
  8613. }
  8614. if (parsedLight.includedOnlyMeshesIds) {
  8615. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8616. }
  8617. // Animations
  8618. if (parsedLight.animations) {
  8619. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8620. var parsedAnimation = parsedLight.animations[animationIndex];
  8621. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8622. }
  8623. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8624. }
  8625. if (parsedLight.autoAnimate) {
  8626. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8627. }
  8628. return light;
  8629. };
  8630. return Light;
  8631. })(BABYLON.Node);
  8632. BABYLON.Light = Light;
  8633. })(BABYLON || (BABYLON = {}));
  8634. var BABYLON;
  8635. (function (BABYLON) {
  8636. var PointLight = (function (_super) {
  8637. __extends(PointLight, _super);
  8638. function PointLight(name, position, scene) {
  8639. _super.call(this, name, scene);
  8640. this.position = position;
  8641. }
  8642. PointLight.prototype.getAbsolutePosition = function () {
  8643. return this.transformedPosition ? this.transformedPosition : this.position;
  8644. };
  8645. PointLight.prototype.computeTransformedPosition = function () {
  8646. if (this.parent && this.parent.getWorldMatrix) {
  8647. if (!this.transformedPosition) {
  8648. this.transformedPosition = BABYLON.Vector3.Zero();
  8649. }
  8650. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8651. return true;
  8652. }
  8653. return false;
  8654. };
  8655. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8656. if (this.parent && this.parent.getWorldMatrix) {
  8657. this.computeTransformedPosition();
  8658. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8659. return;
  8660. }
  8661. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8662. };
  8663. PointLight.prototype.needCube = function () {
  8664. return true;
  8665. };
  8666. PointLight.prototype.supportsVSM = function () {
  8667. return false;
  8668. };
  8669. PointLight.prototype.needRefreshPerFrame = function () {
  8670. return false;
  8671. };
  8672. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8673. switch (faceIndex) {
  8674. case 0:
  8675. return new BABYLON.Vector3(1, 0, 0);
  8676. case 1:
  8677. return new BABYLON.Vector3(-1, 0, 0);
  8678. case 2:
  8679. return new BABYLON.Vector3(0, -1, 0);
  8680. case 3:
  8681. return new BABYLON.Vector3(0, 1, 0);
  8682. case 4:
  8683. return new BABYLON.Vector3(0, 0, 1);
  8684. case 5:
  8685. return new BABYLON.Vector3(0, 0, -1);
  8686. }
  8687. return BABYLON.Vector3.Zero();
  8688. };
  8689. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8690. var activeCamera = this.getScene().activeCamera;
  8691. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8692. };
  8693. PointLight.prototype._getWorldMatrix = function () {
  8694. if (!this._worldMatrix) {
  8695. this._worldMatrix = BABYLON.Matrix.Identity();
  8696. }
  8697. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8698. return this._worldMatrix;
  8699. };
  8700. PointLight.prototype.serialize = function () {
  8701. var serializationObject = _super.prototype.serialize.call(this);
  8702. serializationObject.type = 0;
  8703. serializationObject.position = this.position.asArray();
  8704. return serializationObject;
  8705. };
  8706. return PointLight;
  8707. })(BABYLON.Light);
  8708. BABYLON.PointLight = PointLight;
  8709. })(BABYLON || (BABYLON = {}));
  8710. var BABYLON;
  8711. (function (BABYLON) {
  8712. var SpotLight = (function (_super) {
  8713. __extends(SpotLight, _super);
  8714. function SpotLight(name, position, direction, angle, exponent, scene) {
  8715. _super.call(this, name, scene);
  8716. this.position = position;
  8717. this.direction = direction;
  8718. this.angle = angle;
  8719. this.exponent = exponent;
  8720. }
  8721. SpotLight.prototype.getAbsolutePosition = function () {
  8722. return this.transformedPosition ? this.transformedPosition : this.position;
  8723. };
  8724. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8725. var activeCamera = this.getScene().activeCamera;
  8726. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8727. };
  8728. SpotLight.prototype.needCube = function () {
  8729. return false;
  8730. };
  8731. SpotLight.prototype.supportsVSM = function () {
  8732. return true;
  8733. };
  8734. SpotLight.prototype.needRefreshPerFrame = function () {
  8735. return false;
  8736. };
  8737. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8738. return this.direction;
  8739. };
  8740. SpotLight.prototype.setDirectionToTarget = function (target) {
  8741. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8742. return this.direction;
  8743. };
  8744. SpotLight.prototype.computeTransformedPosition = function () {
  8745. if (this.parent && this.parent.getWorldMatrix) {
  8746. if (!this.transformedPosition) {
  8747. this.transformedPosition = BABYLON.Vector3.Zero();
  8748. }
  8749. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8750. return true;
  8751. }
  8752. return false;
  8753. };
  8754. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8755. var normalizeDirection;
  8756. if (this.parent && this.parent.getWorldMatrix) {
  8757. if (!this._transformedDirection) {
  8758. this._transformedDirection = BABYLON.Vector3.Zero();
  8759. }
  8760. this.computeTransformedPosition();
  8761. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8762. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8763. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8764. }
  8765. else {
  8766. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8767. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8768. }
  8769. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8770. };
  8771. SpotLight.prototype._getWorldMatrix = function () {
  8772. if (!this._worldMatrix) {
  8773. this._worldMatrix = BABYLON.Matrix.Identity();
  8774. }
  8775. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8776. return this._worldMatrix;
  8777. };
  8778. SpotLight.prototype.serialize = function () {
  8779. var serializationObject = _super.prototype.serialize.call(this);
  8780. serializationObject.type = 2;
  8781. serializationObject.position = this.position.asArray();
  8782. serializationObject.direction = this.position.asArray();
  8783. serializationObject.angle = this.angle;
  8784. serializationObject.exponent = this.exponent;
  8785. return serializationObject;
  8786. };
  8787. return SpotLight;
  8788. })(BABYLON.Light);
  8789. BABYLON.SpotLight = SpotLight;
  8790. })(BABYLON || (BABYLON = {}));
  8791. var BABYLON;
  8792. (function (BABYLON) {
  8793. var HemisphericLight = (function (_super) {
  8794. __extends(HemisphericLight, _super);
  8795. function HemisphericLight(name, direction, scene) {
  8796. _super.call(this, name, scene);
  8797. this.direction = direction;
  8798. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8799. }
  8800. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8801. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8802. return this.direction;
  8803. };
  8804. HemisphericLight.prototype.getShadowGenerator = function () {
  8805. return null;
  8806. };
  8807. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8808. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8809. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8810. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8811. };
  8812. HemisphericLight.prototype._getWorldMatrix = function () {
  8813. if (!this._worldMatrix) {
  8814. this._worldMatrix = BABYLON.Matrix.Identity();
  8815. }
  8816. return this._worldMatrix;
  8817. };
  8818. HemisphericLight.prototype.serialize = function () {
  8819. var serializationObject = _super.prototype.serialize.call(this);
  8820. serializationObject.type = 3;
  8821. serializationObject.direction = this.direction.asArray();
  8822. serializationObject.groundColor = this.groundColor.asArray();
  8823. return serializationObject;
  8824. };
  8825. return HemisphericLight;
  8826. })(BABYLON.Light);
  8827. BABYLON.HemisphericLight = HemisphericLight;
  8828. })(BABYLON || (BABYLON = {}));
  8829. var BABYLON;
  8830. (function (BABYLON) {
  8831. var DirectionalLight = (function (_super) {
  8832. __extends(DirectionalLight, _super);
  8833. function DirectionalLight(name, direction, scene) {
  8834. _super.call(this, name, scene);
  8835. this.direction = direction;
  8836. this.shadowOrthoScale = 0.5;
  8837. this.autoUpdateExtends = true;
  8838. // Cache
  8839. this._orthoLeft = Number.MAX_VALUE;
  8840. this._orthoRight = Number.MIN_VALUE;
  8841. this._orthoTop = Number.MIN_VALUE;
  8842. this._orthoBottom = Number.MAX_VALUE;
  8843. this.position = direction.scale(-1);
  8844. }
  8845. DirectionalLight.prototype.getAbsolutePosition = function () {
  8846. return this.transformedPosition ? this.transformedPosition : this.position;
  8847. };
  8848. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8849. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8850. return this.direction;
  8851. };
  8852. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8853. var activeCamera = this.getScene().activeCamera;
  8854. // Check extends
  8855. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8856. var tempVector3 = BABYLON.Vector3.Zero();
  8857. this._orthoLeft = Number.MAX_VALUE;
  8858. this._orthoRight = Number.MIN_VALUE;
  8859. this._orthoTop = Number.MIN_VALUE;
  8860. this._orthoBottom = Number.MAX_VALUE;
  8861. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8862. var mesh = renderList[meshIndex];
  8863. if (!mesh) {
  8864. continue;
  8865. }
  8866. var boundingInfo = mesh.getBoundingInfo();
  8867. if (!boundingInfo) {
  8868. continue;
  8869. }
  8870. var boundingBox = boundingInfo.boundingBox;
  8871. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8872. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8873. if (tempVector3.x < this._orthoLeft)
  8874. this._orthoLeft = tempVector3.x;
  8875. if (tempVector3.y < this._orthoBottom)
  8876. this._orthoBottom = tempVector3.y;
  8877. if (tempVector3.x > this._orthoRight)
  8878. this._orthoRight = tempVector3.x;
  8879. if (tempVector3.y > this._orthoTop)
  8880. this._orthoTop = tempVector3.y;
  8881. }
  8882. }
  8883. }
  8884. var xOffset = this._orthoRight - this._orthoLeft;
  8885. var yOffset = this._orthoTop - this._orthoBottom;
  8886. 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);
  8887. };
  8888. DirectionalLight.prototype.supportsVSM = function () {
  8889. return true;
  8890. };
  8891. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8892. return true;
  8893. };
  8894. DirectionalLight.prototype.needCube = function () {
  8895. return false;
  8896. };
  8897. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8898. return this.direction;
  8899. };
  8900. DirectionalLight.prototype.computeTransformedPosition = function () {
  8901. if (this.parent && this.parent.getWorldMatrix) {
  8902. if (!this.transformedPosition) {
  8903. this.transformedPosition = BABYLON.Vector3.Zero();
  8904. }
  8905. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8906. return true;
  8907. }
  8908. return false;
  8909. };
  8910. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8911. if (this.parent && this.parent.getWorldMatrix) {
  8912. if (!this._transformedDirection) {
  8913. this._transformedDirection = BABYLON.Vector3.Zero();
  8914. }
  8915. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8916. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8917. return;
  8918. }
  8919. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8920. };
  8921. DirectionalLight.prototype._getWorldMatrix = function () {
  8922. if (!this._worldMatrix) {
  8923. this._worldMatrix = BABYLON.Matrix.Identity();
  8924. }
  8925. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8926. return this._worldMatrix;
  8927. };
  8928. DirectionalLight.prototype.serialize = function () {
  8929. var serializationObject = _super.prototype.serialize.call(this);
  8930. serializationObject.type = 1;
  8931. serializationObject.position = this.position.asArray();
  8932. serializationObject.direction = this.direction.asArray();
  8933. return serializationObject;
  8934. };
  8935. return DirectionalLight;
  8936. })(BABYLON.Light);
  8937. BABYLON.DirectionalLight = DirectionalLight;
  8938. })(BABYLON || (BABYLON = {}));
  8939. var BABYLON;
  8940. (function (BABYLON) {
  8941. var ShadowGenerator = (function () {
  8942. function ShadowGenerator(mapSize, light) {
  8943. var _this = this;
  8944. // Members
  8945. this._filter = ShadowGenerator.FILTER_NONE;
  8946. this.blurScale = 2;
  8947. this._blurBoxOffset = 0;
  8948. this._bias = 0.00005;
  8949. this._lightDirection = BABYLON.Vector3.Zero();
  8950. this.forceBackFacesOnly = false;
  8951. this._darkness = 0;
  8952. this._transparencyShadow = false;
  8953. this._viewMatrix = BABYLON.Matrix.Zero();
  8954. this._projectionMatrix = BABYLON.Matrix.Zero();
  8955. this._transformMatrix = BABYLON.Matrix.Zero();
  8956. this._worldViewProjection = BABYLON.Matrix.Zero();
  8957. this._currentFaceIndex = 0;
  8958. this._currentFaceIndexCache = 0;
  8959. this._light = light;
  8960. this._scene = light.getScene();
  8961. this._mapSize = mapSize;
  8962. light._shadowGenerator = this;
  8963. // Render target
  8964. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8965. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8966. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8967. this._shadowMap.anisotropicFilteringLevel = 1;
  8968. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8969. this._shadowMap.renderParticles = false;
  8970. this._shadowMap.onBeforeRender = function (faceIndex) {
  8971. _this._currentFaceIndex = faceIndex;
  8972. };
  8973. this._shadowMap.onAfterUnbind = function () {
  8974. if (!_this.useBlurVarianceShadowMap) {
  8975. return;
  8976. }
  8977. if (!_this._shadowMap2) {
  8978. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8979. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8980. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8981. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8982. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8983. _this._downSamplePostprocess.onApply = function (effect) {
  8984. effect.setTexture("textureSampler", _this._shadowMap);
  8985. };
  8986. _this.blurBoxOffset = 1;
  8987. }
  8988. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8989. };
  8990. // Custom render function
  8991. var renderSubMesh = function (subMesh) {
  8992. var mesh = subMesh.getRenderingMesh();
  8993. var scene = _this._scene;
  8994. var engine = scene.getEngine();
  8995. // Culling
  8996. engine.setState(subMesh.getMaterial().backFaceCulling);
  8997. // Managing instances
  8998. var batch = mesh._getInstancesRenderList(subMesh._id);
  8999. if (batch.mustReturn) {
  9000. return;
  9001. }
  9002. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9003. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9004. engine.enableEffect(_this._effect);
  9005. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9006. var material = subMesh.getMaterial();
  9007. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9008. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9009. if (_this.getLight().needCube()) {
  9010. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9011. }
  9012. // Alpha test
  9013. if (material && material.needAlphaTesting()) {
  9014. var alphaTexture = material.getAlphaTestTexture();
  9015. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9016. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9017. }
  9018. // Bones
  9019. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9020. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9021. }
  9022. if (_this.forceBackFacesOnly) {
  9023. engine.setState(true, 0, false, true);
  9024. }
  9025. // Draw
  9026. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9027. if (_this.forceBackFacesOnly) {
  9028. engine.setState(true, 0, false, false);
  9029. }
  9030. }
  9031. else {
  9032. // Need to reset refresh rate of the shadowMap
  9033. _this._shadowMap.resetRefreshCounter();
  9034. }
  9035. };
  9036. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9037. var index;
  9038. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9039. renderSubMesh(opaqueSubMeshes.data[index]);
  9040. }
  9041. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9042. renderSubMesh(alphaTestSubMeshes.data[index]);
  9043. }
  9044. if (_this._transparencyShadow) {
  9045. for (index = 0; index < transparentSubMeshes.length; index++) {
  9046. renderSubMesh(transparentSubMeshes.data[index]);
  9047. }
  9048. }
  9049. };
  9050. this._shadowMap.onClear = function (engine) {
  9051. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9052. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9053. }
  9054. else {
  9055. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9056. }
  9057. };
  9058. }
  9059. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9060. // Static
  9061. get: function () {
  9062. return ShadowGenerator._FILTER_NONE;
  9063. },
  9064. enumerable: true,
  9065. configurable: true
  9066. });
  9067. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9068. get: function () {
  9069. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9070. },
  9071. enumerable: true,
  9072. configurable: true
  9073. });
  9074. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9075. get: function () {
  9076. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9082. get: function () {
  9083. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9084. },
  9085. enumerable: true,
  9086. configurable: true
  9087. });
  9088. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9089. get: function () {
  9090. return this._bias;
  9091. },
  9092. set: function (bias) {
  9093. this._bias = bias;
  9094. },
  9095. enumerable: true,
  9096. configurable: true
  9097. });
  9098. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9099. get: function () {
  9100. return this._blurBoxOffset;
  9101. },
  9102. set: function (value) {
  9103. var _this = this;
  9104. if (this._blurBoxOffset === value) {
  9105. return;
  9106. }
  9107. this._blurBoxOffset = value;
  9108. if (this._boxBlurPostprocess) {
  9109. this._boxBlurPostprocess.dispose();
  9110. }
  9111. 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);
  9112. this._boxBlurPostprocess.onApply = function (effect) {
  9113. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9114. };
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9120. get: function () {
  9121. return this._filter;
  9122. },
  9123. set: function (value) {
  9124. if (this._filter === value) {
  9125. return;
  9126. }
  9127. this._filter = value;
  9128. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9129. this._shadowMap.anisotropicFilteringLevel = 16;
  9130. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9131. }
  9132. else {
  9133. this._shadowMap.anisotropicFilteringLevel = 1;
  9134. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9135. }
  9136. },
  9137. enumerable: true,
  9138. configurable: true
  9139. });
  9140. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9141. get: function () {
  9142. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9143. },
  9144. set: function (value) {
  9145. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9146. },
  9147. enumerable: true,
  9148. configurable: true
  9149. });
  9150. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9151. get: function () {
  9152. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9153. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9154. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9155. },
  9156. set: function (value) {
  9157. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9158. },
  9159. enumerable: true,
  9160. configurable: true
  9161. });
  9162. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9163. get: function () {
  9164. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9165. },
  9166. set: function (value) {
  9167. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9168. },
  9169. enumerable: true,
  9170. configurable: true
  9171. });
  9172. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9173. var defines = [];
  9174. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9175. defines.push("#define VSM");
  9176. }
  9177. if (this.getLight().needCube()) {
  9178. defines.push("#define CUBEMAP");
  9179. }
  9180. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9181. var mesh = subMesh.getMesh();
  9182. var material = subMesh.getMaterial();
  9183. // Alpha test
  9184. if (material && material.needAlphaTesting()) {
  9185. defines.push("#define ALPHATEST");
  9186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9187. attribs.push(BABYLON.VertexBuffer.UVKind);
  9188. defines.push("#define UV1");
  9189. }
  9190. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9192. defines.push("#define UV2");
  9193. }
  9194. }
  9195. // Bones
  9196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9199. if (mesh.numBoneInfluencers > 4) {
  9200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9202. }
  9203. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9204. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9205. }
  9206. else {
  9207. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9208. }
  9209. // Instances
  9210. if (useInstances) {
  9211. defines.push("#define INSTANCES");
  9212. attribs.push("world0");
  9213. attribs.push("world1");
  9214. attribs.push("world2");
  9215. attribs.push("world3");
  9216. }
  9217. // Get correct effect
  9218. var join = defines.join("\n");
  9219. if (this._cachedDefines !== join) {
  9220. this._cachedDefines = join;
  9221. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9222. }
  9223. return this._effect.isReady();
  9224. };
  9225. ShadowGenerator.prototype.getShadowMap = function () {
  9226. return this._shadowMap;
  9227. };
  9228. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9229. if (this._shadowMap2) {
  9230. return this._shadowMap2;
  9231. }
  9232. return this._shadowMap;
  9233. };
  9234. ShadowGenerator.prototype.getLight = function () {
  9235. return this._light;
  9236. };
  9237. // Methods
  9238. ShadowGenerator.prototype.getTransformMatrix = function () {
  9239. var scene = this._scene;
  9240. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9241. return this._transformMatrix;
  9242. }
  9243. this._currentRenderID = scene.getRenderId();
  9244. this._currentFaceIndexCache = this._currentFaceIndex;
  9245. var lightPosition = this._light.position;
  9246. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9247. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9248. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9249. }
  9250. if (this._light.computeTransformedPosition()) {
  9251. lightPosition = this._light.transformedPosition;
  9252. }
  9253. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9254. this._cachedPosition = lightPosition.clone();
  9255. this._cachedDirection = this._lightDirection.clone();
  9256. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9257. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9258. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9259. }
  9260. return this._transformMatrix;
  9261. };
  9262. ShadowGenerator.prototype.getDarkness = function () {
  9263. return this._darkness;
  9264. };
  9265. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9266. if (darkness >= 1.0)
  9267. this._darkness = 1.0;
  9268. else if (darkness <= 0.0)
  9269. this._darkness = 0.0;
  9270. else
  9271. this._darkness = darkness;
  9272. };
  9273. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9274. this._transparencyShadow = hasShadow;
  9275. };
  9276. ShadowGenerator.prototype._packHalf = function (depth) {
  9277. var scale = depth * 255.0;
  9278. var fract = scale - Math.floor(scale);
  9279. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9280. };
  9281. ShadowGenerator.prototype.dispose = function () {
  9282. this._shadowMap.dispose();
  9283. if (this._shadowMap2) {
  9284. this._shadowMap2.dispose();
  9285. }
  9286. if (this._downSamplePostprocess) {
  9287. this._downSamplePostprocess.dispose();
  9288. }
  9289. if (this._boxBlurPostprocess) {
  9290. this._boxBlurPostprocess.dispose();
  9291. }
  9292. };
  9293. ShadowGenerator.prototype.serialize = function () {
  9294. var serializationObject = {};
  9295. serializationObject.lightId = this._light.id;
  9296. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9297. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9298. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9299. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9300. serializationObject.renderList = [];
  9301. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9302. var mesh = this.getShadowMap().renderList[meshIndex];
  9303. serializationObject.renderList.push(mesh.id);
  9304. }
  9305. return serializationObject;
  9306. };
  9307. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9308. //casting to point light, as light is missing the position attr and typescript complains.
  9309. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9310. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9311. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9312. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9313. shadowGenerator.getShadowMap().renderList.push(mesh);
  9314. }
  9315. if (parsedShadowGenerator.usePoissonSampling) {
  9316. shadowGenerator.usePoissonSampling = true;
  9317. }
  9318. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9319. shadowGenerator.useVarianceShadowMap = true;
  9320. }
  9321. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9322. shadowGenerator.useBlurVarianceShadowMap = true;
  9323. if (parsedShadowGenerator.blurScale) {
  9324. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9325. }
  9326. if (parsedShadowGenerator.blurBoxOffset) {
  9327. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9328. }
  9329. }
  9330. if (parsedShadowGenerator.bias !== undefined) {
  9331. shadowGenerator.bias = parsedShadowGenerator.bias;
  9332. }
  9333. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9334. return shadowGenerator;
  9335. };
  9336. ShadowGenerator._FILTER_NONE = 0;
  9337. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9338. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9339. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9340. return ShadowGenerator;
  9341. })();
  9342. BABYLON.ShadowGenerator = ShadowGenerator;
  9343. })(BABYLON || (BABYLON = {}));
  9344. var BABYLON;
  9345. (function (BABYLON) {
  9346. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9347. if (boxMin.x > sphereCenter.x + sphereRadius)
  9348. return false;
  9349. if (sphereCenter.x - sphereRadius > boxMax.x)
  9350. return false;
  9351. if (boxMin.y > sphereCenter.y + sphereRadius)
  9352. return false;
  9353. if (sphereCenter.y - sphereRadius > boxMax.y)
  9354. return false;
  9355. if (boxMin.z > sphereCenter.z + sphereRadius)
  9356. return false;
  9357. if (sphereCenter.z - sphereRadius > boxMax.z)
  9358. return false;
  9359. return true;
  9360. };
  9361. var getLowestRoot = function (a, b, c, maxR) {
  9362. var determinant = b * b - 4.0 * a * c;
  9363. var result = { root: 0, found: false };
  9364. if (determinant < 0)
  9365. return result;
  9366. var sqrtD = Math.sqrt(determinant);
  9367. var r1 = (-b - sqrtD) / (2.0 * a);
  9368. var r2 = (-b + sqrtD) / (2.0 * a);
  9369. if (r1 > r2) {
  9370. var temp = r2;
  9371. r2 = r1;
  9372. r1 = temp;
  9373. }
  9374. if (r1 > 0 && r1 < maxR) {
  9375. result.root = r1;
  9376. result.found = true;
  9377. return result;
  9378. }
  9379. if (r2 > 0 && r2 < maxR) {
  9380. result.root = r2;
  9381. result.found = true;
  9382. return result;
  9383. }
  9384. return result;
  9385. };
  9386. var Collider = (function () {
  9387. function Collider() {
  9388. this.radius = new BABYLON.Vector3(1, 1, 1);
  9389. this.retry = 0;
  9390. this.basePointWorld = BABYLON.Vector3.Zero();
  9391. this.velocityWorld = BABYLON.Vector3.Zero();
  9392. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9393. this._collisionPoint = BABYLON.Vector3.Zero();
  9394. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9395. this._tempVector = BABYLON.Vector3.Zero();
  9396. this._tempVector2 = BABYLON.Vector3.Zero();
  9397. this._tempVector3 = BABYLON.Vector3.Zero();
  9398. this._tempVector4 = BABYLON.Vector3.Zero();
  9399. this._edge = BABYLON.Vector3.Zero();
  9400. this._baseToVertex = BABYLON.Vector3.Zero();
  9401. this._destinationPoint = BABYLON.Vector3.Zero();
  9402. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9403. this._displacementVector = BABYLON.Vector3.Zero();
  9404. }
  9405. // Methods
  9406. Collider.prototype._initialize = function (source, dir, e) {
  9407. this.velocity = dir;
  9408. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9409. this.basePoint = source;
  9410. source.multiplyToRef(this.radius, this.basePointWorld);
  9411. dir.multiplyToRef(this.radius, this.velocityWorld);
  9412. this.velocityWorldLength = this.velocityWorld.length();
  9413. this.epsilon = e;
  9414. this.collisionFound = false;
  9415. };
  9416. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9417. pa.subtractToRef(point, this._tempVector);
  9418. pb.subtractToRef(point, this._tempVector2);
  9419. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9420. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9421. if (d < 0)
  9422. return false;
  9423. pc.subtractToRef(point, this._tempVector3);
  9424. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9425. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9426. if (d < 0)
  9427. return false;
  9428. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9429. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9430. return d >= 0;
  9431. };
  9432. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9433. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9434. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9435. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9436. return false;
  9437. }
  9438. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9439. return false;
  9440. return true;
  9441. };
  9442. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9443. var t0;
  9444. var embeddedInPlane = false;
  9445. //defensive programming, actually not needed.
  9446. if (!trianglePlaneArray) {
  9447. trianglePlaneArray = [];
  9448. }
  9449. if (!trianglePlaneArray[faceIndex]) {
  9450. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9451. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9452. }
  9453. var trianglePlane = trianglePlaneArray[faceIndex];
  9454. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9455. return;
  9456. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9457. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9458. if (normalDotVelocity == 0) {
  9459. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9460. return;
  9461. embeddedInPlane = true;
  9462. t0 = 0;
  9463. }
  9464. else {
  9465. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9466. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9467. if (t0 > t1) {
  9468. var temp = t1;
  9469. t1 = t0;
  9470. t0 = temp;
  9471. }
  9472. if (t0 > 1.0 || t1 < 0.0)
  9473. return;
  9474. if (t0 < 0)
  9475. t0 = 0;
  9476. if (t0 > 1.0)
  9477. t0 = 1.0;
  9478. }
  9479. this._collisionPoint.copyFromFloats(0, 0, 0);
  9480. var found = false;
  9481. var t = 1.0;
  9482. if (!embeddedInPlane) {
  9483. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9484. this.velocity.scaleToRef(t0, this._tempVector);
  9485. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9486. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9487. found = true;
  9488. t = t0;
  9489. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9490. }
  9491. }
  9492. if (!found) {
  9493. var velocitySquaredLength = this.velocity.lengthSquared();
  9494. var a = velocitySquaredLength;
  9495. this.basePoint.subtractToRef(p1, this._tempVector);
  9496. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9497. var c = this._tempVector.lengthSquared() - 1.0;
  9498. var lowestRoot = getLowestRoot(a, b, c, t);
  9499. if (lowestRoot.found) {
  9500. t = lowestRoot.root;
  9501. found = true;
  9502. this._collisionPoint.copyFrom(p1);
  9503. }
  9504. this.basePoint.subtractToRef(p2, this._tempVector);
  9505. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9506. c = this._tempVector.lengthSquared() - 1.0;
  9507. lowestRoot = getLowestRoot(a, b, c, t);
  9508. if (lowestRoot.found) {
  9509. t = lowestRoot.root;
  9510. found = true;
  9511. this._collisionPoint.copyFrom(p2);
  9512. }
  9513. this.basePoint.subtractToRef(p3, this._tempVector);
  9514. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9515. c = this._tempVector.lengthSquared() - 1.0;
  9516. lowestRoot = getLowestRoot(a, b, c, t);
  9517. if (lowestRoot.found) {
  9518. t = lowestRoot.root;
  9519. found = true;
  9520. this._collisionPoint.copyFrom(p3);
  9521. }
  9522. p2.subtractToRef(p1, this._edge);
  9523. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9524. var edgeSquaredLength = this._edge.lengthSquared();
  9525. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9526. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9527. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9528. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9529. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9530. lowestRoot = getLowestRoot(a, b, c, t);
  9531. if (lowestRoot.found) {
  9532. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9533. if (f >= 0.0 && f <= 1.0) {
  9534. t = lowestRoot.root;
  9535. found = true;
  9536. this._edge.scaleInPlace(f);
  9537. p1.addToRef(this._edge, this._collisionPoint);
  9538. }
  9539. }
  9540. p3.subtractToRef(p2, this._edge);
  9541. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9542. edgeSquaredLength = this._edge.lengthSquared();
  9543. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9544. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9545. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9546. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9547. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9548. lowestRoot = getLowestRoot(a, b, c, t);
  9549. if (lowestRoot.found) {
  9550. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9551. if (f >= 0.0 && f <= 1.0) {
  9552. t = lowestRoot.root;
  9553. found = true;
  9554. this._edge.scaleInPlace(f);
  9555. p2.addToRef(this._edge, this._collisionPoint);
  9556. }
  9557. }
  9558. p1.subtractToRef(p3, this._edge);
  9559. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9560. edgeSquaredLength = this._edge.lengthSquared();
  9561. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9562. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9563. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9564. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9565. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9566. lowestRoot = getLowestRoot(a, b, c, t);
  9567. if (lowestRoot.found) {
  9568. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9569. if (f >= 0.0 && f <= 1.0) {
  9570. t = lowestRoot.root;
  9571. found = true;
  9572. this._edge.scaleInPlace(f);
  9573. p3.addToRef(this._edge, this._collisionPoint);
  9574. }
  9575. }
  9576. }
  9577. if (found) {
  9578. var distToCollision = t * this.velocity.length();
  9579. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9580. if (!this.intersectionPoint) {
  9581. this.intersectionPoint = this._collisionPoint.clone();
  9582. }
  9583. else {
  9584. this.intersectionPoint.copyFrom(this._collisionPoint);
  9585. }
  9586. this.nearestDistance = distToCollision;
  9587. this.collisionFound = true;
  9588. }
  9589. }
  9590. };
  9591. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9592. for (var i = indexStart; i < indexEnd; i += 3) {
  9593. var p1 = pts[indices[i] - decal];
  9594. var p2 = pts[indices[i + 1] - decal];
  9595. var p3 = pts[indices[i + 2] - decal];
  9596. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9597. }
  9598. };
  9599. Collider.prototype._getResponse = function (pos, vel) {
  9600. pos.addToRef(vel, this._destinationPoint);
  9601. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9602. this.basePoint.addToRef(vel, pos);
  9603. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9604. this._slidePlaneNormal.normalize();
  9605. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9606. pos.addInPlace(this._displacementVector);
  9607. this.intersectionPoint.addInPlace(this._displacementVector);
  9608. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9609. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9610. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9611. };
  9612. return Collider;
  9613. })();
  9614. BABYLON.Collider = Collider;
  9615. })(BABYLON || (BABYLON = {}));
  9616. var BABYLON;
  9617. (function (BABYLON) {
  9618. //WebWorker code will be inserted to this variable.
  9619. BABYLON.CollisionWorker = "";
  9620. (function (WorkerTaskType) {
  9621. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9622. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9623. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9624. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9625. var WorkerTaskType = BABYLON.WorkerTaskType;
  9626. (function (WorkerReplyType) {
  9627. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9628. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9629. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9630. var WorkerReplyType = BABYLON.WorkerReplyType;
  9631. var CollisionCoordinatorWorker = (function () {
  9632. function CollisionCoordinatorWorker() {
  9633. var _this = this;
  9634. this._scaledPosition = BABYLON.Vector3.Zero();
  9635. this._scaledVelocity = BABYLON.Vector3.Zero();
  9636. this.onMeshUpdated = function (mesh) {
  9637. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9638. };
  9639. this.onGeometryUpdated = function (geometry) {
  9640. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9641. };
  9642. this._afterRender = function () {
  9643. if (!_this._init)
  9644. return;
  9645. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9646. return;
  9647. }
  9648. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9649. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9650. if (_this._runningUpdated > 4) {
  9651. return;
  9652. }
  9653. ++_this._runningUpdated;
  9654. var payload = {
  9655. updatedMeshes: _this._addUpdateMeshesList,
  9656. updatedGeometries: _this._addUpdateGeometriesList,
  9657. removedGeometries: _this._toRemoveGeometryArray,
  9658. removedMeshes: _this._toRemoveMeshesArray
  9659. };
  9660. var message = {
  9661. payload: payload,
  9662. taskType: WorkerTaskType.UPDATE
  9663. };
  9664. var serializable = [];
  9665. for (var id in payload.updatedGeometries) {
  9666. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9667. //prepare transferables
  9668. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9669. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9670. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9671. }
  9672. }
  9673. _this._worker.postMessage(message, serializable);
  9674. _this._addUpdateMeshesList = {};
  9675. _this._addUpdateGeometriesList = {};
  9676. _this._toRemoveGeometryArray = [];
  9677. _this._toRemoveMeshesArray = [];
  9678. };
  9679. this._onMessageFromWorker = function (e) {
  9680. var returnData = e.data;
  9681. if (returnData.error != WorkerReplyType.SUCCESS) {
  9682. //TODO what errors can be returned from the worker?
  9683. BABYLON.Tools.Warn("error returned from worker!");
  9684. return;
  9685. }
  9686. switch (returnData.taskType) {
  9687. case WorkerTaskType.INIT:
  9688. _this._init = true;
  9689. //Update the worked with ALL of the scene's current state
  9690. _this._scene.meshes.forEach(function (mesh) {
  9691. _this.onMeshAdded(mesh);
  9692. });
  9693. _this._scene.getGeometries().forEach(function (geometry) {
  9694. _this.onGeometryAdded(geometry);
  9695. });
  9696. break;
  9697. case WorkerTaskType.UPDATE:
  9698. _this._runningUpdated--;
  9699. break;
  9700. case WorkerTaskType.COLLIDE:
  9701. _this._runningCollisionTask = false;
  9702. var returnPayload = returnData.payload;
  9703. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9704. return;
  9705. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9706. //cleanup
  9707. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9708. break;
  9709. }
  9710. };
  9711. this._collisionsCallbackArray = [];
  9712. this._init = false;
  9713. this._runningUpdated = 0;
  9714. this._runningCollisionTask = false;
  9715. this._addUpdateMeshesList = {};
  9716. this._addUpdateGeometriesList = {};
  9717. this._toRemoveGeometryArray = [];
  9718. this._toRemoveMeshesArray = [];
  9719. }
  9720. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9721. if (!this._init)
  9722. return;
  9723. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9724. return;
  9725. position.divideToRef(collider.radius, this._scaledPosition);
  9726. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9727. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9728. var payload = {
  9729. collider: {
  9730. position: this._scaledPosition.asArray(),
  9731. velocity: this._scaledVelocity.asArray(),
  9732. radius: collider.radius.asArray()
  9733. },
  9734. collisionId: collisionIndex,
  9735. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9736. maximumRetry: maximumRetry
  9737. };
  9738. var message = {
  9739. payload: payload,
  9740. taskType: WorkerTaskType.COLLIDE
  9741. };
  9742. this._worker.postMessage(message);
  9743. };
  9744. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9745. this._scene = scene;
  9746. this._scene.registerAfterRender(this._afterRender);
  9747. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9748. this._worker = new Worker(workerUrl);
  9749. this._worker.onmessage = this._onMessageFromWorker;
  9750. var message = {
  9751. payload: {},
  9752. taskType: WorkerTaskType.INIT
  9753. };
  9754. this._worker.postMessage(message);
  9755. };
  9756. CollisionCoordinatorWorker.prototype.destroy = function () {
  9757. this._scene.unregisterAfterRender(this._afterRender);
  9758. this._worker.terminate();
  9759. };
  9760. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9761. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9762. this.onMeshUpdated(mesh);
  9763. };
  9764. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9765. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9766. };
  9767. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9768. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9769. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9770. this.onGeometryUpdated(geometry);
  9771. };
  9772. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9773. this._toRemoveGeometryArray.push(geometry.id);
  9774. };
  9775. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9776. var submeshes = [];
  9777. if (mesh.subMeshes) {
  9778. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9779. return {
  9780. position: idx,
  9781. verticesStart: sm.verticesStart,
  9782. verticesCount: sm.verticesCount,
  9783. indexStart: sm.indexStart,
  9784. indexCount: sm.indexCount,
  9785. hasMaterial: !!sm.getMaterial(),
  9786. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9787. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9788. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9789. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9790. };
  9791. });
  9792. }
  9793. var geometryId = null;
  9794. if (mesh instanceof BABYLON.Mesh) {
  9795. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9796. }
  9797. else if (mesh instanceof BABYLON.InstancedMesh) {
  9798. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9799. }
  9800. return {
  9801. uniqueId: mesh.uniqueId,
  9802. id: mesh.id,
  9803. name: mesh.name,
  9804. geometryId: geometryId,
  9805. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9806. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9807. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9808. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9809. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9810. subMeshes: submeshes,
  9811. checkCollisions: mesh.checkCollisions
  9812. };
  9813. };
  9814. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9815. return {
  9816. id: geometry.id,
  9817. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9818. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9819. indices: new Int32Array(geometry.getIndices() || []),
  9820. };
  9821. };
  9822. return CollisionCoordinatorWorker;
  9823. })();
  9824. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9825. var CollisionCoordinatorLegacy = (function () {
  9826. function CollisionCoordinatorLegacy() {
  9827. this._scaledPosition = BABYLON.Vector3.Zero();
  9828. this._scaledVelocity = BABYLON.Vector3.Zero();
  9829. this._finalPosition = BABYLON.Vector3.Zero();
  9830. }
  9831. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9832. position.divideToRef(collider.radius, this._scaledPosition);
  9833. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9834. collider.collidedMesh = null;
  9835. collider.retry = 0;
  9836. collider.initialVelocity = this._scaledVelocity;
  9837. collider.initialPosition = this._scaledPosition;
  9838. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9839. this._finalPosition.multiplyInPlace(collider.radius);
  9840. //run the callback
  9841. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9842. };
  9843. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9844. this._scene = scene;
  9845. };
  9846. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9847. //Legacy need no destruction method.
  9848. };
  9849. //No update in legacy mode
  9850. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9851. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9852. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9853. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9854. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9855. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9856. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9857. if (excludedMesh === void 0) { excludedMesh = null; }
  9858. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9859. if (collider.retry >= maximumRetry) {
  9860. finalPosition.copyFrom(position);
  9861. return;
  9862. }
  9863. collider._initialize(position, velocity, closeDistance);
  9864. // Check all meshes
  9865. for (var index = 0; index < this._scene.meshes.length; index++) {
  9866. var mesh = this._scene.meshes[index];
  9867. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9868. mesh._checkCollision(collider);
  9869. }
  9870. }
  9871. if (!collider.collisionFound) {
  9872. position.addToRef(velocity, finalPosition);
  9873. return;
  9874. }
  9875. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9876. collider._getResponse(position, velocity);
  9877. }
  9878. if (velocity.length() <= closeDistance) {
  9879. finalPosition.copyFrom(position);
  9880. return;
  9881. }
  9882. collider.retry++;
  9883. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9884. };
  9885. return CollisionCoordinatorLegacy;
  9886. })();
  9887. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9888. })(BABYLON || (BABYLON = {}));
  9889. var BABYLON;
  9890. (function (BABYLON) {
  9891. var VRCameraMetrics = (function () {
  9892. function VRCameraMetrics() {
  9893. this.compensateDistortion = true;
  9894. }
  9895. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9896. get: function () {
  9897. return this.hResolution / (2 * this.vResolution);
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9903. get: function () {
  9904. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9910. get: function () {
  9911. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9912. var h = (4 * meters) / this.hScreenSize;
  9913. return BABYLON.Matrix.Translation(h, 0, 0);
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9919. get: function () {
  9920. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9921. var h = (4 * meters) / this.hScreenSize;
  9922. return BABYLON.Matrix.Translation(-h, 0, 0);
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9928. get: function () {
  9929. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9935. get: function () {
  9936. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. VRCameraMetrics.GetDefault = function () {
  9942. var result = new VRCameraMetrics();
  9943. result.hResolution = 1280;
  9944. result.vResolution = 800;
  9945. result.hScreenSize = 0.149759993;
  9946. result.vScreenSize = 0.0935999975;
  9947. result.vScreenCenter = 0.0467999987,
  9948. result.eyeToScreenDistance = 0.0410000011;
  9949. result.lensSeparationDistance = 0.0635000020;
  9950. result.interpupillaryDistance = 0.0640000030;
  9951. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9952. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9953. result.postProcessScaleFactor = 1.714605507808412;
  9954. result.lensCenterOffset = 0.151976421;
  9955. return result;
  9956. };
  9957. return VRCameraMetrics;
  9958. })();
  9959. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9960. var Camera = (function (_super) {
  9961. __extends(Camera, _super);
  9962. function Camera(name, position, scene) {
  9963. _super.call(this, name, scene);
  9964. this.position = position;
  9965. // Members
  9966. this.upVector = BABYLON.Vector3.Up();
  9967. this.orthoLeft = null;
  9968. this.orthoRight = null;
  9969. this.orthoBottom = null;
  9970. this.orthoTop = null;
  9971. this.fov = 0.8;
  9972. this.minZ = 1.0;
  9973. this.maxZ = 10000.0;
  9974. this.inertia = 0.9;
  9975. this.mode = Camera.PERSPECTIVE_CAMERA;
  9976. this.isIntermediate = false;
  9977. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9978. this.layerMask = 0x0FFFFFFF;
  9979. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9980. // Camera rig members
  9981. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9982. this._rigCameras = new Array();
  9983. // Cache
  9984. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9985. this._projectionMatrix = new BABYLON.Matrix();
  9986. this._postProcesses = new Array();
  9987. this._postProcessesTakenIndices = [];
  9988. this._activeMeshes = new BABYLON.SmartArray(256);
  9989. this._globalPosition = BABYLON.Vector3.Zero();
  9990. scene.addCamera(this);
  9991. if (!scene.activeCamera) {
  9992. scene.activeCamera = this;
  9993. }
  9994. }
  9995. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9996. get: function () {
  9997. return Camera._PERSPECTIVE_CAMERA;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10003. get: function () {
  10004. return Camera._ORTHOGRAPHIC_CAMERA;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10010. get: function () {
  10011. return Camera._FOVMODE_VERTICAL_FIXED;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10017. get: function () {
  10018. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10024. get: function () {
  10025. return Camera._RIG_MODE_NONE;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10031. get: function () {
  10032. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10038. get: function () {
  10039. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10045. get: function () {
  10046. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10052. get: function () {
  10053. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10059. get: function () {
  10060. return Camera._RIG_MODE_VR;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(Camera.prototype, "globalPosition", {
  10066. get: function () {
  10067. return this._globalPosition;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Camera.prototype.getActiveMeshes = function () {
  10073. return this._activeMeshes;
  10074. };
  10075. Camera.prototype.isActiveMesh = function (mesh) {
  10076. return (this._activeMeshes.indexOf(mesh) !== -1);
  10077. };
  10078. //Cache
  10079. Camera.prototype._initCache = function () {
  10080. _super.prototype._initCache.call(this);
  10081. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10082. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10083. this._cache.mode = undefined;
  10084. this._cache.minZ = undefined;
  10085. this._cache.maxZ = undefined;
  10086. this._cache.fov = undefined;
  10087. this._cache.aspectRatio = undefined;
  10088. this._cache.orthoLeft = undefined;
  10089. this._cache.orthoRight = undefined;
  10090. this._cache.orthoBottom = undefined;
  10091. this._cache.orthoTop = undefined;
  10092. this._cache.renderWidth = undefined;
  10093. this._cache.renderHeight = undefined;
  10094. };
  10095. Camera.prototype._updateCache = function (ignoreParentClass) {
  10096. if (!ignoreParentClass) {
  10097. _super.prototype._updateCache.call(this);
  10098. }
  10099. var engine = this.getEngine();
  10100. this._cache.position.copyFrom(this.position);
  10101. this._cache.upVector.copyFrom(this.upVector);
  10102. this._cache.mode = this.mode;
  10103. this._cache.minZ = this.minZ;
  10104. this._cache.maxZ = this.maxZ;
  10105. this._cache.fov = this.fov;
  10106. this._cache.aspectRatio = engine.getAspectRatio(this);
  10107. this._cache.orthoLeft = this.orthoLeft;
  10108. this._cache.orthoRight = this.orthoRight;
  10109. this._cache.orthoBottom = this.orthoBottom;
  10110. this._cache.orthoTop = this.orthoTop;
  10111. this._cache.renderWidth = engine.getRenderWidth();
  10112. this._cache.renderHeight = engine.getRenderHeight();
  10113. };
  10114. Camera.prototype._updateFromScene = function () {
  10115. this.updateCache();
  10116. this._update();
  10117. };
  10118. // Synchronized
  10119. Camera.prototype._isSynchronized = function () {
  10120. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10121. };
  10122. Camera.prototype._isSynchronizedViewMatrix = function () {
  10123. if (!_super.prototype._isSynchronized.call(this))
  10124. return false;
  10125. return this._cache.position.equals(this.position)
  10126. && this._cache.upVector.equals(this.upVector)
  10127. && this.isSynchronizedWithParent();
  10128. };
  10129. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10130. var check = this._cache.mode === this.mode
  10131. && this._cache.minZ === this.minZ
  10132. && this._cache.maxZ === this.maxZ;
  10133. if (!check) {
  10134. return false;
  10135. }
  10136. var engine = this.getEngine();
  10137. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10138. check = this._cache.fov === this.fov
  10139. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10140. }
  10141. else {
  10142. check = this._cache.orthoLeft === this.orthoLeft
  10143. && this._cache.orthoRight === this.orthoRight
  10144. && this._cache.orthoBottom === this.orthoBottom
  10145. && this._cache.orthoTop === this.orthoTop
  10146. && this._cache.renderWidth === engine.getRenderWidth()
  10147. && this._cache.renderHeight === engine.getRenderHeight();
  10148. }
  10149. return check;
  10150. };
  10151. // Controls
  10152. Camera.prototype.attachControl = function (element) {
  10153. };
  10154. Camera.prototype.detachControl = function (element) {
  10155. };
  10156. Camera.prototype._update = function () {
  10157. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10158. this._updateRigCameras();
  10159. }
  10160. this._checkInputs();
  10161. };
  10162. Camera.prototype._checkInputs = function () {
  10163. };
  10164. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10165. if (insertAt === void 0) { insertAt = null; }
  10166. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10167. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10168. return 0;
  10169. }
  10170. if (insertAt == null || insertAt < 0) {
  10171. this._postProcesses.push(postProcess);
  10172. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10173. return this._postProcesses.length - 1;
  10174. }
  10175. var add = 0;
  10176. var i;
  10177. var start;
  10178. if (this._postProcesses[insertAt]) {
  10179. start = this._postProcesses.length - 1;
  10180. for (i = start; i >= insertAt + 1; --i) {
  10181. this._postProcesses[i + 1] = this._postProcesses[i];
  10182. }
  10183. add = 1;
  10184. }
  10185. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10186. if (this._postProcessesTakenIndices[i] < insertAt) {
  10187. continue;
  10188. }
  10189. start = this._postProcessesTakenIndices.length - 1;
  10190. for (var j = start; j >= i; --j) {
  10191. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10192. }
  10193. this._postProcessesTakenIndices[i] = insertAt;
  10194. break;
  10195. }
  10196. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10197. this._postProcessesTakenIndices.push(insertAt);
  10198. }
  10199. var result = insertAt + add;
  10200. this._postProcesses[result] = postProcess;
  10201. return result;
  10202. };
  10203. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10204. if (atIndices === void 0) { atIndices = null; }
  10205. var result = [];
  10206. var i;
  10207. var index;
  10208. if (!atIndices) {
  10209. var length = this._postProcesses.length;
  10210. for (i = 0; i < length; i++) {
  10211. if (this._postProcesses[i] !== postProcess) {
  10212. continue;
  10213. }
  10214. delete this._postProcesses[i];
  10215. index = this._postProcessesTakenIndices.indexOf(i);
  10216. this._postProcessesTakenIndices.splice(index, 1);
  10217. }
  10218. }
  10219. else {
  10220. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10221. for (i = 0; i < atIndices.length; i++) {
  10222. var foundPostProcess = this._postProcesses[atIndices[i]];
  10223. if (foundPostProcess !== postProcess) {
  10224. result.push(i);
  10225. continue;
  10226. }
  10227. delete this._postProcesses[atIndices[i]];
  10228. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10229. this._postProcessesTakenIndices.splice(index, 1);
  10230. }
  10231. }
  10232. return result;
  10233. };
  10234. Camera.prototype.getWorldMatrix = function () {
  10235. if (!this._worldMatrix) {
  10236. this._worldMatrix = BABYLON.Matrix.Identity();
  10237. }
  10238. var viewMatrix = this.getViewMatrix();
  10239. viewMatrix.invertToRef(this._worldMatrix);
  10240. return this._worldMatrix;
  10241. };
  10242. Camera.prototype._getViewMatrix = function () {
  10243. return BABYLON.Matrix.Identity();
  10244. };
  10245. Camera.prototype.getViewMatrix = function (force) {
  10246. this._computedViewMatrix = this._computeViewMatrix(force);
  10247. if (!force && this._isSynchronizedViewMatrix()) {
  10248. return this._computedViewMatrix;
  10249. }
  10250. if (!this.parent || !this.parent.getWorldMatrix) {
  10251. this._globalPosition.copyFrom(this.position);
  10252. }
  10253. else {
  10254. if (!this._worldMatrix) {
  10255. this._worldMatrix = BABYLON.Matrix.Identity();
  10256. }
  10257. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10258. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10259. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10260. this._computedViewMatrix.invert();
  10261. this._markSyncedWithParent();
  10262. }
  10263. this._currentRenderId = this.getScene().getRenderId();
  10264. return this._computedViewMatrix;
  10265. };
  10266. Camera.prototype._computeViewMatrix = function (force) {
  10267. if (!force && this._isSynchronizedViewMatrix()) {
  10268. return this._computedViewMatrix;
  10269. }
  10270. this._computedViewMatrix = this._getViewMatrix();
  10271. this._currentRenderId = this.getScene().getRenderId();
  10272. return this._computedViewMatrix;
  10273. };
  10274. Camera.prototype.getProjectionMatrix = function (force) {
  10275. if (!force && this._isSynchronizedProjectionMatrix()) {
  10276. return this._projectionMatrix;
  10277. }
  10278. var engine = this.getEngine();
  10279. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10280. if (this.minZ <= 0) {
  10281. this.minZ = 0.1;
  10282. }
  10283. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10284. return this._projectionMatrix;
  10285. }
  10286. var halfWidth = engine.getRenderWidth() / 2.0;
  10287. var halfHeight = engine.getRenderHeight() / 2.0;
  10288. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10289. return this._projectionMatrix;
  10290. };
  10291. Camera.prototype.dispose = function () {
  10292. // Animations
  10293. this.getScene().stopAnimation(this);
  10294. // Remove from scene
  10295. this.getScene().removeCamera(this);
  10296. while (this._rigCameras.length > 0) {
  10297. this._rigCameras.pop().dispose();
  10298. }
  10299. // Postprocesses
  10300. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10301. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10302. }
  10303. };
  10304. // ---- Camera rigs section ----
  10305. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10306. while (this._rigCameras.length > 0) {
  10307. this._rigCameras.pop().dispose();
  10308. }
  10309. this.cameraRigMode = mode;
  10310. this._cameraRigParams = {};
  10311. switch (this.cameraRigMode) {
  10312. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10313. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10314. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10315. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10316. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10317. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10318. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10319. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10320. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10321. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10322. break;
  10323. }
  10324. var postProcesses = new Array();
  10325. switch (this.cameraRigMode) {
  10326. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10327. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10328. this._rigCameras[0].isIntermediate = true;
  10329. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10330. postProcesses[1].onApply = function (effect) {
  10331. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10332. };
  10333. break;
  10334. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10335. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10336. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10337. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10338. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10339. var secondCamIndex = 1 - firstCamIndex;
  10340. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10341. this._rigCameras[firstCamIndex].isIntermediate = true;
  10342. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10343. break;
  10344. case Camera.RIG_MODE_VR:
  10345. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10346. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10347. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10348. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10349. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10350. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10351. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10352. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10353. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10354. if (metrics.compensateDistortion) {
  10355. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10356. }
  10357. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10358. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10359. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10360. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10361. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10362. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10363. if (metrics.compensateDistortion) {
  10364. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10365. }
  10366. break;
  10367. }
  10368. this._update();
  10369. };
  10370. Camera.prototype._getVRProjectionMatrix = function () {
  10371. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10372. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10373. return this._projectionMatrix;
  10374. };
  10375. Camera.prototype.setCameraRigParameter = function (name, value) {
  10376. this._cameraRigParams[name] = value;
  10377. //provisionnally:
  10378. if (name === "interaxialDistance") {
  10379. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10380. }
  10381. };
  10382. /**
  10383. * May needs to be overridden by children so sub has required properties to be copied
  10384. */
  10385. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10386. return null;
  10387. };
  10388. /**
  10389. * May needs to be overridden by children
  10390. */
  10391. Camera.prototype._updateRigCameras = function () {
  10392. for (var i = 0; i < this._rigCameras.length; i++) {
  10393. this._rigCameras[i].minZ = this.minZ;
  10394. this._rigCameras[i].maxZ = this.maxZ;
  10395. this._rigCameras[i].fov = this.fov;
  10396. }
  10397. // only update viewport when ANAGLYPH
  10398. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10399. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10400. }
  10401. };
  10402. Camera.prototype.serialize = function () {
  10403. var serializationObject = {};
  10404. serializationObject.name = this.name;
  10405. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10406. serializationObject.id = this.id;
  10407. serializationObject.position = this.position.asArray();
  10408. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10409. // Parent
  10410. if (this.parent) {
  10411. serializationObject.parentId = this.parent.id;
  10412. }
  10413. serializationObject.fov = this.fov;
  10414. serializationObject.minZ = this.minZ;
  10415. serializationObject.maxZ = this.maxZ;
  10416. serializationObject.inertia = this.inertia;
  10417. // Animations
  10418. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10419. serializationObject.ranges = this.serializeAnimationRanges();
  10420. // Layer mask
  10421. serializationObject.layerMask = this.layerMask;
  10422. return serializationObject;
  10423. };
  10424. Camera.Parse = function (parsedCamera, scene) {
  10425. var camera;
  10426. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10427. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10428. var interaxial_distance;
  10429. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10430. var alpha = parsedCamera.alpha;
  10431. var beta = parsedCamera.beta;
  10432. var radius = parsedCamera.radius;
  10433. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10434. interaxial_distance = parsedCamera.interaxial_distance;
  10435. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10436. }
  10437. else {
  10438. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10439. }
  10440. }
  10441. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10442. interaxial_distance = parsedCamera.interaxial_distance;
  10443. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10444. }
  10445. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10446. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10447. }
  10448. else if (parsedCamera.type === "FollowCamera") {
  10449. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10450. camera.heightOffset = parsedCamera.heightOffset;
  10451. camera.radius = parsedCamera.radius;
  10452. camera.rotationOffset = parsedCamera.rotationOffset;
  10453. if (lockedTargetMesh)
  10454. camera.target = lockedTargetMesh;
  10455. }
  10456. else if (parsedCamera.type === "GamepadCamera") {
  10457. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10458. }
  10459. else if (parsedCamera.type === "TouchCamera") {
  10460. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10461. }
  10462. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10463. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10464. }
  10465. else if (parsedCamera.type === "WebVRFreeCamera") {
  10466. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10467. }
  10468. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10469. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10470. }
  10471. else {
  10472. // Touch Camera is the default value
  10473. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10474. }
  10475. // apply 3d rig, when found
  10476. if (parsedCamera.cameraRigMode) {
  10477. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10478. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10479. }
  10480. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10481. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10482. camera.lockedTarget = lockedTargetMesh;
  10483. }
  10484. camera.id = parsedCamera.id;
  10485. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10486. // Parent
  10487. if (parsedCamera.parentId) {
  10488. camera._waitingParentId = parsedCamera.parentId;
  10489. }
  10490. // Target
  10491. if (parsedCamera.target) {
  10492. if (camera.setTarget) {
  10493. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10494. }
  10495. else {
  10496. //For ArcRotate
  10497. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10498. }
  10499. }
  10500. else {
  10501. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10502. }
  10503. camera.fov = parsedCamera.fov;
  10504. camera.minZ = parsedCamera.minZ;
  10505. camera.maxZ = parsedCamera.maxZ;
  10506. camera.speed = parsedCamera.speed;
  10507. camera.inertia = parsedCamera.inertia;
  10508. camera.checkCollisions = parsedCamera.checkCollisions;
  10509. camera.applyGravity = parsedCamera.applyGravity;
  10510. if (parsedCamera.ellipsoid) {
  10511. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10512. }
  10513. // Animations
  10514. if (parsedCamera.animations) {
  10515. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10516. var parsedAnimation = parsedCamera.animations[animationIndex];
  10517. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10518. }
  10519. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10520. }
  10521. if (parsedCamera.autoAnimate) {
  10522. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10523. }
  10524. // Layer Mask
  10525. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10526. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10527. }
  10528. else {
  10529. camera.layerMask = 0x0FFFFFFF;
  10530. }
  10531. return camera;
  10532. };
  10533. // Statics
  10534. Camera._PERSPECTIVE_CAMERA = 0;
  10535. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10536. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10537. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10538. Camera._RIG_MODE_NONE = 0;
  10539. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10540. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10541. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10542. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10543. Camera._RIG_MODE_VR = 20;
  10544. return Camera;
  10545. })(BABYLON.Node);
  10546. BABYLON.Camera = Camera;
  10547. })(BABYLON || (BABYLON = {}));
  10548. var BABYLON;
  10549. (function (BABYLON) {
  10550. var TargetCamera = (function (_super) {
  10551. __extends(TargetCamera, _super);
  10552. function TargetCamera(name, position, scene) {
  10553. _super.call(this, name, position, scene);
  10554. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10555. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10556. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10557. this.speed = 2.0;
  10558. this.noRotationConstraint = false;
  10559. this.lockedTarget = null;
  10560. this._currentTarget = BABYLON.Vector3.Zero();
  10561. this._viewMatrix = BABYLON.Matrix.Zero();
  10562. this._camMatrix = BABYLON.Matrix.Zero();
  10563. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10564. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10565. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10566. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10567. this._lookAtTemp = BABYLON.Matrix.Zero();
  10568. this._tempMatrix = BABYLON.Matrix.Zero();
  10569. }
  10570. TargetCamera.prototype.getFrontPosition = function (distance) {
  10571. var direction = this.getTarget().subtract(this.position);
  10572. direction.normalize();
  10573. direction.scaleInPlace(distance);
  10574. return this.globalPosition.add(direction);
  10575. };
  10576. TargetCamera.prototype._getLockedTargetPosition = function () {
  10577. if (!this.lockedTarget) {
  10578. return null;
  10579. }
  10580. return this.lockedTarget.position || this.lockedTarget;
  10581. };
  10582. // Cache
  10583. TargetCamera.prototype._initCache = function () {
  10584. _super.prototype._initCache.call(this);
  10585. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10586. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10587. };
  10588. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10589. if (!ignoreParentClass) {
  10590. _super.prototype._updateCache.call(this);
  10591. }
  10592. var lockedTargetPosition = this._getLockedTargetPosition();
  10593. if (!lockedTargetPosition) {
  10594. this._cache.lockedTarget = null;
  10595. }
  10596. else {
  10597. if (!this._cache.lockedTarget) {
  10598. this._cache.lockedTarget = lockedTargetPosition.clone();
  10599. }
  10600. else {
  10601. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10602. }
  10603. }
  10604. this._cache.rotation.copyFrom(this.rotation);
  10605. };
  10606. // Synchronized
  10607. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10608. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10609. return false;
  10610. }
  10611. var lockedTargetPosition = this._getLockedTargetPosition();
  10612. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10613. && this._cache.rotation.equals(this.rotation);
  10614. };
  10615. // Methods
  10616. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10617. var engine = this.getEngine();
  10618. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10619. };
  10620. // Target
  10621. TargetCamera.prototype.setTarget = function (target) {
  10622. this.upVector.normalize();
  10623. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10624. this._camMatrix.invert();
  10625. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10626. var vDir = target.subtract(this.position);
  10627. if (vDir.x >= 0.0) {
  10628. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10629. }
  10630. else {
  10631. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10632. }
  10633. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10634. if (isNaN(this.rotation.x)) {
  10635. this.rotation.x = 0;
  10636. }
  10637. if (isNaN(this.rotation.y)) {
  10638. this.rotation.y = 0;
  10639. }
  10640. if (isNaN(this.rotation.z)) {
  10641. this.rotation.z = 0;
  10642. }
  10643. };
  10644. TargetCamera.prototype.getTarget = function () {
  10645. return this._currentTarget;
  10646. };
  10647. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10648. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10649. };
  10650. TargetCamera.prototype._updatePosition = function () {
  10651. this.position.addInPlace(this.cameraDirection);
  10652. };
  10653. TargetCamera.prototype._checkInputs = function () {
  10654. var needToMove = this._decideIfNeedsToMove();
  10655. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10656. // Move
  10657. if (needToMove) {
  10658. this._updatePosition();
  10659. }
  10660. // Rotate
  10661. if (needToRotate) {
  10662. this.rotation.x += this.cameraRotation.x;
  10663. this.rotation.y += this.cameraRotation.y;
  10664. if (!this.noRotationConstraint) {
  10665. var limit = (Math.PI / 2) * 0.95;
  10666. if (this.rotation.x > limit)
  10667. this.rotation.x = limit;
  10668. if (this.rotation.x < -limit)
  10669. this.rotation.x = -limit;
  10670. }
  10671. }
  10672. // Inertia
  10673. if (needToMove) {
  10674. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10675. this.cameraDirection.x = 0;
  10676. }
  10677. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10678. this.cameraDirection.y = 0;
  10679. }
  10680. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10681. this.cameraDirection.z = 0;
  10682. }
  10683. this.cameraDirection.scaleInPlace(this.inertia);
  10684. }
  10685. if (needToRotate) {
  10686. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10687. this.cameraRotation.x = 0;
  10688. }
  10689. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10690. this.cameraRotation.y = 0;
  10691. }
  10692. this.cameraRotation.scaleInPlace(this.inertia);
  10693. }
  10694. _super.prototype._checkInputs.call(this);
  10695. };
  10696. TargetCamera.prototype._getViewMatrix = function () {
  10697. if (!this.lockedTarget) {
  10698. // Compute
  10699. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10700. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10701. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10702. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10703. this._lookAtTemp.invert();
  10704. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10705. }
  10706. else {
  10707. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10708. }
  10709. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10710. // Computing target and final matrix
  10711. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10712. }
  10713. else {
  10714. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10715. }
  10716. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10717. return this._viewMatrix;
  10718. };
  10719. TargetCamera.prototype._getVRViewMatrix = function () {
  10720. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10721. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10722. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10723. // Computing target and final matrix
  10724. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10725. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10726. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10727. return this._viewMatrix;
  10728. };
  10729. /**
  10730. * @override
  10731. * Override Camera.createRigCamera
  10732. */
  10733. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10734. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10735. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10736. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10737. rigCamera._cameraRigParams = {};
  10738. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10739. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10740. }
  10741. return rigCamera;
  10742. }
  10743. return null;
  10744. };
  10745. /**
  10746. * @override
  10747. * Override Camera._updateRigCameras
  10748. */
  10749. TargetCamera.prototype._updateRigCameras = function () {
  10750. switch (this.cameraRigMode) {
  10751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10755. case BABYLON.Camera.RIG_MODE_VR:
  10756. var camLeft = this._rigCameras[0];
  10757. var camRight = this._rigCameras[1];
  10758. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10759. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10760. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10761. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10762. camLeft.position.copyFrom(this.position);
  10763. camRight.position.copyFrom(this.position);
  10764. }
  10765. else {
  10766. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10767. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10768. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10769. camLeft.setTarget(this.getTarget());
  10770. camRight.setTarget(this.getTarget());
  10771. }
  10772. break;
  10773. }
  10774. _super.prototype._updateRigCameras.call(this);
  10775. };
  10776. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10777. if (!this._rigCamTransformMatrix) {
  10778. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10779. }
  10780. var target = this.getTarget();
  10781. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10782. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10783. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10784. };
  10785. TargetCamera.prototype.serialize = function () {
  10786. var serializationObject = _super.prototype.serialize.call(this);
  10787. serializationObject.speed = this.speed;
  10788. if (this.rotation) {
  10789. serializationObject.rotation = this.rotation.asArray();
  10790. }
  10791. if (this.lockedTarget && this.lockedTarget.id) {
  10792. serializationObject.lockedTargetId = this.lockedTarget.id;
  10793. }
  10794. return serializationObject;
  10795. };
  10796. return TargetCamera;
  10797. })(BABYLON.Camera);
  10798. BABYLON.TargetCamera = TargetCamera;
  10799. })(BABYLON || (BABYLON = {}));
  10800. var BABYLON;
  10801. (function (BABYLON) {
  10802. var FreeCamera = (function (_super) {
  10803. __extends(FreeCamera, _super);
  10804. function FreeCamera(name, position, scene) {
  10805. var _this = this;
  10806. _super.call(this, name, position, scene);
  10807. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10808. this.keysUp = [38];
  10809. this.keysDown = [40];
  10810. this.keysLeft = [37];
  10811. this.keysRight = [39];
  10812. this.checkCollisions = false;
  10813. this.applyGravity = false;
  10814. this.angularSensibility = 2000.0;
  10815. this._keys = [];
  10816. this._collider = new BABYLON.Collider();
  10817. this._needMoveForGravity = false;
  10818. this._oldPosition = BABYLON.Vector3.Zero();
  10819. this._diffPosition = BABYLON.Vector3.Zero();
  10820. this._newPosition = BABYLON.Vector3.Zero();
  10821. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10822. if (collidedMesh === void 0) { collidedMesh = null; }
  10823. //TODO move this to the collision coordinator!
  10824. if (_this.getScene().workerCollisions)
  10825. newPosition.multiplyInPlace(_this._collider.radius);
  10826. var updatePosition = function (newPos) {
  10827. _this._newPosition.copyFrom(newPos);
  10828. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10829. var oldPosition = _this.position.clone();
  10830. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10831. _this.position.addInPlace(_this._diffPosition);
  10832. if (_this.onCollide && collidedMesh) {
  10833. _this.onCollide(collidedMesh);
  10834. }
  10835. }
  10836. };
  10837. updatePosition(newPosition);
  10838. };
  10839. }
  10840. FreeCamera.prototype._onLostFocus = function (e) {
  10841. this._keys = [];
  10842. };
  10843. // Controls
  10844. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10845. var _this = this;
  10846. var previousPosition;
  10847. var engine = this.getEngine();
  10848. if (this._attachedElement) {
  10849. return;
  10850. }
  10851. this._attachedElement = element;
  10852. if (this._onMouseDown === undefined) {
  10853. this._onMouseDown = function (evt) {
  10854. previousPosition = {
  10855. x: evt.clientX,
  10856. y: evt.clientY
  10857. };
  10858. if (!noPreventDefault) {
  10859. evt.preventDefault();
  10860. }
  10861. };
  10862. this._onMouseUp = function (evt) {
  10863. previousPosition = null;
  10864. if (!noPreventDefault) {
  10865. evt.preventDefault();
  10866. }
  10867. };
  10868. this._onMouseOut = function (evt) {
  10869. previousPosition = null;
  10870. _this._keys = [];
  10871. if (!noPreventDefault) {
  10872. evt.preventDefault();
  10873. }
  10874. };
  10875. this._onMouseMove = function (evt) {
  10876. if (!previousPosition && !engine.isPointerLock) {
  10877. return;
  10878. }
  10879. var offsetX;
  10880. var offsetY;
  10881. if (!engine.isPointerLock) {
  10882. offsetX = evt.clientX - previousPosition.x;
  10883. offsetY = evt.clientY - previousPosition.y;
  10884. }
  10885. else {
  10886. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10887. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10888. }
  10889. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10890. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10891. previousPosition = {
  10892. x: evt.clientX,
  10893. y: evt.clientY
  10894. };
  10895. if (!noPreventDefault) {
  10896. evt.preventDefault();
  10897. }
  10898. };
  10899. this._onKeyDown = function (evt) {
  10900. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10901. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10902. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10903. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10904. var index = _this._keys.indexOf(evt.keyCode);
  10905. if (index === -1) {
  10906. _this._keys.push(evt.keyCode);
  10907. }
  10908. if (!noPreventDefault) {
  10909. evt.preventDefault();
  10910. }
  10911. }
  10912. };
  10913. this._onKeyUp = function (evt) {
  10914. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10915. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10916. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10917. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10918. var index = _this._keys.indexOf(evt.keyCode);
  10919. if (index >= 0) {
  10920. _this._keys.splice(index, 1);
  10921. }
  10922. if (!noPreventDefault) {
  10923. evt.preventDefault();
  10924. }
  10925. }
  10926. };
  10927. this._reset = function () {
  10928. _this._keys = [];
  10929. previousPosition = null;
  10930. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10931. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10932. };
  10933. }
  10934. element.addEventListener("mousedown", this._onMouseDown, false);
  10935. element.addEventListener("mouseup", this._onMouseUp, false);
  10936. element.addEventListener("mouseout", this._onMouseOut, false);
  10937. element.addEventListener("mousemove", this._onMouseMove, false);
  10938. BABYLON.Tools.RegisterTopRootEvents([
  10939. { name: "keydown", handler: this._onKeyDown },
  10940. { name: "keyup", handler: this._onKeyUp },
  10941. { name: "blur", handler: this._onLostFocus }
  10942. ]);
  10943. };
  10944. FreeCamera.prototype.detachControl = function (element) {
  10945. if (this._attachedElement !== element) {
  10946. return;
  10947. }
  10948. element.removeEventListener("mousedown", this._onMouseDown);
  10949. element.removeEventListener("mouseup", this._onMouseUp);
  10950. element.removeEventListener("mouseout", this._onMouseOut);
  10951. element.removeEventListener("mousemove", this._onMouseMove);
  10952. BABYLON.Tools.UnregisterTopRootEvents([
  10953. { name: "keydown", handler: this._onKeyDown },
  10954. { name: "keyup", handler: this._onKeyUp },
  10955. { name: "blur", handler: this._onLostFocus }
  10956. ]);
  10957. this._attachedElement = null;
  10958. if (this._reset) {
  10959. this._reset();
  10960. }
  10961. };
  10962. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10963. var globalPosition;
  10964. if (this.parent) {
  10965. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10966. }
  10967. else {
  10968. globalPosition = this.position;
  10969. }
  10970. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10971. this._collider.radius = this.ellipsoid;
  10972. //no need for clone, as long as gravity is not on.
  10973. var actualVelocity = velocity;
  10974. //add gravity to the velocity to prevent the dual-collision checking
  10975. if (this.applyGravity) {
  10976. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10977. actualVelocity = velocity.add(this.getScene().gravity);
  10978. }
  10979. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10980. };
  10981. FreeCamera.prototype._checkInputs = function () {
  10982. if (!this._localDirection) {
  10983. this._localDirection = BABYLON.Vector3.Zero();
  10984. this._transformedDirection = BABYLON.Vector3.Zero();
  10985. }
  10986. // Keyboard
  10987. for (var index = 0; index < this._keys.length; index++) {
  10988. var keyCode = this._keys[index];
  10989. var speed = this._computeLocalCameraSpeed();
  10990. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10991. this._localDirection.copyFromFloats(-speed, 0, 0);
  10992. }
  10993. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10994. this._localDirection.copyFromFloats(0, 0, speed);
  10995. }
  10996. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10997. this._localDirection.copyFromFloats(speed, 0, 0);
  10998. }
  10999. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11000. this._localDirection.copyFromFloats(0, 0, -speed);
  11001. }
  11002. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11003. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11004. this.cameraDirection.addInPlace(this._transformedDirection);
  11005. }
  11006. _super.prototype._checkInputs.call(this);
  11007. };
  11008. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11009. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11010. };
  11011. FreeCamera.prototype._updatePosition = function () {
  11012. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11013. this._collideWithWorld(this.cameraDirection);
  11014. }
  11015. else {
  11016. this.position.addInPlace(this.cameraDirection);
  11017. }
  11018. };
  11019. FreeCamera.prototype.serialize = function () {
  11020. var serializationObject = _super.prototype.serialize.call(this);
  11021. serializationObject.checkCollisions = this.checkCollisions;
  11022. serializationObject.applyGravity = this.applyGravity;
  11023. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11024. return serializationObject;
  11025. };
  11026. return FreeCamera;
  11027. })(BABYLON.TargetCamera);
  11028. BABYLON.FreeCamera = FreeCamera;
  11029. })(BABYLON || (BABYLON = {}));
  11030. var BABYLON;
  11031. (function (BABYLON) {
  11032. var FollowCamera = (function (_super) {
  11033. __extends(FollowCamera, _super);
  11034. function FollowCamera(name, position, scene) {
  11035. _super.call(this, name, position, scene);
  11036. this.radius = 12;
  11037. this.rotationOffset = 0;
  11038. this.heightOffset = 4;
  11039. this.cameraAcceleration = 0.05;
  11040. this.maxCameraSpeed = 20;
  11041. }
  11042. FollowCamera.prototype.getRadians = function (degrees) {
  11043. return degrees * Math.PI / 180;
  11044. };
  11045. FollowCamera.prototype.follow = function (cameraTarget) {
  11046. if (!cameraTarget)
  11047. return;
  11048. var yRotation;
  11049. if (cameraTarget.rotationQuaternion) {
  11050. var rotMatrix = new BABYLON.Matrix();
  11051. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11052. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11053. }
  11054. else {
  11055. yRotation = cameraTarget.rotation.y;
  11056. }
  11057. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11058. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11059. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11060. var dx = targetX - this.position.x;
  11061. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11062. var dz = (targetZ) - this.position.z;
  11063. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11064. var vy = dy * this.cameraAcceleration;
  11065. var vz = dz * this.cameraAcceleration * 2;
  11066. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11067. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11068. }
  11069. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11070. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11071. }
  11072. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11073. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11074. }
  11075. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11076. this.setTarget(cameraTarget.position);
  11077. };
  11078. FollowCamera.prototype._checkInputs = function () {
  11079. _super.prototype._checkInputs.call(this);
  11080. this.follow(this.target);
  11081. };
  11082. FollowCamera.prototype.serialize = function () {
  11083. var serializationObject = _super.prototype.serialize.call(this);
  11084. serializationObject.radius = this.radius;
  11085. serializationObject.heightOffset = this.heightOffset;
  11086. serializationObject.rotationOffset = this.rotationOffset;
  11087. return serializationObject;
  11088. };
  11089. return FollowCamera;
  11090. })(BABYLON.TargetCamera);
  11091. BABYLON.FollowCamera = FollowCamera;
  11092. var ArcFollowCamera = (function (_super) {
  11093. __extends(ArcFollowCamera, _super);
  11094. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11095. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11096. this.alpha = alpha;
  11097. this.beta = beta;
  11098. this.radius = radius;
  11099. this.target = target;
  11100. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11101. this.follow();
  11102. }
  11103. ArcFollowCamera.prototype.follow = function () {
  11104. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11105. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11106. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11107. this.position = this.target.position.add(this._cartesianCoordinates);
  11108. this.setTarget(this.target.position);
  11109. };
  11110. ArcFollowCamera.prototype._checkInputs = function () {
  11111. _super.prototype._checkInputs.call(this);
  11112. this.follow();
  11113. };
  11114. ArcFollowCamera.prototype.serialize = function () {
  11115. var serializationObject = _super.prototype.serialize.call(this);
  11116. serializationObject.radius = this.radius;
  11117. return serializationObject;
  11118. };
  11119. return ArcFollowCamera;
  11120. })(BABYLON.TargetCamera);
  11121. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11122. })(BABYLON || (BABYLON = {}));
  11123. var BABYLON;
  11124. (function (BABYLON) {
  11125. // We're mainly based on the logic defined into the FreeCamera code
  11126. var TouchCamera = (function (_super) {
  11127. __extends(TouchCamera, _super);
  11128. function TouchCamera(name, position, scene) {
  11129. _super.call(this, name, position, scene);
  11130. this._offsetX = null;
  11131. this._offsetY = null;
  11132. this._pointerCount = 0;
  11133. this._pointerPressed = [];
  11134. this.touchAngularSensibility = 200000.0;
  11135. this.touchMoveSensibility = 500.0;
  11136. }
  11137. TouchCamera.prototype._onLostFocus = function (e) {
  11138. this._offsetX = null;
  11139. this._offsetY = null;
  11140. _super.prototype._onLostFocus.call(this, e);
  11141. };
  11142. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11143. var _this = this;
  11144. var previousPosition;
  11145. if (this._attachedCanvas) {
  11146. return;
  11147. }
  11148. if (this._onPointerDown === undefined) {
  11149. this._onPointerDown = function (evt) {
  11150. if (evt.pointerType === "mouse") {
  11151. return;
  11152. }
  11153. if (!noPreventDefault) {
  11154. evt.preventDefault();
  11155. }
  11156. _this._pointerPressed.push(evt.pointerId);
  11157. if (_this._pointerPressed.length !== 1) {
  11158. return;
  11159. }
  11160. previousPosition = {
  11161. x: evt.clientX,
  11162. y: evt.clientY
  11163. };
  11164. };
  11165. this._onPointerUp = function (evt) {
  11166. if (evt.pointerType === "mouse") {
  11167. return;
  11168. }
  11169. if (!noPreventDefault) {
  11170. evt.preventDefault();
  11171. }
  11172. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11173. if (index === -1) {
  11174. return;
  11175. }
  11176. _this._pointerPressed.splice(index, 1);
  11177. if (index != 0) {
  11178. return;
  11179. }
  11180. previousPosition = null;
  11181. _this._offsetX = null;
  11182. _this._offsetY = null;
  11183. };
  11184. this._onPointerMove = function (evt) {
  11185. if (evt.pointerType === "mouse") {
  11186. return;
  11187. }
  11188. if (!noPreventDefault) {
  11189. evt.preventDefault();
  11190. }
  11191. if (!previousPosition) {
  11192. return;
  11193. }
  11194. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11195. if (index != 0) {
  11196. return;
  11197. }
  11198. _this._offsetX = evt.clientX - previousPosition.x;
  11199. _this._offsetY = -(evt.clientY - previousPosition.y);
  11200. };
  11201. }
  11202. canvas.addEventListener("pointerdown", this._onPointerDown);
  11203. canvas.addEventListener("pointerup", this._onPointerUp);
  11204. canvas.addEventListener("pointerout", this._onPointerUp);
  11205. canvas.addEventListener("pointermove", this._onPointerMove);
  11206. _super.prototype.attachControl.call(this, canvas);
  11207. };
  11208. TouchCamera.prototype.detachControl = function (canvas) {
  11209. if (this._attachedCanvas !== canvas) {
  11210. return;
  11211. }
  11212. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11213. canvas.removeEventListener("pointerup", this._onPointerUp);
  11214. canvas.removeEventListener("pointerout", this._onPointerUp);
  11215. canvas.removeEventListener("pointermove", this._onPointerMove);
  11216. _super.prototype.detachControl.call(this, canvas);
  11217. };
  11218. TouchCamera.prototype._checkInputs = function () {
  11219. if (this._offsetX) {
  11220. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11221. if (this._pointerPressed.length > 1) {
  11222. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11223. }
  11224. else {
  11225. var speed = this._computeLocalCameraSpeed();
  11226. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11227. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11228. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11229. }
  11230. }
  11231. _super.prototype._checkInputs.call(this);
  11232. };
  11233. return TouchCamera;
  11234. })(BABYLON.FreeCamera);
  11235. BABYLON.TouchCamera = TouchCamera;
  11236. })(BABYLON || (BABYLON = {}));
  11237. var BABYLON;
  11238. (function (BABYLON) {
  11239. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11240. var ArcRotateCamera = (function (_super) {
  11241. __extends(ArcRotateCamera, _super);
  11242. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11243. var _this = this;
  11244. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11245. this.alpha = alpha;
  11246. this.beta = beta;
  11247. this.radius = radius;
  11248. this.target = target;
  11249. this.inertialAlphaOffset = 0;
  11250. this.inertialBetaOffset = 0;
  11251. this.inertialRadiusOffset = 0;
  11252. this.lowerAlphaLimit = null;
  11253. this.upperAlphaLimit = null;
  11254. this.lowerBetaLimit = 0.01;
  11255. this.upperBetaLimit = Math.PI;
  11256. this.lowerRadiusLimit = null;
  11257. this.upperRadiusLimit = null;
  11258. this.angularSensibilityX = 1000.0;
  11259. this.angularSensibilityY = 1000.0;
  11260. this.wheelPrecision = 3.0;
  11261. this.pinchPrecision = 2.0;
  11262. this.panningSensibility = 50.0;
  11263. this.inertialPanningX = 0;
  11264. this.inertialPanningY = 0;
  11265. this.keysUp = [38];
  11266. this.keysDown = [40];
  11267. this.keysLeft = [37];
  11268. this.keysRight = [39];
  11269. this.zoomOnFactor = 1;
  11270. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11271. this.pinchInwards = true;
  11272. this.allowUpsideDown = true;
  11273. this._keys = [];
  11274. this._viewMatrix = new BABYLON.Matrix();
  11275. // Panning
  11276. this.panningAxis = new BABYLON.Vector3(1, 0, 1);
  11277. this._isRightClick = false;
  11278. this._isCtrlPushed = false;
  11279. this.checkCollisions = false;
  11280. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11281. this._collider = new BABYLON.Collider();
  11282. this._previousPosition = BABYLON.Vector3.Zero();
  11283. this._collisionVelocity = BABYLON.Vector3.Zero();
  11284. this._newPosition = BABYLON.Vector3.Zero();
  11285. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11286. if (collidedMesh === void 0) { collidedMesh = null; }
  11287. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11288. newPosition.multiplyInPlace(_this._collider.radius);
  11289. }
  11290. if (!collidedMesh) {
  11291. _this._previousPosition.copyFrom(_this.position);
  11292. }
  11293. else {
  11294. _this.setPosition(newPosition);
  11295. if (_this.onCollide) {
  11296. _this.onCollide(collidedMesh);
  11297. }
  11298. }
  11299. // Recompute because of constraints
  11300. var cosa = Math.cos(_this.alpha);
  11301. var sina = Math.sin(_this.alpha);
  11302. var cosb = Math.cos(_this.beta);
  11303. var sinb = Math.sin(_this.beta);
  11304. var target = _this._getTargetPosition();
  11305. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11306. _this.position.copyFrom(_this._newPosition);
  11307. var up = _this.upVector;
  11308. if (_this.allowUpsideDown && _this.beta < 0) {
  11309. up = up.clone();
  11310. up = up.negate();
  11311. }
  11312. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11313. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11314. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11315. _this._collisionTriggered = false;
  11316. };
  11317. if (!this.target) {
  11318. this.target = BABYLON.Vector3.Zero();
  11319. }
  11320. this.getViewMatrix();
  11321. }
  11322. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11323. //deprecated angularSensibility support
  11324. get: function () {
  11325. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11326. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11327. },
  11328. //deprecated angularSensibility support
  11329. set: function (value) {
  11330. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11331. this.angularSensibilityX = value;
  11332. this.angularSensibilityY = value;
  11333. },
  11334. enumerable: true,
  11335. configurable: true
  11336. });
  11337. ArcRotateCamera.prototype._getTargetPosition = function () {
  11338. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11339. };
  11340. // Cache
  11341. ArcRotateCamera.prototype._initCache = function () {
  11342. _super.prototype._initCache.call(this);
  11343. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11344. this._cache.alpha = undefined;
  11345. this._cache.beta = undefined;
  11346. this._cache.radius = undefined;
  11347. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11348. };
  11349. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11350. if (!ignoreParentClass) {
  11351. _super.prototype._updateCache.call(this);
  11352. }
  11353. this._cache.target.copyFrom(this._getTargetPosition());
  11354. this._cache.alpha = this.alpha;
  11355. this._cache.beta = this.beta;
  11356. this._cache.radius = this.radius;
  11357. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11358. };
  11359. // Synchronized
  11360. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11361. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11362. return false;
  11363. return this._cache.target.equals(this._getTargetPosition())
  11364. && this._cache.alpha === this.alpha
  11365. && this._cache.beta === this.beta
  11366. && this._cache.radius === this.radius
  11367. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11368. };
  11369. // Methods
  11370. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11371. var _this = this;
  11372. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11373. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11374. var previousPinchDistance = 0;
  11375. var pointers = new BABYLON.SmartCollection();
  11376. if (this._attachedElement) {
  11377. return;
  11378. }
  11379. this._attachedElement = element;
  11380. var engine = this.getEngine();
  11381. if (this._onPointerDown === undefined) {
  11382. this._onPointerDown = function (evt) {
  11383. // Manage panning with right click
  11384. _this._isRightClick = evt.button === 2;
  11385. // manage pointers
  11386. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11387. cacheSoloPointer = pointers.item(evt.pointerId);
  11388. if (!noPreventDefault) {
  11389. evt.preventDefault();
  11390. }
  11391. };
  11392. this._onPointerUp = function (evt) {
  11393. cacheSoloPointer = null;
  11394. previousPinchDistance = 0;
  11395. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11396. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11397. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11398. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11399. pointers.empty();
  11400. if (!noPreventDefault) {
  11401. evt.preventDefault();
  11402. }
  11403. };
  11404. this._onContextMenu = function (evt) {
  11405. evt.preventDefault();
  11406. };
  11407. this._onPointerMove = function (evt) {
  11408. if (!noPreventDefault) {
  11409. evt.preventDefault();
  11410. }
  11411. switch (pointers.count) {
  11412. case 1:
  11413. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11414. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11415. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11416. }
  11417. else {
  11418. var offsetX = evt.clientX - cacheSoloPointer.x;
  11419. var offsetY = evt.clientY - cacheSoloPointer.y;
  11420. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11421. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11422. }
  11423. cacheSoloPointer.x = evt.clientX;
  11424. cacheSoloPointer.y = evt.clientY;
  11425. break;
  11426. case 2:
  11427. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11428. pointers.item(evt.pointerId).x = evt.clientX;
  11429. pointers.item(evt.pointerId).y = evt.clientY;
  11430. var direction = _this.pinchInwards ? 1 : -1;
  11431. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11432. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11433. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11434. if (previousPinchDistance === 0) {
  11435. previousPinchDistance = pinchSquaredDistance;
  11436. return;
  11437. }
  11438. if (pinchSquaredDistance !== previousPinchDistance) {
  11439. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11440. previousPinchDistance = pinchSquaredDistance;
  11441. }
  11442. break;
  11443. default:
  11444. if (pointers.item(evt.pointerId)) {
  11445. pointers.item(evt.pointerId).x = evt.clientX;
  11446. pointers.item(evt.pointerId).y = evt.clientY;
  11447. }
  11448. }
  11449. };
  11450. this._onMouseMove = function (evt) {
  11451. if (!engine.isPointerLock) {
  11452. return;
  11453. }
  11454. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11455. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11456. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11457. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11458. if (!noPreventDefault) {
  11459. evt.preventDefault();
  11460. }
  11461. };
  11462. this._wheel = function (event) {
  11463. var delta = 0;
  11464. if (event.wheelDelta) {
  11465. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11466. }
  11467. else if (event.detail) {
  11468. delta = -event.detail / _this.wheelPrecision;
  11469. }
  11470. if (delta)
  11471. _this.inertialRadiusOffset += delta;
  11472. if (event.preventDefault) {
  11473. if (!noPreventDefault) {
  11474. event.preventDefault();
  11475. }
  11476. }
  11477. };
  11478. this._onKeyDown = function (evt) {
  11479. _this._isCtrlPushed = evt.ctrlKey;
  11480. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11481. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11482. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11483. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11484. var index = _this._keys.indexOf(evt.keyCode);
  11485. if (index === -1) {
  11486. _this._keys.push(evt.keyCode);
  11487. }
  11488. if (evt.preventDefault) {
  11489. if (!noPreventDefault) {
  11490. evt.preventDefault();
  11491. }
  11492. }
  11493. }
  11494. };
  11495. this._onKeyUp = function (evt) {
  11496. _this._isCtrlPushed = evt.ctrlKey;
  11497. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11498. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11499. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11500. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11501. var index = _this._keys.indexOf(evt.keyCode);
  11502. if (index >= 0) {
  11503. _this._keys.splice(index, 1);
  11504. }
  11505. if (evt.preventDefault) {
  11506. if (!noPreventDefault) {
  11507. evt.preventDefault();
  11508. }
  11509. }
  11510. }
  11511. };
  11512. this._onLostFocus = function () {
  11513. _this._keys = [];
  11514. pointers.empty();
  11515. previousPinchDistance = 0;
  11516. cacheSoloPointer = null;
  11517. };
  11518. this._onGestureStart = function (e) {
  11519. if (window.MSGesture === undefined) {
  11520. return;
  11521. }
  11522. if (!_this._MSGestureHandler) {
  11523. _this._MSGestureHandler = new MSGesture();
  11524. _this._MSGestureHandler.target = element;
  11525. }
  11526. _this._MSGestureHandler.addPointer(e.pointerId);
  11527. };
  11528. this._onGesture = function (e) {
  11529. _this.radius *= e.scale;
  11530. if (e.preventDefault) {
  11531. if (!noPreventDefault) {
  11532. e.stopPropagation();
  11533. e.preventDefault();
  11534. }
  11535. }
  11536. };
  11537. this._reset = function () {
  11538. _this._keys = [];
  11539. _this.inertialAlphaOffset = 0;
  11540. _this.inertialBetaOffset = 0;
  11541. _this.inertialRadiusOffset = 0;
  11542. pointers.empty();
  11543. previousPinchDistance = 0;
  11544. cacheSoloPointer = null;
  11545. };
  11546. }
  11547. if (!useCtrlForPanning) {
  11548. element.addEventListener("contextmenu", this._onContextMenu, false);
  11549. }
  11550. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11551. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11552. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11553. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11554. element.addEventListener("mousemove", this._onMouseMove, false);
  11555. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11556. element.addEventListener("MSGestureChange", this._onGesture, false);
  11557. element.addEventListener('mousewheel', this._wheel, false);
  11558. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11559. BABYLON.Tools.RegisterTopRootEvents([
  11560. { name: "keydown", handler: this._onKeyDown },
  11561. { name: "keyup", handler: this._onKeyUp },
  11562. { name: "blur", handler: this._onLostFocus }
  11563. ]);
  11564. };
  11565. ArcRotateCamera.prototype.detachControl = function (element) {
  11566. if (this._attachedElement !== element) {
  11567. return;
  11568. }
  11569. element.removeEventListener("contextmenu", this._onContextMenu);
  11570. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11571. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11572. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11573. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11574. element.removeEventListener("mousemove", this._onMouseMove);
  11575. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11576. element.removeEventListener("MSGestureChange", this._onGesture);
  11577. element.removeEventListener('mousewheel', this._wheel);
  11578. element.removeEventListener('DOMMouseScroll', this._wheel);
  11579. BABYLON.Tools.UnregisterTopRootEvents([
  11580. { name: "keydown", handler: this._onKeyDown },
  11581. { name: "keyup", handler: this._onKeyUp },
  11582. { name: "blur", handler: this._onLostFocus }
  11583. ]);
  11584. this._MSGestureHandler = null;
  11585. this._attachedElement = null;
  11586. if (this._reset) {
  11587. this._reset();
  11588. }
  11589. };
  11590. ArcRotateCamera.prototype._checkInputs = function () {
  11591. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11592. if (this._collisionTriggered) {
  11593. return;
  11594. }
  11595. // Keyboard
  11596. for (var index = 0; index < this._keys.length; index++) {
  11597. var keyCode = this._keys[index];
  11598. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11599. this.inertialAlphaOffset -= 0.01;
  11600. }
  11601. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11602. this.inertialBetaOffset -= 0.01;
  11603. }
  11604. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11605. this.inertialAlphaOffset += 0.01;
  11606. }
  11607. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11608. this.inertialBetaOffset += 0.01;
  11609. }
  11610. }
  11611. // Inertia
  11612. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11613. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11614. this.beta += this.inertialBetaOffset;
  11615. this.radius -= this.inertialRadiusOffset;
  11616. this.inertialAlphaOffset *= this.inertia;
  11617. this.inertialBetaOffset *= this.inertia;
  11618. this.inertialRadiusOffset *= this.inertia;
  11619. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11620. this.inertialAlphaOffset = 0;
  11621. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11622. this.inertialBetaOffset = 0;
  11623. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11624. this.inertialRadiusOffset = 0;
  11625. }
  11626. // Panning inertia
  11627. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11628. if (!this._localDirection) {
  11629. this._localDirection = BABYLON.Vector3.Zero();
  11630. this._transformedDirection = BABYLON.Vector3.Zero();
  11631. }
  11632. this.inertialPanningX *= this.inertia;
  11633. this.inertialPanningY *= this.inertia;
  11634. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11635. this.inertialPanningX = 0;
  11636. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11637. this.inertialPanningY = 0;
  11638. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11639. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11640. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11641. this._transformedDirection.multiplyInPlace(this.panningAxis);
  11642. this.target.addInPlace(this._transformedDirection);
  11643. }
  11644. // Limits
  11645. this._checkLimits();
  11646. _super.prototype._checkInputs.call(this);
  11647. };
  11648. ArcRotateCamera.prototype._checkLimits = function () {
  11649. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11650. if (this.allowUpsideDown && this.beta > Math.PI) {
  11651. this.beta = this.beta - (2 * Math.PI);
  11652. }
  11653. }
  11654. else {
  11655. if (this.beta < this.lowerBetaLimit) {
  11656. this.beta = this.lowerBetaLimit;
  11657. }
  11658. }
  11659. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11660. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11661. this.beta = this.beta + (2 * Math.PI);
  11662. }
  11663. }
  11664. else {
  11665. if (this.beta > this.upperBetaLimit) {
  11666. this.beta = this.upperBetaLimit;
  11667. }
  11668. }
  11669. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11670. this.alpha = this.lowerAlphaLimit;
  11671. }
  11672. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11673. this.alpha = this.upperAlphaLimit;
  11674. }
  11675. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11676. this.radius = this.lowerRadiusLimit;
  11677. }
  11678. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11679. this.radius = this.upperRadiusLimit;
  11680. }
  11681. };
  11682. ArcRotateCamera.prototype.setPosition = function (position) {
  11683. if (this.position.equals(position)) {
  11684. return;
  11685. }
  11686. var radiusv3 = position.subtract(this._getTargetPosition());
  11687. this.radius = radiusv3.length();
  11688. // Alpha
  11689. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11690. if (radiusv3.z < 0) {
  11691. this.alpha = 2 * Math.PI - this.alpha;
  11692. }
  11693. // Beta
  11694. this.beta = Math.acos(radiusv3.y / this.radius);
  11695. this._checkLimits();
  11696. };
  11697. ArcRotateCamera.prototype.setTarget = function (target) {
  11698. this.target = target;
  11699. };
  11700. ArcRotateCamera.prototype._getViewMatrix = function () {
  11701. // Compute
  11702. var cosa = Math.cos(this.alpha);
  11703. var sina = Math.sin(this.alpha);
  11704. var cosb = Math.cos(this.beta);
  11705. var sinb = Math.sin(this.beta);
  11706. var target = this._getTargetPosition();
  11707. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11708. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11709. this._collider.radius = this.collisionRadius;
  11710. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11711. this._collisionTriggered = true;
  11712. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11713. }
  11714. else {
  11715. this.position.copyFrom(this._newPosition);
  11716. var up = this.upVector;
  11717. if (this.allowUpsideDown && this.beta < 0) {
  11718. up = up.clone();
  11719. up = up.negate();
  11720. }
  11721. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11722. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11723. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11724. }
  11725. return this._viewMatrix;
  11726. };
  11727. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11728. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11729. meshes = meshes || this.getScene().meshes;
  11730. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11731. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11732. this.radius = distance * this.zoomOnFactor;
  11733. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11734. };
  11735. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11736. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11737. var meshesOrMinMaxVector;
  11738. var distance;
  11739. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11740. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11741. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11742. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11743. }
  11744. else {
  11745. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11746. distance = meshesOrMinMaxVectorAndDistance.distance;
  11747. }
  11748. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11749. if (!doNotUpdateMaxZ) {
  11750. this.maxZ = distance * 2;
  11751. }
  11752. };
  11753. /**
  11754. * @override
  11755. * Override Camera.createRigCamera
  11756. */
  11757. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11758. switch (this.cameraRigMode) {
  11759. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11760. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11762. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11763. case BABYLON.Camera.RIG_MODE_VR:
  11764. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11765. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11766. }
  11767. return null;
  11768. };
  11769. /**
  11770. * @override
  11771. * Override Camera._updateRigCameras
  11772. */
  11773. ArcRotateCamera.prototype._updateRigCameras = function () {
  11774. switch (this.cameraRigMode) {
  11775. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11776. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11779. case BABYLON.Camera.RIG_MODE_VR:
  11780. var camLeft = this._rigCameras[0];
  11781. var camRight = this._rigCameras[1];
  11782. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11783. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11784. camLeft.beta = camRight.beta = this.beta;
  11785. camLeft.radius = camRight.radius = this.radius;
  11786. break;
  11787. }
  11788. _super.prototype._updateRigCameras.call(this);
  11789. };
  11790. ArcRotateCamera.prototype.serialize = function () {
  11791. var serializationObject = _super.prototype.serialize.call(this);
  11792. if (this.target instanceof BABYLON.Vector3) {
  11793. serializationObject.target = this.target.asArray();
  11794. }
  11795. if (this.target && this.target.id) {
  11796. serializationObject.lockedTargetId = this.target.id;
  11797. }
  11798. serializationObject.checkCollisions = this.checkCollisions;
  11799. serializationObject.alpha = this.alpha;
  11800. serializationObject.beta = this.beta;
  11801. serializationObject.radius = this.radius;
  11802. return serializationObject;
  11803. };
  11804. return ArcRotateCamera;
  11805. })(BABYLON.TargetCamera);
  11806. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11807. })(BABYLON || (BABYLON = {}));
  11808. var BABYLON;
  11809. (function (BABYLON) {
  11810. var RenderingManager = (function () {
  11811. function RenderingManager(scene) {
  11812. this._renderingGroups = new Array();
  11813. this._scene = scene;
  11814. }
  11815. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11816. if (this._scene._activeParticleSystems.length === 0) {
  11817. return;
  11818. }
  11819. // Particles
  11820. var activeCamera = this._scene.activeCamera;
  11821. var beforeParticlesDate = BABYLON.Tools.Now;
  11822. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11823. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11824. if (particleSystem.renderingGroupId !== index) {
  11825. continue;
  11826. }
  11827. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11828. continue;
  11829. }
  11830. this._clearDepthBuffer();
  11831. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11832. this._scene._activeParticles += particleSystem.render();
  11833. }
  11834. }
  11835. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11836. };
  11837. RenderingManager.prototype._renderSprites = function (index) {
  11838. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11839. return;
  11840. }
  11841. // Sprites
  11842. var activeCamera = this._scene.activeCamera;
  11843. var beforeSpritessDate = BABYLON.Tools.Now;
  11844. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11845. var spriteManager = this._scene.spriteManagers[id];
  11846. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11847. this._clearDepthBuffer();
  11848. spriteManager.render();
  11849. }
  11850. }
  11851. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11852. };
  11853. RenderingManager.prototype._clearDepthBuffer = function () {
  11854. if (this._depthBufferAlreadyCleaned) {
  11855. return;
  11856. }
  11857. this._scene.getEngine().clear(0, false, true);
  11858. this._depthBufferAlreadyCleaned = true;
  11859. };
  11860. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11861. if (this._currentRenderSprites) {
  11862. this._renderSprites(this._currentIndex);
  11863. }
  11864. if (this._currentRenderParticles) {
  11865. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11866. }
  11867. };
  11868. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11869. this._currentActiveMeshes = activeMeshes;
  11870. this._currentRenderParticles = renderParticles;
  11871. this._currentRenderSprites = renderSprites;
  11872. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11873. this._depthBufferAlreadyCleaned = index == 0;
  11874. var renderingGroup = this._renderingGroups[index];
  11875. var needToStepBack = false;
  11876. this._currentIndex = index;
  11877. if (renderingGroup) {
  11878. this._clearDepthBuffer();
  11879. if (!renderingGroup.onBeforeTransparentRendering) {
  11880. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11881. }
  11882. if (!renderingGroup.render(customRenderFunction)) {
  11883. this._renderingGroups.splice(index, 1);
  11884. needToStepBack = true;
  11885. this._renderSpritesAndParticles();
  11886. }
  11887. }
  11888. else {
  11889. this._renderSpritesAndParticles();
  11890. }
  11891. if (needToStepBack) {
  11892. index--;
  11893. }
  11894. }
  11895. };
  11896. RenderingManager.prototype.reset = function () {
  11897. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11898. if (renderingGroup) {
  11899. renderingGroup.prepare();
  11900. }
  11901. });
  11902. };
  11903. RenderingManager.prototype.dispatch = function (subMesh) {
  11904. var mesh = subMesh.getMesh();
  11905. var renderingGroupId = mesh.renderingGroupId || 0;
  11906. if (!this._renderingGroups[renderingGroupId]) {
  11907. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11908. }
  11909. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11910. };
  11911. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11912. return RenderingManager;
  11913. })();
  11914. BABYLON.RenderingManager = RenderingManager;
  11915. })(BABYLON || (BABYLON = {}));
  11916. var BABYLON;
  11917. (function (BABYLON) {
  11918. var RenderingGroup = (function () {
  11919. function RenderingGroup(index, scene) {
  11920. this.index = index;
  11921. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11922. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11923. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11924. this._scene = scene;
  11925. }
  11926. RenderingGroup.prototype.render = function (customRenderFunction) {
  11927. if (customRenderFunction) {
  11928. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11929. return true;
  11930. }
  11931. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11932. if (this.onBeforeTransparentRendering) {
  11933. this.onBeforeTransparentRendering();
  11934. }
  11935. return false;
  11936. }
  11937. var engine = this._scene.getEngine();
  11938. // Opaque
  11939. var subIndex;
  11940. var submesh;
  11941. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11942. submesh = this._opaqueSubMeshes.data[subIndex];
  11943. submesh.render(false);
  11944. }
  11945. // Alpha test
  11946. engine.setAlphaTesting(true);
  11947. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11948. submesh = this._alphaTestSubMeshes.data[subIndex];
  11949. submesh.render(false);
  11950. }
  11951. engine.setAlphaTesting(false);
  11952. if (this.onBeforeTransparentRendering) {
  11953. this.onBeforeTransparentRendering();
  11954. }
  11955. // Transparent
  11956. if (this._transparentSubMeshes.length) {
  11957. // Sorting
  11958. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11959. submesh = this._transparentSubMeshes.data[subIndex];
  11960. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11961. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11962. }
  11963. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11964. sortedArray.sort(function (a, b) {
  11965. // Alpha index first
  11966. if (a._alphaIndex > b._alphaIndex) {
  11967. return 1;
  11968. }
  11969. if (a._alphaIndex < b._alphaIndex) {
  11970. return -1;
  11971. }
  11972. // Then distance to camera
  11973. if (a._distanceToCamera < b._distanceToCamera) {
  11974. return 1;
  11975. }
  11976. if (a._distanceToCamera > b._distanceToCamera) {
  11977. return -1;
  11978. }
  11979. return 0;
  11980. });
  11981. // Rendering
  11982. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11983. submesh = sortedArray[subIndex];
  11984. submesh.render(true);
  11985. }
  11986. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11987. }
  11988. return true;
  11989. };
  11990. RenderingGroup.prototype.prepare = function () {
  11991. this._opaqueSubMeshes.reset();
  11992. this._transparentSubMeshes.reset();
  11993. this._alphaTestSubMeshes.reset();
  11994. };
  11995. RenderingGroup.prototype.dispatch = function (subMesh) {
  11996. var material = subMesh.getMaterial();
  11997. var mesh = subMesh.getMesh();
  11998. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11999. this._transparentSubMeshes.push(subMesh);
  12000. }
  12001. else if (material.needAlphaTesting()) {
  12002. this._alphaTestSubMeshes.push(subMesh);
  12003. }
  12004. else {
  12005. this._opaqueSubMeshes.push(subMesh); // Opaque
  12006. }
  12007. };
  12008. return RenderingGroup;
  12009. })();
  12010. BABYLON.RenderingGroup = RenderingGroup;
  12011. })(BABYLON || (BABYLON = {}));
  12012. var BABYLON;
  12013. (function (BABYLON) {
  12014. /**
  12015. * Represents a scene to be rendered by the engine.
  12016. * @see http://doc.babylonjs.com/page.php?p=21911
  12017. */
  12018. var Scene = (function () {
  12019. /**
  12020. * @constructor
  12021. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12022. */
  12023. function Scene(engine) {
  12024. // Members
  12025. this.autoClear = true;
  12026. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12027. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12028. this.forceWireframe = false;
  12029. this.forcePointsCloud = false;
  12030. this.forceShowBoundingBoxes = false;
  12031. this.animationsEnabled = true;
  12032. this.constantlyUpdateMeshUnderPointer = false;
  12033. 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
  12034. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12035. this._startingPointerTime = 0;
  12036. // Fog
  12037. /**
  12038. * is fog enabled on this scene.
  12039. * @type {boolean}
  12040. */
  12041. this.fogEnabled = true;
  12042. this.fogMode = Scene.FOGMODE_NONE;
  12043. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12044. this.fogDensity = 0.1;
  12045. this.fogStart = 0;
  12046. this.fogEnd = 1000.0;
  12047. // Lights
  12048. /**
  12049. * is shadow enabled on this scene.
  12050. * @type {boolean}
  12051. */
  12052. this.shadowsEnabled = true;
  12053. /**
  12054. * is light enabled on this scene.
  12055. * @type {boolean}
  12056. */
  12057. this.lightsEnabled = true;
  12058. /**
  12059. * All of the lights added to this scene.
  12060. * @see BABYLON.Light
  12061. * @type {BABYLON.Light[]}
  12062. */
  12063. this.lights = new Array();
  12064. // Cameras
  12065. /**
  12066. * All of the cameras added to this scene.
  12067. * @see BABYLON.Camera
  12068. * @type {BABYLON.Camera[]}
  12069. */
  12070. this.cameras = new Array();
  12071. this.activeCameras = new Array();
  12072. // Meshes
  12073. /**
  12074. * All of the (abstract) meshes added to this scene.
  12075. * @see BABYLON.AbstractMesh
  12076. * @type {BABYLON.AbstractMesh[]}
  12077. */
  12078. this.meshes = new Array();
  12079. // Geometries
  12080. this._geometries = new Array();
  12081. this.materials = new Array();
  12082. this.multiMaterials = new Array();
  12083. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12084. // Textures
  12085. this.texturesEnabled = true;
  12086. this.textures = new Array();
  12087. // Particles
  12088. this.particlesEnabled = true;
  12089. this.particleSystems = new Array();
  12090. // Sprites
  12091. this.spritesEnabled = true;
  12092. this.spriteManagers = new Array();
  12093. // Layers
  12094. this.layers = new Array();
  12095. // Skeletons
  12096. this.skeletonsEnabled = true;
  12097. this.skeletons = new Array();
  12098. // Lens flares
  12099. this.lensFlaresEnabled = true;
  12100. this.lensFlareSystems = new Array();
  12101. // Collisions
  12102. this.collisionsEnabled = true;
  12103. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12104. // Postprocesses
  12105. this.postProcessesEnabled = true;
  12106. // Customs render targets
  12107. this.renderTargetsEnabled = true;
  12108. this.dumpNextRenderTargets = false;
  12109. this.customRenderTargets = new Array();
  12110. // Imported meshes
  12111. this.importedMeshesFiles = new Array();
  12112. // Probes
  12113. this.probesEnabled = true;
  12114. this.reflectionProbes = new Array();
  12115. this._actionManagers = new Array();
  12116. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12117. // Procedural textures
  12118. this.proceduralTexturesEnabled = true;
  12119. this._proceduralTextures = new Array();
  12120. this.soundTracks = new Array();
  12121. this._audioEnabled = true;
  12122. this._headphone = false;
  12123. this._totalVertices = 0;
  12124. this._activeIndices = 0;
  12125. this._activeParticles = 0;
  12126. this._lastFrameDuration = 0;
  12127. this._evaluateActiveMeshesDuration = 0;
  12128. this._renderTargetsDuration = 0;
  12129. this._particlesDuration = 0;
  12130. this._renderDuration = 0;
  12131. this._spritesDuration = 0;
  12132. this._animationRatio = 0;
  12133. this._renderId = 0;
  12134. this._executeWhenReadyTimeoutId = -1;
  12135. this._toBeDisposed = new BABYLON.SmartArray(256);
  12136. this._onReadyCallbacks = new Array();
  12137. this._pendingData = []; //ANY
  12138. this._onBeforeRenderCallbacks = new Array();
  12139. this._onAfterRenderCallbacks = new Array();
  12140. this._activeMeshes = new BABYLON.SmartArray(256);
  12141. this._processedMaterials = new BABYLON.SmartArray(256);
  12142. this._renderTargets = new BABYLON.SmartArray(256);
  12143. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12144. this._activeSkeletons = new BABYLON.SmartArray(32);
  12145. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12146. this._activeBones = 0;
  12147. this._activeAnimatables = new Array();
  12148. this._transformMatrix = BABYLON.Matrix.Zero();
  12149. this._edgesRenderers = new BABYLON.SmartArray(16);
  12150. this._uniqueIdCounter = 0;
  12151. this._engine = engine;
  12152. engine.scenes.push(this);
  12153. this._renderingManager = new BABYLON.RenderingManager(this);
  12154. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12155. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12156. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12157. if (BABYLON.OutlineRenderer) {
  12158. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12159. }
  12160. this.attachControl();
  12161. this._debugLayer = new BABYLON.DebugLayer(this);
  12162. if (BABYLON.SoundTrack) {
  12163. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12164. }
  12165. //simplification queue
  12166. if (BABYLON.SimplificationQueue) {
  12167. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12168. }
  12169. //collision coordinator initialization. For now legacy per default.
  12170. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12171. }
  12172. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12173. get: function () {
  12174. return Scene._FOGMODE_NONE;
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12180. get: function () {
  12181. return Scene._FOGMODE_EXP;
  12182. },
  12183. enumerable: true,
  12184. configurable: true
  12185. });
  12186. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12187. get: function () {
  12188. return Scene._FOGMODE_EXP2;
  12189. },
  12190. enumerable: true,
  12191. configurable: true
  12192. });
  12193. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12194. get: function () {
  12195. return Scene._FOGMODE_LINEAR;
  12196. },
  12197. enumerable: true,
  12198. configurable: true
  12199. });
  12200. Object.defineProperty(Scene.prototype, "debugLayer", {
  12201. // Properties
  12202. get: function () {
  12203. return this._debugLayer;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12209. get: function () {
  12210. return this._workerCollisions;
  12211. },
  12212. set: function (enabled) {
  12213. enabled = (enabled && !!Worker);
  12214. this._workerCollisions = enabled;
  12215. if (this.collisionCoordinator) {
  12216. this.collisionCoordinator.destroy();
  12217. }
  12218. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12219. this.collisionCoordinator.init(this);
  12220. },
  12221. enumerable: true,
  12222. configurable: true
  12223. });
  12224. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12225. get: function () {
  12226. return this._selectionOctree;
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12232. /**
  12233. * The mesh that is currently under the pointer.
  12234. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12235. */
  12236. get: function () {
  12237. return this._meshUnderPointer;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Object.defineProperty(Scene.prototype, "pointerX", {
  12243. /**
  12244. * Current on-screen X position of the pointer
  12245. * @return {number} X position of the pointer
  12246. */
  12247. get: function () {
  12248. return this._pointerX;
  12249. },
  12250. enumerable: true,
  12251. configurable: true
  12252. });
  12253. Object.defineProperty(Scene.prototype, "pointerY", {
  12254. /**
  12255. * Current on-screen Y position of the pointer
  12256. * @return {number} Y position of the pointer
  12257. */
  12258. get: function () {
  12259. return this._pointerY;
  12260. },
  12261. enumerable: true,
  12262. configurable: true
  12263. });
  12264. Scene.prototype.getCachedMaterial = function () {
  12265. return this._cachedMaterial;
  12266. };
  12267. Scene.prototype.getBoundingBoxRenderer = function () {
  12268. return this._boundingBoxRenderer;
  12269. };
  12270. Scene.prototype.getOutlineRenderer = function () {
  12271. return this._outlineRenderer;
  12272. };
  12273. Scene.prototype.getEngine = function () {
  12274. return this._engine;
  12275. };
  12276. Scene.prototype.getTotalVertices = function () {
  12277. return this._totalVertices;
  12278. };
  12279. Scene.prototype.getActiveIndices = function () {
  12280. return this._activeIndices;
  12281. };
  12282. Scene.prototype.getActiveParticles = function () {
  12283. return this._activeParticles;
  12284. };
  12285. Scene.prototype.getActiveBones = function () {
  12286. return this._activeBones;
  12287. };
  12288. // Stats
  12289. Scene.prototype.getLastFrameDuration = function () {
  12290. return this._lastFrameDuration;
  12291. };
  12292. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12293. return this._evaluateActiveMeshesDuration;
  12294. };
  12295. Scene.prototype.getActiveMeshes = function () {
  12296. return this._activeMeshes;
  12297. };
  12298. Scene.prototype.getRenderTargetsDuration = function () {
  12299. return this._renderTargetsDuration;
  12300. };
  12301. Scene.prototype.getRenderDuration = function () {
  12302. return this._renderDuration;
  12303. };
  12304. Scene.prototype.getParticlesDuration = function () {
  12305. return this._particlesDuration;
  12306. };
  12307. Scene.prototype.getSpritesDuration = function () {
  12308. return this._spritesDuration;
  12309. };
  12310. Scene.prototype.getAnimationRatio = function () {
  12311. return this._animationRatio;
  12312. };
  12313. Scene.prototype.getRenderId = function () {
  12314. return this._renderId;
  12315. };
  12316. Scene.prototype.incrementRenderId = function () {
  12317. this._renderId++;
  12318. };
  12319. Scene.prototype._updatePointerPosition = function (evt) {
  12320. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12321. this._pointerX = evt.clientX - canvasRect.left;
  12322. this._pointerY = evt.clientY - canvasRect.top;
  12323. if (this.cameraToUseForPointers) {
  12324. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12325. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12326. }
  12327. };
  12328. // Pointers handling
  12329. Scene.prototype.attachControl = function () {
  12330. var _this = this;
  12331. var spritePredicate = function (sprite) {
  12332. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12333. };
  12334. this._onPointerMove = function (evt) {
  12335. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12336. return;
  12337. }
  12338. var canvas = _this._engine.getRenderingCanvas();
  12339. _this._updatePointerPosition(evt);
  12340. // Meshes
  12341. 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);
  12342. if (pickResult.hit && pickResult.pickedMesh) {
  12343. _this._meshUnderPointer = pickResult.pickedMesh;
  12344. _this.setPointerOverMesh(pickResult.pickedMesh);
  12345. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12346. canvas.style.cursor = "pointer";
  12347. }
  12348. else {
  12349. canvas.style.cursor = "";
  12350. }
  12351. }
  12352. else {
  12353. // Sprites
  12354. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12355. if (pickResult.hit && pickResult.pickedSprite) {
  12356. canvas.style.cursor = "pointer";
  12357. }
  12358. else {
  12359. // Restore pointer
  12360. _this.setPointerOverMesh(null);
  12361. canvas.style.cursor = "";
  12362. _this._meshUnderPointer = null;
  12363. }
  12364. }
  12365. if (_this.onPointerMove) {
  12366. _this.onPointerMove(evt, pickResult);
  12367. }
  12368. };
  12369. this._onPointerDown = function (evt) {
  12370. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12371. return;
  12372. }
  12373. _this._updatePointerPosition(evt);
  12374. _this._startingPointerPosition.x = _this._pointerX;
  12375. _this._startingPointerPosition.y = _this._pointerY;
  12376. _this._startingPointerTime = new Date().getTime();
  12377. var predicate = null;
  12378. // Meshes
  12379. if (!_this.onPointerDown) {
  12380. predicate = function (mesh) {
  12381. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12382. };
  12383. }
  12384. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12385. if (pickResult.hit && pickResult.pickedMesh) {
  12386. if (pickResult.pickedMesh.actionManager) {
  12387. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12388. switch (evt.button) {
  12389. case 0:
  12390. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12391. break;
  12392. case 1:
  12393. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12394. break;
  12395. case 2:
  12396. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12397. break;
  12398. }
  12399. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12400. }
  12401. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12402. var that = _this;
  12403. window.setTimeout(function () {
  12404. 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);
  12405. if (pickResult.hit && pickResult.pickedMesh) {
  12406. if (pickResult.pickedMesh.actionManager) {
  12407. 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)) {
  12408. that._startingPointerTime = 0;
  12409. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12410. }
  12411. }
  12412. }
  12413. }, BABYLON.ActionManager.LongPressDelay);
  12414. }
  12415. }
  12416. }
  12417. if (_this.onPointerDown) {
  12418. _this.onPointerDown(evt, pickResult);
  12419. }
  12420. // Sprites
  12421. if (_this.spriteManagers.length > 0) {
  12422. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12423. if (pickResult.hit && pickResult.pickedSprite) {
  12424. if (pickResult.pickedSprite.actionManager) {
  12425. switch (evt.button) {
  12426. case 0:
  12427. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12428. break;
  12429. case 1:
  12430. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12431. break;
  12432. case 2:
  12433. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12434. break;
  12435. }
  12436. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12437. }
  12438. }
  12439. }
  12440. };
  12441. this._onPointerUp = function (evt) {
  12442. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12443. return;
  12444. }
  12445. var predicate = null;
  12446. _this._updatePointerPosition(evt);
  12447. if (!_this.onPointerUp) {
  12448. predicate = function (mesh) {
  12449. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12450. };
  12451. }
  12452. // Meshes
  12453. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12454. if (pickResult.hit && pickResult.pickedMesh) {
  12455. if (pickResult.pickedMesh.actionManager) {
  12456. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12457. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12458. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12459. }
  12460. }
  12461. }
  12462. if (_this.onPointerUp) {
  12463. _this.onPointerUp(evt, pickResult);
  12464. }
  12465. _this._startingPointerTime = 0;
  12466. // Sprites
  12467. if (_this.spriteManagers.length > 0) {
  12468. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12469. if (pickResult.hit && pickResult.pickedSprite) {
  12470. if (pickResult.pickedSprite.actionManager) {
  12471. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12472. }
  12473. }
  12474. }
  12475. };
  12476. this._onKeyDown = function (evt) {
  12477. if (_this.actionManager) {
  12478. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12479. }
  12480. };
  12481. this._onKeyUp = function (evt) {
  12482. if (_this.actionManager) {
  12483. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12484. }
  12485. };
  12486. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12487. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12488. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12489. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12490. // Wheel
  12491. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12492. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12493. BABYLON.Tools.RegisterTopRootEvents([
  12494. { name: "keydown", handler: this._onKeyDown },
  12495. { name: "keyup", handler: this._onKeyUp }
  12496. ]);
  12497. };
  12498. Scene.prototype.detachControl = function () {
  12499. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12500. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12501. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12502. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12503. // Wheel
  12504. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12505. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12506. BABYLON.Tools.UnregisterTopRootEvents([
  12507. { name: "keydown", handler: this._onKeyDown },
  12508. { name: "keyup", handler: this._onKeyUp }
  12509. ]);
  12510. };
  12511. // Ready
  12512. Scene.prototype.isReady = function () {
  12513. if (this._pendingData.length > 0) {
  12514. return false;
  12515. }
  12516. var index;
  12517. for (index = 0; index < this._geometries.length; index++) {
  12518. var geometry = this._geometries[index];
  12519. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12520. return false;
  12521. }
  12522. }
  12523. for (index = 0; index < this.meshes.length; index++) {
  12524. var mesh = this.meshes[index];
  12525. if (!mesh.isReady()) {
  12526. return false;
  12527. }
  12528. var mat = mesh.material;
  12529. if (mat) {
  12530. if (!mat.isReady(mesh)) {
  12531. return false;
  12532. }
  12533. }
  12534. }
  12535. return true;
  12536. };
  12537. Scene.prototype.resetCachedMaterial = function () {
  12538. this._cachedMaterial = null;
  12539. };
  12540. Scene.prototype.registerBeforeRender = function (func) {
  12541. this._onBeforeRenderCallbacks.push(func);
  12542. };
  12543. Scene.prototype.unregisterBeforeRender = function (func) {
  12544. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12545. if (index > -1) {
  12546. this._onBeforeRenderCallbacks.splice(index, 1);
  12547. }
  12548. };
  12549. Scene.prototype.registerAfterRender = function (func) {
  12550. this._onAfterRenderCallbacks.push(func);
  12551. };
  12552. Scene.prototype.unregisterAfterRender = function (func) {
  12553. var index = this._onAfterRenderCallbacks.indexOf(func);
  12554. if (index > -1) {
  12555. this._onAfterRenderCallbacks.splice(index, 1);
  12556. }
  12557. };
  12558. Scene.prototype._addPendingData = function (data) {
  12559. this._pendingData.push(data);
  12560. };
  12561. Scene.prototype._removePendingData = function (data) {
  12562. var index = this._pendingData.indexOf(data);
  12563. if (index !== -1) {
  12564. this._pendingData.splice(index, 1);
  12565. }
  12566. };
  12567. Scene.prototype.getWaitingItemsCount = function () {
  12568. return this._pendingData.length;
  12569. };
  12570. /**
  12571. * Registers a function to be executed when the scene is ready.
  12572. * @param {Function} func - the function to be executed.
  12573. */
  12574. Scene.prototype.executeWhenReady = function (func) {
  12575. var _this = this;
  12576. this._onReadyCallbacks.push(func);
  12577. if (this._executeWhenReadyTimeoutId !== -1) {
  12578. return;
  12579. }
  12580. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12581. _this._checkIsReady();
  12582. }, 150);
  12583. };
  12584. Scene.prototype._checkIsReady = function () {
  12585. var _this = this;
  12586. if (this.isReady()) {
  12587. this._onReadyCallbacks.forEach(function (func) {
  12588. func();
  12589. });
  12590. this._onReadyCallbacks = [];
  12591. this._executeWhenReadyTimeoutId = -1;
  12592. return;
  12593. }
  12594. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12595. _this._checkIsReady();
  12596. }, 150);
  12597. };
  12598. // Animations
  12599. /**
  12600. * Will start the animation sequence of a given target
  12601. * @param target - the target
  12602. * @param {number} from - from which frame should animation start
  12603. * @param {number} to - till which frame should animation run.
  12604. * @param {boolean} [loop] - should the animation loop
  12605. * @param {number} [speedRatio] - the speed in which to run the animation
  12606. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12607. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12608. * @return {BABYLON.Animatable} the animatable object created for this animation
  12609. * @see BABYLON.Animatable
  12610. * @see http://doc.babylonjs.com/page.php?p=22081
  12611. */
  12612. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12613. if (speedRatio === void 0) { speedRatio = 1.0; }
  12614. this.stopAnimation(target);
  12615. if (!animatable) {
  12616. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12617. }
  12618. // Local animations
  12619. if (target.animations) {
  12620. animatable.appendAnimations(target, target.animations);
  12621. }
  12622. // Children animations
  12623. if (target.getAnimatables) {
  12624. var animatables = target.getAnimatables();
  12625. for (var index = 0; index < animatables.length; index++) {
  12626. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12627. }
  12628. }
  12629. return animatable;
  12630. };
  12631. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12632. if (speedRatio === undefined) {
  12633. speedRatio = 1.0;
  12634. }
  12635. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12636. return animatable;
  12637. };
  12638. Scene.prototype.getAnimatableByTarget = function (target) {
  12639. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12640. if (this._activeAnimatables[index].target === target) {
  12641. return this._activeAnimatables[index];
  12642. }
  12643. }
  12644. return null;
  12645. };
  12646. Object.defineProperty(Scene.prototype, "Animatables", {
  12647. get: function () {
  12648. return this._activeAnimatables;
  12649. },
  12650. enumerable: true,
  12651. configurable: true
  12652. });
  12653. /**
  12654. * Will stop the animation of the given target
  12655. * @param target - the target
  12656. * @see beginAnimation
  12657. */
  12658. Scene.prototype.stopAnimation = function (target) {
  12659. var animatable = this.getAnimatableByTarget(target);
  12660. if (animatable) {
  12661. animatable.stop();
  12662. }
  12663. };
  12664. Scene.prototype._animate = function () {
  12665. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12666. return;
  12667. }
  12668. if (!this._animationStartDate) {
  12669. if (this._pendingData.length > 0) {
  12670. return;
  12671. }
  12672. this._animationStartDate = BABYLON.Tools.Now;
  12673. }
  12674. // Getting time
  12675. var now = BABYLON.Tools.Now;
  12676. var delay = now - this._animationStartDate;
  12677. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12678. this._activeAnimatables[index]._animate(delay);
  12679. }
  12680. };
  12681. // Matrix
  12682. Scene.prototype.getViewMatrix = function () {
  12683. return this._viewMatrix;
  12684. };
  12685. Scene.prototype.getProjectionMatrix = function () {
  12686. return this._projectionMatrix;
  12687. };
  12688. Scene.prototype.getTransformMatrix = function () {
  12689. return this._transformMatrix;
  12690. };
  12691. Scene.prototype.setTransformMatrix = function (view, projection) {
  12692. this._viewMatrix = view;
  12693. this._projectionMatrix = projection;
  12694. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12695. };
  12696. // Methods
  12697. Scene.prototype.addMesh = function (newMesh) {
  12698. newMesh.uniqueId = this._uniqueIdCounter++;
  12699. var position = this.meshes.push(newMesh);
  12700. //notify the collision coordinator
  12701. this.collisionCoordinator.onMeshAdded(newMesh);
  12702. if (this.onNewMeshAdded) {
  12703. this.onNewMeshAdded(newMesh, position, this);
  12704. }
  12705. };
  12706. Scene.prototype.removeMesh = function (toRemove) {
  12707. var index = this.meshes.indexOf(toRemove);
  12708. if (index !== -1) {
  12709. // Remove from the scene if mesh found
  12710. this.meshes.splice(index, 1);
  12711. }
  12712. //notify the collision coordinator
  12713. this.collisionCoordinator.onMeshRemoved(toRemove);
  12714. if (this.onMeshRemoved) {
  12715. this.onMeshRemoved(toRemove);
  12716. }
  12717. return index;
  12718. };
  12719. Scene.prototype.removeSkeleton = function (toRemove) {
  12720. var index = this.skeletons.indexOf(toRemove);
  12721. if (index !== -1) {
  12722. // Remove from the scene if mesh found
  12723. this.skeletons.splice(index, 1);
  12724. }
  12725. return index;
  12726. };
  12727. Scene.prototype.removeLight = function (toRemove) {
  12728. var index = this.lights.indexOf(toRemove);
  12729. if (index !== -1) {
  12730. // Remove from the scene if mesh found
  12731. this.lights.splice(index, 1);
  12732. }
  12733. if (this.onLightRemoved) {
  12734. this.onLightRemoved(toRemove);
  12735. }
  12736. return index;
  12737. };
  12738. Scene.prototype.removeCamera = function (toRemove) {
  12739. var index = this.cameras.indexOf(toRemove);
  12740. if (index !== -1) {
  12741. // Remove from the scene if mesh found
  12742. this.cameras.splice(index, 1);
  12743. }
  12744. // Remove from activeCameras
  12745. var index2 = this.activeCameras.indexOf(toRemove);
  12746. if (index2 !== -1) {
  12747. // Remove from the scene if mesh found
  12748. this.activeCameras.splice(index2, 1);
  12749. }
  12750. // Reset the activeCamera
  12751. if (this.activeCamera === toRemove) {
  12752. if (this.cameras.length > 0) {
  12753. this.activeCamera = this.cameras[0];
  12754. }
  12755. else {
  12756. this.activeCamera = null;
  12757. }
  12758. }
  12759. if (this.onCameraRemoved) {
  12760. this.onCameraRemoved(toRemove);
  12761. }
  12762. return index;
  12763. };
  12764. Scene.prototype.addLight = function (newLight) {
  12765. newLight.uniqueId = this._uniqueIdCounter++;
  12766. var position = this.lights.push(newLight);
  12767. if (this.onNewLightAdded) {
  12768. this.onNewLightAdded(newLight, position, this);
  12769. }
  12770. };
  12771. Scene.prototype.addCamera = function (newCamera) {
  12772. newCamera.uniqueId = this._uniqueIdCounter++;
  12773. var position = this.cameras.push(newCamera);
  12774. if (this.onNewCameraAdded) {
  12775. this.onNewCameraAdded(newCamera, position, this);
  12776. }
  12777. };
  12778. /**
  12779. * sets the active camera of the scene using its ID
  12780. * @param {string} id - the camera's ID
  12781. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12782. * @see activeCamera
  12783. */
  12784. Scene.prototype.setActiveCameraByID = function (id) {
  12785. var camera = this.getCameraByID(id);
  12786. if (camera) {
  12787. this.activeCamera = camera;
  12788. return camera;
  12789. }
  12790. return null;
  12791. };
  12792. /**
  12793. * sets the active camera of the scene using its name
  12794. * @param {string} name - the camera's name
  12795. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12796. * @see activeCamera
  12797. */
  12798. Scene.prototype.setActiveCameraByName = function (name) {
  12799. var camera = this.getCameraByName(name);
  12800. if (camera) {
  12801. this.activeCamera = camera;
  12802. return camera;
  12803. }
  12804. return null;
  12805. };
  12806. /**
  12807. * get a material using its id
  12808. * @param {string} the material's ID
  12809. * @return {BABYLON.Material|null} the material or null if none found.
  12810. */
  12811. Scene.prototype.getMaterialByID = function (id) {
  12812. for (var index = 0; index < this.materials.length; index++) {
  12813. if (this.materials[index].id === id) {
  12814. return this.materials[index];
  12815. }
  12816. }
  12817. return null;
  12818. };
  12819. /**
  12820. * get a material using its name
  12821. * @param {string} the material's name
  12822. * @return {BABYLON.Material|null} the material or null if none found.
  12823. */
  12824. Scene.prototype.getMaterialByName = function (name) {
  12825. for (var index = 0; index < this.materials.length; index++) {
  12826. if (this.materials[index].name === name) {
  12827. return this.materials[index];
  12828. }
  12829. }
  12830. return null;
  12831. };
  12832. Scene.prototype.getLensFlareSystemByName = function (name) {
  12833. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12834. if (this.lensFlareSystems[index].name === name) {
  12835. return this.lensFlareSystems[index];
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. Scene.prototype.getCameraByID = function (id) {
  12841. for (var index = 0; index < this.cameras.length; index++) {
  12842. if (this.cameras[index].id === id) {
  12843. return this.cameras[index];
  12844. }
  12845. }
  12846. return null;
  12847. };
  12848. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12849. for (var index = 0; index < this.cameras.length; index++) {
  12850. if (this.cameras[index].uniqueId === uniqueId) {
  12851. return this.cameras[index];
  12852. }
  12853. }
  12854. return null;
  12855. };
  12856. /**
  12857. * get a camera using its name
  12858. * @param {string} the camera's name
  12859. * @return {BABYLON.Camera|null} the camera or null if none found.
  12860. */
  12861. Scene.prototype.getCameraByName = function (name) {
  12862. for (var index = 0; index < this.cameras.length; index++) {
  12863. if (this.cameras[index].name === name) {
  12864. return this.cameras[index];
  12865. }
  12866. }
  12867. return null;
  12868. };
  12869. /**
  12870. * get a bone using its id
  12871. * @param {string} the bone's id
  12872. * @return {BABYLON.Bone|null} the bone or null if not found
  12873. */
  12874. Scene.prototype.getBoneByID = function (id) {
  12875. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12876. var skeleton = this.skeletons[skeletonIndex];
  12877. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12878. if (skeleton.bones[boneIndex].id === id) {
  12879. return skeleton.bones[boneIndex];
  12880. }
  12881. }
  12882. }
  12883. return null;
  12884. };
  12885. /**
  12886. * get a bone using its id
  12887. * @param {string} the bone's name
  12888. * @return {BABYLON.Bone|null} the bone or null if not found
  12889. */
  12890. Scene.prototype.getBoneByName = function (name) {
  12891. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12892. var skeleton = this.skeletons[skeletonIndex];
  12893. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12894. if (skeleton.bones[boneIndex].name === name) {
  12895. return skeleton.bones[boneIndex];
  12896. }
  12897. }
  12898. }
  12899. return null;
  12900. };
  12901. /**
  12902. * get a light node using its name
  12903. * @param {string} the light's name
  12904. * @return {BABYLON.Light|null} the light or null if none found.
  12905. */
  12906. Scene.prototype.getLightByName = function (name) {
  12907. for (var index = 0; index < this.lights.length; index++) {
  12908. if (this.lights[index].name === name) {
  12909. return this.lights[index];
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. /**
  12915. * get a light node using its ID
  12916. * @param {string} the light's id
  12917. * @return {BABYLON.Light|null} the light or null if none found.
  12918. */
  12919. Scene.prototype.getLightByID = function (id) {
  12920. for (var index = 0; index < this.lights.length; index++) {
  12921. if (this.lights[index].id === id) {
  12922. return this.lights[index];
  12923. }
  12924. }
  12925. return null;
  12926. };
  12927. /**
  12928. * get a light node using its scene-generated unique ID
  12929. * @param {number} the light's unique id
  12930. * @return {BABYLON.Light|null} the light or null if none found.
  12931. */
  12932. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12933. for (var index = 0; index < this.lights.length; index++) {
  12934. if (this.lights[index].uniqueId === uniqueId) {
  12935. return this.lights[index];
  12936. }
  12937. }
  12938. return null;
  12939. };
  12940. /**
  12941. * get a particle system by id
  12942. * @param id {number} the particle system id
  12943. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12944. */
  12945. Scene.prototype.getParticleSystemByID = function (id) {
  12946. for (var index = 0; index < this.particleSystems.length; index++) {
  12947. if (this.particleSystems[index].id === id) {
  12948. return this.particleSystems[index];
  12949. }
  12950. }
  12951. return null;
  12952. };
  12953. /**
  12954. * get a geometry using its ID
  12955. * @param {string} the geometry's id
  12956. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12957. */
  12958. Scene.prototype.getGeometryByID = function (id) {
  12959. for (var index = 0; index < this._geometries.length; index++) {
  12960. if (this._geometries[index].id === id) {
  12961. return this._geometries[index];
  12962. }
  12963. }
  12964. return null;
  12965. };
  12966. /**
  12967. * add a new geometry to this scene.
  12968. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12969. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12970. * @return {boolean} was the geometry added or not
  12971. */
  12972. Scene.prototype.pushGeometry = function (geometry, force) {
  12973. if (!force && this.getGeometryByID(geometry.id)) {
  12974. return false;
  12975. }
  12976. this._geometries.push(geometry);
  12977. //notify the collision coordinator
  12978. this.collisionCoordinator.onGeometryAdded(geometry);
  12979. if (this.onGeometryAdded) {
  12980. this.onGeometryAdded(geometry);
  12981. }
  12982. return true;
  12983. };
  12984. /**
  12985. * Removes an existing geometry
  12986. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12987. * @return {boolean} was the geometry removed or not
  12988. */
  12989. Scene.prototype.removeGeometry = function (geometry) {
  12990. var index = this._geometries.indexOf(geometry);
  12991. if (index > -1) {
  12992. this._geometries.splice(index, 1);
  12993. //notify the collision coordinator
  12994. this.collisionCoordinator.onGeometryDeleted(geometry);
  12995. if (this.onGeometryRemoved) {
  12996. this.onGeometryRemoved(geometry);
  12997. }
  12998. return true;
  12999. }
  13000. return false;
  13001. };
  13002. Scene.prototype.getGeometries = function () {
  13003. return this._geometries;
  13004. };
  13005. /**
  13006. * Get the first added mesh found of a given ID
  13007. * @param {string} id - the id to search for
  13008. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13009. */
  13010. Scene.prototype.getMeshByID = function (id) {
  13011. for (var index = 0; index < this.meshes.length; index++) {
  13012. if (this.meshes[index].id === id) {
  13013. return this.meshes[index];
  13014. }
  13015. }
  13016. return null;
  13017. };
  13018. /**
  13019. * Get a mesh with its auto-generated unique id
  13020. * @param {number} uniqueId - the unique id to search for
  13021. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13022. */
  13023. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13024. for (var index = 0; index < this.meshes.length; index++) {
  13025. if (this.meshes[index].uniqueId === uniqueId) {
  13026. return this.meshes[index];
  13027. }
  13028. }
  13029. return null;
  13030. };
  13031. /**
  13032. * Get a the last added mesh found of a given ID
  13033. * @param {string} id - the id to search for
  13034. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13035. */
  13036. Scene.prototype.getLastMeshByID = function (id) {
  13037. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13038. if (this.meshes[index].id === id) {
  13039. return this.meshes[index];
  13040. }
  13041. }
  13042. return null;
  13043. };
  13044. /**
  13045. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13046. * @param {string} id - the id to search for
  13047. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13048. */
  13049. Scene.prototype.getLastEntryByID = function (id) {
  13050. var index;
  13051. for (index = this.meshes.length - 1; index >= 0; index--) {
  13052. if (this.meshes[index].id === id) {
  13053. return this.meshes[index];
  13054. }
  13055. }
  13056. for (index = this.cameras.length - 1; index >= 0; index--) {
  13057. if (this.cameras[index].id === id) {
  13058. return this.cameras[index];
  13059. }
  13060. }
  13061. for (index = this.lights.length - 1; index >= 0; index--) {
  13062. if (this.lights[index].id === id) {
  13063. return this.lights[index];
  13064. }
  13065. }
  13066. return null;
  13067. };
  13068. Scene.prototype.getNodeByID = function (id) {
  13069. var mesh = this.getMeshByID(id);
  13070. if (mesh) {
  13071. return mesh;
  13072. }
  13073. var light = this.getLightByID(id);
  13074. if (light) {
  13075. return light;
  13076. }
  13077. var camera = this.getCameraByID(id);
  13078. if (camera) {
  13079. return camera;
  13080. }
  13081. var bone = this.getBoneByID(id);
  13082. return bone;
  13083. };
  13084. Scene.prototype.getNodeByName = function (name) {
  13085. var mesh = this.getMeshByName(name);
  13086. if (mesh) {
  13087. return mesh;
  13088. }
  13089. var light = this.getLightByName(name);
  13090. if (light) {
  13091. return light;
  13092. }
  13093. var camera = this.getCameraByName(name);
  13094. if (camera) {
  13095. return camera;
  13096. }
  13097. var bone = this.getBoneByName(name);
  13098. return bone;
  13099. };
  13100. Scene.prototype.getMeshByName = function (name) {
  13101. for (var index = 0; index < this.meshes.length; index++) {
  13102. if (this.meshes[index].name === name) {
  13103. return this.meshes[index];
  13104. }
  13105. }
  13106. return null;
  13107. };
  13108. Scene.prototype.getSoundByName = function (name) {
  13109. var index;
  13110. if (BABYLON.AudioEngine) {
  13111. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13112. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13113. return this.mainSoundTrack.soundCollection[index];
  13114. }
  13115. }
  13116. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13117. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13118. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13119. return this.soundTracks[sdIndex].soundCollection[index];
  13120. }
  13121. }
  13122. }
  13123. }
  13124. return null;
  13125. };
  13126. Scene.prototype.getLastSkeletonByID = function (id) {
  13127. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13128. if (this.skeletons[index].id === id) {
  13129. return this.skeletons[index];
  13130. }
  13131. }
  13132. return null;
  13133. };
  13134. Scene.prototype.getSkeletonById = function (id) {
  13135. for (var index = 0; index < this.skeletons.length; index++) {
  13136. if (this.skeletons[index].id === id) {
  13137. return this.skeletons[index];
  13138. }
  13139. }
  13140. return null;
  13141. };
  13142. Scene.prototype.getSkeletonByName = function (name) {
  13143. for (var index = 0; index < this.skeletons.length; index++) {
  13144. if (this.skeletons[index].name === name) {
  13145. return this.skeletons[index];
  13146. }
  13147. }
  13148. return null;
  13149. };
  13150. Scene.prototype.isActiveMesh = function (mesh) {
  13151. return (this._activeMeshes.indexOf(mesh) !== -1);
  13152. };
  13153. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13154. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13155. var material = subMesh.getMaterial();
  13156. if (mesh.showSubMeshesBoundingBox) {
  13157. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13158. }
  13159. if (material) {
  13160. // Render targets
  13161. if (material.getRenderTargetTextures) {
  13162. if (this._processedMaterials.indexOf(material) === -1) {
  13163. this._processedMaterials.push(material);
  13164. this._renderTargets.concat(material.getRenderTargetTextures());
  13165. }
  13166. }
  13167. // Dispatch
  13168. this._activeIndices += subMesh.indexCount;
  13169. this._renderingManager.dispatch(subMesh);
  13170. }
  13171. }
  13172. };
  13173. Scene.prototype._evaluateActiveMeshes = function () {
  13174. this.activeCamera._activeMeshes.reset();
  13175. this._activeMeshes.reset();
  13176. this._renderingManager.reset();
  13177. this._processedMaterials.reset();
  13178. this._activeParticleSystems.reset();
  13179. this._activeSkeletons.reset();
  13180. this._softwareSkinnedMeshes.reset();
  13181. this._boundingBoxRenderer.reset();
  13182. this._edgesRenderers.reset();
  13183. if (!this._frustumPlanes) {
  13184. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13185. }
  13186. else {
  13187. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13188. }
  13189. // Meshes
  13190. var meshes;
  13191. var len;
  13192. if (this._selectionOctree) {
  13193. var selection = this._selectionOctree.select(this._frustumPlanes);
  13194. meshes = selection.data;
  13195. len = selection.length;
  13196. }
  13197. else {
  13198. len = this.meshes.length;
  13199. meshes = this.meshes;
  13200. }
  13201. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13202. var mesh = meshes[meshIndex];
  13203. if (mesh.isBlocked) {
  13204. continue;
  13205. }
  13206. this._totalVertices += mesh.getTotalVertices();
  13207. if (!mesh.isReady() || !mesh.isEnabled()) {
  13208. continue;
  13209. }
  13210. mesh.computeWorldMatrix();
  13211. // Intersections
  13212. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13213. this._meshesForIntersections.pushNoDuplicate(mesh);
  13214. }
  13215. // Switch to current LOD
  13216. var meshLOD = mesh.getLOD(this.activeCamera);
  13217. if (!meshLOD) {
  13218. continue;
  13219. }
  13220. mesh._preActivate();
  13221. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13222. this._activeMeshes.push(mesh);
  13223. this.activeCamera._activeMeshes.push(mesh);
  13224. mesh._activate(this._renderId);
  13225. this._activeMesh(meshLOD);
  13226. }
  13227. }
  13228. // Particle systems
  13229. var beforeParticlesDate = BABYLON.Tools.Now;
  13230. if (this.particlesEnabled) {
  13231. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13232. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13233. var particleSystem = this.particleSystems[particleIndex];
  13234. if (!particleSystem.isStarted()) {
  13235. continue;
  13236. }
  13237. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13238. this._activeParticleSystems.push(particleSystem);
  13239. particleSystem.animate();
  13240. }
  13241. }
  13242. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13243. }
  13244. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13245. };
  13246. Scene.prototype._activeMesh = function (mesh) {
  13247. if (mesh.skeleton && this.skeletonsEnabled) {
  13248. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13249. if (!mesh.computeBonesUsingShaders) {
  13250. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13251. }
  13252. }
  13253. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13254. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13255. }
  13256. if (mesh._edgesRenderer) {
  13257. this._edgesRenderers.push(mesh._edgesRenderer);
  13258. }
  13259. if (mesh && mesh.subMeshes) {
  13260. // Submeshes Octrees
  13261. var len;
  13262. var subMeshes;
  13263. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13264. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13265. len = intersections.length;
  13266. subMeshes = intersections.data;
  13267. }
  13268. else {
  13269. subMeshes = mesh.subMeshes;
  13270. len = subMeshes.length;
  13271. }
  13272. for (var subIndex = 0; subIndex < len; subIndex++) {
  13273. var subMesh = subMeshes[subIndex];
  13274. this._evaluateSubMesh(subMesh, mesh);
  13275. }
  13276. }
  13277. };
  13278. Scene.prototype.updateTransformMatrix = function (force) {
  13279. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13280. };
  13281. Scene.prototype._renderForCamera = function (camera) {
  13282. var engine = this._engine;
  13283. this.activeCamera = camera;
  13284. if (!this.activeCamera)
  13285. throw new Error("Active camera not set");
  13286. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13287. // Viewport
  13288. engine.setViewport(this.activeCamera.viewport);
  13289. // Camera
  13290. this.resetCachedMaterial();
  13291. this._renderId++;
  13292. this.updateTransformMatrix();
  13293. if (this.beforeCameraRender) {
  13294. this.beforeCameraRender(this.activeCamera);
  13295. }
  13296. // Meshes
  13297. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13298. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13299. this._evaluateActiveMeshes();
  13300. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13301. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13302. // Skeletons
  13303. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13304. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13305. skeleton.prepare();
  13306. }
  13307. // Software skinning
  13308. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13309. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13310. mesh.applySkeleton(mesh.skeleton);
  13311. }
  13312. // Render targets
  13313. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13314. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13315. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13316. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13317. var renderTarget = this._renderTargets.data[renderIndex];
  13318. if (renderTarget._shouldRender()) {
  13319. this._renderId++;
  13320. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13321. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13322. }
  13323. }
  13324. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13325. this._renderId++;
  13326. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13327. }
  13328. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13329. // Prepare Frame
  13330. this.postProcessManager._prepareFrame();
  13331. var beforeRenderDate = BABYLON.Tools.Now;
  13332. // Backgrounds
  13333. var layerIndex;
  13334. var layer;
  13335. if (this.layers.length) {
  13336. engine.setDepthBuffer(false);
  13337. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13338. layer = this.layers[layerIndex];
  13339. if (layer.isBackground) {
  13340. layer.render();
  13341. }
  13342. }
  13343. engine.setDepthBuffer(true);
  13344. }
  13345. // Render
  13346. BABYLON.Tools.StartPerformanceCounter("Main render");
  13347. this._renderingManager.render(null, null, true, true);
  13348. BABYLON.Tools.EndPerformanceCounter("Main render");
  13349. // Bounding boxes
  13350. this._boundingBoxRenderer.render();
  13351. // Edges
  13352. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13353. this._edgesRenderers.data[edgesRendererIndex].render();
  13354. }
  13355. // Lens flares
  13356. if (this.lensFlaresEnabled) {
  13357. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13358. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13359. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13360. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13361. lensFlareSystem.render();
  13362. }
  13363. }
  13364. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13365. }
  13366. // Foregrounds
  13367. if (this.layers.length) {
  13368. engine.setDepthBuffer(false);
  13369. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13370. layer = this.layers[layerIndex];
  13371. if (!layer.isBackground) {
  13372. layer.render();
  13373. }
  13374. }
  13375. engine.setDepthBuffer(true);
  13376. }
  13377. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13378. // Finalize frame
  13379. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13380. // Update camera
  13381. this.activeCamera._updateFromScene();
  13382. // Reset some special arrays
  13383. this._renderTargets.reset();
  13384. if (this.afterCameraRender) {
  13385. this.afterCameraRender(this.activeCamera);
  13386. }
  13387. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13388. };
  13389. Scene.prototype._processSubCameras = function (camera) {
  13390. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13391. this._renderForCamera(camera);
  13392. return;
  13393. }
  13394. // rig cameras
  13395. for (var index = 0; index < camera._rigCameras.length; index++) {
  13396. this._renderForCamera(camera._rigCameras[index]);
  13397. }
  13398. this.activeCamera = camera;
  13399. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13400. // Update camera
  13401. this.activeCamera._updateFromScene();
  13402. };
  13403. Scene.prototype._checkIntersections = function () {
  13404. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13405. var sourceMesh = this._meshesForIntersections.data[index];
  13406. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13407. var action = sourceMesh.actionManager.actions[actionIndex];
  13408. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13409. var parameters = action.getTriggerParameter();
  13410. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13411. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13412. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13413. if (areIntersecting && currentIntersectionInProgress === -1) {
  13414. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13415. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13416. sourceMesh._intersectionsInProgress.push(otherMesh);
  13417. }
  13418. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13419. sourceMesh._intersectionsInProgress.push(otherMesh);
  13420. }
  13421. }
  13422. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13423. //They intersected, and now they don't.
  13424. //is this trigger an exit trigger? execute an event.
  13425. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13426. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13427. }
  13428. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13429. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13430. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13431. }
  13432. }
  13433. }
  13434. }
  13435. }
  13436. };
  13437. Scene.prototype.render = function () {
  13438. var startDate = BABYLON.Tools.Now;
  13439. this._particlesDuration = 0;
  13440. this._spritesDuration = 0;
  13441. this._activeParticles = 0;
  13442. this._renderDuration = 0;
  13443. this._renderTargetsDuration = 0;
  13444. this._evaluateActiveMeshesDuration = 0;
  13445. this._totalVertices = 0;
  13446. this._activeIndices = 0;
  13447. this._activeBones = 0;
  13448. this.getEngine().resetDrawCalls();
  13449. this._meshesForIntersections.reset();
  13450. this.resetCachedMaterial();
  13451. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13452. // Actions
  13453. if (this.actionManager) {
  13454. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13455. }
  13456. //Simplification Queue
  13457. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13458. this.simplificationQueue.executeNext();
  13459. }
  13460. // Animations
  13461. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13462. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13463. this._animate();
  13464. // Physics
  13465. if (this._physicsEngine) {
  13466. BABYLON.Tools.StartPerformanceCounter("Physics");
  13467. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13468. BABYLON.Tools.EndPerformanceCounter("Physics");
  13469. }
  13470. // Before render
  13471. if (this.beforeRender) {
  13472. this.beforeRender();
  13473. }
  13474. var callbackIndex;
  13475. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13476. this._onBeforeRenderCallbacks[callbackIndex]();
  13477. }
  13478. // Customs render targets
  13479. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13480. var engine = this.getEngine();
  13481. var currentActiveCamera = this.activeCamera;
  13482. if (this.renderTargetsEnabled) {
  13483. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13484. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13485. var renderTarget = this.customRenderTargets[customIndex];
  13486. if (renderTarget._shouldRender()) {
  13487. this._renderId++;
  13488. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13489. if (!this.activeCamera)
  13490. throw new Error("Active camera not set");
  13491. // Viewport
  13492. engine.setViewport(this.activeCamera.viewport);
  13493. // Camera
  13494. this.updateTransformMatrix();
  13495. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13496. }
  13497. }
  13498. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13499. this._renderId++;
  13500. }
  13501. if (this.customRenderTargets.length > 0) {
  13502. engine.restoreDefaultFramebuffer();
  13503. }
  13504. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13505. this.activeCamera = currentActiveCamera;
  13506. // Procedural textures
  13507. if (this.proceduralTexturesEnabled) {
  13508. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13509. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13510. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13511. if (proceduralTexture._shouldRender()) {
  13512. proceduralTexture.render();
  13513. }
  13514. }
  13515. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13516. }
  13517. // Clear
  13518. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13519. // Shadows
  13520. if (this.shadowsEnabled) {
  13521. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13522. var light = this.lights[lightIndex];
  13523. var shadowGenerator = light.getShadowGenerator();
  13524. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13525. this._renderTargets.push(shadowGenerator.getShadowMap());
  13526. }
  13527. }
  13528. }
  13529. // Depth renderer
  13530. if (this._depthRenderer) {
  13531. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13532. }
  13533. // RenderPipeline
  13534. this.postProcessRenderPipelineManager.update();
  13535. // Multi-cameras?
  13536. if (this.activeCameras.length > 0) {
  13537. var currentRenderId = this._renderId;
  13538. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13539. this._renderId = currentRenderId;
  13540. if (cameraIndex > 0) {
  13541. this._engine.clear(0, false, true);
  13542. }
  13543. this._processSubCameras(this.activeCameras[cameraIndex]);
  13544. }
  13545. }
  13546. else {
  13547. if (!this.activeCamera) {
  13548. throw new Error("No camera defined");
  13549. }
  13550. this._processSubCameras(this.activeCamera);
  13551. }
  13552. // Intersection checks
  13553. this._checkIntersections();
  13554. // Update the audio listener attached to the camera
  13555. if (BABYLON.AudioEngine) {
  13556. this._updateAudioParameters();
  13557. }
  13558. // After render
  13559. if (this.afterRender) {
  13560. this.afterRender();
  13561. }
  13562. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13563. this._onAfterRenderCallbacks[callbackIndex]();
  13564. }
  13565. // Cleaning
  13566. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13567. this._toBeDisposed.data[index].dispose();
  13568. this._toBeDisposed[index] = null;
  13569. }
  13570. this._toBeDisposed.reset();
  13571. if (this.dumpNextRenderTargets) {
  13572. this.dumpNextRenderTargets = false;
  13573. }
  13574. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13575. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13576. };
  13577. Scene.prototype._updateAudioParameters = function () {
  13578. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13579. return;
  13580. }
  13581. var listeningCamera;
  13582. var audioEngine = BABYLON.Engine.audioEngine;
  13583. if (this.activeCameras.length > 0) {
  13584. listeningCamera = this.activeCameras[0];
  13585. }
  13586. else {
  13587. listeningCamera = this.activeCamera;
  13588. }
  13589. if (listeningCamera && audioEngine.canUseWebAudio) {
  13590. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13591. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13592. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13593. cameraDirection.normalize();
  13594. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13595. var i;
  13596. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13597. var sound = this.mainSoundTrack.soundCollection[i];
  13598. if (sound.useCustomAttenuation) {
  13599. sound.updateDistanceFromListener();
  13600. }
  13601. }
  13602. for (i = 0; i < this.soundTracks.length; i++) {
  13603. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13604. sound = this.soundTracks[i].soundCollection[j];
  13605. if (sound.useCustomAttenuation) {
  13606. sound.updateDistanceFromListener();
  13607. }
  13608. }
  13609. }
  13610. }
  13611. };
  13612. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13613. // Audio
  13614. get: function () {
  13615. return this._audioEnabled;
  13616. },
  13617. set: function (value) {
  13618. this._audioEnabled = value;
  13619. if (BABYLON.AudioEngine) {
  13620. if (this._audioEnabled) {
  13621. this._enableAudio();
  13622. }
  13623. else {
  13624. this._disableAudio();
  13625. }
  13626. }
  13627. },
  13628. enumerable: true,
  13629. configurable: true
  13630. });
  13631. Scene.prototype._disableAudio = function () {
  13632. var i;
  13633. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13634. this.mainSoundTrack.soundCollection[i].pause();
  13635. }
  13636. for (i = 0; i < this.soundTracks.length; i++) {
  13637. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13638. this.soundTracks[i].soundCollection[j].pause();
  13639. }
  13640. }
  13641. };
  13642. Scene.prototype._enableAudio = function () {
  13643. var i;
  13644. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13645. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13646. this.mainSoundTrack.soundCollection[i].play();
  13647. }
  13648. }
  13649. for (i = 0; i < this.soundTracks.length; i++) {
  13650. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13651. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13652. this.soundTracks[i].soundCollection[j].play();
  13653. }
  13654. }
  13655. }
  13656. };
  13657. Object.defineProperty(Scene.prototype, "headphone", {
  13658. get: function () {
  13659. return this._headphone;
  13660. },
  13661. set: function (value) {
  13662. this._headphone = value;
  13663. if (BABYLON.AudioEngine) {
  13664. if (this._headphone) {
  13665. this._switchAudioModeForHeadphones();
  13666. }
  13667. else {
  13668. this._switchAudioModeForNormalSpeakers();
  13669. }
  13670. }
  13671. },
  13672. enumerable: true,
  13673. configurable: true
  13674. });
  13675. Scene.prototype._switchAudioModeForHeadphones = function () {
  13676. this.mainSoundTrack.switchPanningModelToHRTF();
  13677. for (var i = 0; i < this.soundTracks.length; i++) {
  13678. this.soundTracks[i].switchPanningModelToHRTF();
  13679. }
  13680. };
  13681. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13682. this.mainSoundTrack.switchPanningModelToEqualPower();
  13683. for (var i = 0; i < this.soundTracks.length; i++) {
  13684. this.soundTracks[i].switchPanningModelToEqualPower();
  13685. }
  13686. };
  13687. Scene.prototype.enableDepthRenderer = function () {
  13688. if (this._depthRenderer) {
  13689. return this._depthRenderer;
  13690. }
  13691. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13692. return this._depthRenderer;
  13693. };
  13694. Scene.prototype.disableDepthRenderer = function () {
  13695. if (!this._depthRenderer) {
  13696. return;
  13697. }
  13698. this._depthRenderer.dispose();
  13699. this._depthRenderer = null;
  13700. };
  13701. Scene.prototype.freezeMaterials = function () {
  13702. for (var i = 0; i < this.materials.length; i++) {
  13703. this.materials[i].freeze();
  13704. }
  13705. };
  13706. Scene.prototype.unfreezeMaterials = function () {
  13707. for (var i = 0; i < this.materials.length; i++) {
  13708. this.materials[i].unfreeze();
  13709. }
  13710. };
  13711. Scene.prototype.dispose = function () {
  13712. this.beforeRender = null;
  13713. this.afterRender = null;
  13714. this.skeletons = [];
  13715. this._boundingBoxRenderer.dispose();
  13716. if (this._depthRenderer) {
  13717. this._depthRenderer.dispose();
  13718. }
  13719. // Debug layer
  13720. this.debugLayer.hide();
  13721. // Events
  13722. if (this.onDispose) {
  13723. this.onDispose();
  13724. }
  13725. this._onBeforeRenderCallbacks = [];
  13726. this._onAfterRenderCallbacks = [];
  13727. this.detachControl();
  13728. // Release sounds & sounds tracks
  13729. if (BABYLON.AudioEngine) {
  13730. this.disposeSounds();
  13731. }
  13732. // Detach cameras
  13733. var canvas = this._engine.getRenderingCanvas();
  13734. var index;
  13735. for (index = 0; index < this.cameras.length; index++) {
  13736. this.cameras[index].detachControl(canvas);
  13737. }
  13738. // Release lights
  13739. while (this.lights.length) {
  13740. this.lights[0].dispose();
  13741. }
  13742. // Release meshes
  13743. while (this.meshes.length) {
  13744. this.meshes[0].dispose(true);
  13745. }
  13746. // Release cameras
  13747. while (this.cameras.length) {
  13748. this.cameras[0].dispose();
  13749. }
  13750. // Release materials
  13751. while (this.materials.length) {
  13752. this.materials[0].dispose();
  13753. }
  13754. // Release particles
  13755. while (this.particleSystems.length) {
  13756. this.particleSystems[0].dispose();
  13757. }
  13758. // Release sprites
  13759. while (this.spriteManagers.length) {
  13760. this.spriteManagers[0].dispose();
  13761. }
  13762. // Release layers
  13763. while (this.layers.length) {
  13764. this.layers[0].dispose();
  13765. }
  13766. // Release textures
  13767. while (this.textures.length) {
  13768. this.textures[0].dispose();
  13769. }
  13770. // Post-processes
  13771. this.postProcessManager.dispose();
  13772. // Physics
  13773. if (this._physicsEngine) {
  13774. this.disablePhysicsEngine();
  13775. }
  13776. // Remove from engine
  13777. index = this._engine.scenes.indexOf(this);
  13778. if (index > -1) {
  13779. this._engine.scenes.splice(index, 1);
  13780. }
  13781. this._engine.wipeCaches();
  13782. };
  13783. // Release sounds & sounds tracks
  13784. Scene.prototype.disposeSounds = function () {
  13785. this.mainSoundTrack.dispose();
  13786. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13787. this.soundTracks[scIndex].dispose();
  13788. }
  13789. };
  13790. // Octrees
  13791. Scene.prototype.getWorldExtends = function () {
  13792. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13793. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13794. for (var index = 0; index < this.meshes.length; index++) {
  13795. var mesh = this.meshes[index];
  13796. mesh.computeWorldMatrix(true);
  13797. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13798. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13799. BABYLON.Tools.CheckExtends(minBox, min, max);
  13800. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13801. }
  13802. return {
  13803. min: min,
  13804. max: max
  13805. };
  13806. };
  13807. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13808. if (maxCapacity === void 0) { maxCapacity = 64; }
  13809. if (maxDepth === void 0) { maxDepth = 2; }
  13810. if (!this._selectionOctree) {
  13811. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13812. }
  13813. var worldExtends = this.getWorldExtends();
  13814. // Update octree
  13815. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13816. return this._selectionOctree;
  13817. };
  13818. // Picking
  13819. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13820. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13821. var engine = this._engine;
  13822. if (!camera) {
  13823. if (!this.activeCamera)
  13824. throw new Error("Active camera not set");
  13825. camera = this.activeCamera;
  13826. }
  13827. var cameraViewport = camera.viewport;
  13828. var viewport = cameraViewport.toGlobal(engine);
  13829. // Moving coordinates to local viewport world
  13830. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13831. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13832. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13833. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13834. };
  13835. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13836. var engine = this._engine;
  13837. if (!camera) {
  13838. if (!this.activeCamera)
  13839. throw new Error("Active camera not set");
  13840. camera = this.activeCamera;
  13841. }
  13842. var cameraViewport = camera.viewport;
  13843. var viewport = cameraViewport.toGlobal(engine);
  13844. var identity = BABYLON.Matrix.Identity();
  13845. // Moving coordinates to local viewport world
  13846. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13847. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13848. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13849. };
  13850. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13851. var pickingInfo = null;
  13852. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13853. var mesh = this.meshes[meshIndex];
  13854. if (predicate) {
  13855. if (!predicate(mesh)) {
  13856. continue;
  13857. }
  13858. }
  13859. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13860. continue;
  13861. }
  13862. var world = mesh.getWorldMatrix();
  13863. var ray = rayFunction(world);
  13864. var result = mesh.intersects(ray, fastCheck);
  13865. if (!result || !result.hit)
  13866. continue;
  13867. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13868. continue;
  13869. pickingInfo = result;
  13870. if (fastCheck) {
  13871. break;
  13872. }
  13873. }
  13874. return pickingInfo || new BABYLON.PickingInfo();
  13875. };
  13876. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13877. var pickingInfo = null;
  13878. camera = camera || this.activeCamera;
  13879. if (this.spriteManagers.length > 0) {
  13880. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13881. var spriteManager = this.spriteManagers[spriteIndex];
  13882. if (!spriteManager.isPickable) {
  13883. continue;
  13884. }
  13885. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13886. if (!result || !result.hit)
  13887. continue;
  13888. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13889. continue;
  13890. pickingInfo = result;
  13891. if (fastCheck) {
  13892. break;
  13893. }
  13894. }
  13895. }
  13896. return pickingInfo || new BABYLON.PickingInfo();
  13897. };
  13898. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13899. var _this = this;
  13900. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13901. /// <param name="x">X position on screen</param>
  13902. /// <param name="y">Y position on screen</param>
  13903. /// <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>
  13904. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13905. /// <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>
  13906. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13907. };
  13908. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13909. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13910. /// <param name="x">X position on screen</param>
  13911. /// <param name="y">Y position on screen</param>
  13912. /// <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>
  13913. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13914. /// <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>
  13915. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13916. };
  13917. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13918. var _this = this;
  13919. return this._internalPick(function (world) {
  13920. if (!_this._pickWithRayInverseMatrix) {
  13921. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13922. }
  13923. world.invertToRef(_this._pickWithRayInverseMatrix);
  13924. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13925. }, predicate, fastCheck);
  13926. };
  13927. Scene.prototype.setPointerOverMesh = function (mesh) {
  13928. if (this._pointerOverMesh === mesh) {
  13929. return;
  13930. }
  13931. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13932. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13933. }
  13934. this._pointerOverMesh = mesh;
  13935. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13936. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13937. }
  13938. };
  13939. Scene.prototype.getPointerOverMesh = function () {
  13940. return this._pointerOverMesh;
  13941. };
  13942. // Physics
  13943. Scene.prototype.getPhysicsEngine = function () {
  13944. return this._physicsEngine;
  13945. };
  13946. /**
  13947. * Enables physics to the current scene
  13948. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13949. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13950. * @return {boolean} was the physics engine initialized
  13951. */
  13952. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13953. if (this._physicsEngine) {
  13954. return true;
  13955. }
  13956. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13957. if (!this._physicsEngine.isSupported()) {
  13958. this._physicsEngine = null;
  13959. return false;
  13960. }
  13961. this._physicsEngine._initialize(gravity);
  13962. return true;
  13963. };
  13964. Scene.prototype.disablePhysicsEngine = function () {
  13965. if (!this._physicsEngine) {
  13966. return;
  13967. }
  13968. this._physicsEngine.dispose();
  13969. this._physicsEngine = undefined;
  13970. };
  13971. Scene.prototype.isPhysicsEnabled = function () {
  13972. return this._physicsEngine !== undefined;
  13973. };
  13974. /**
  13975. * Sets the gravity of the physics engine (and NOT of the scene)
  13976. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13977. */
  13978. Scene.prototype.setGravity = function (gravity) {
  13979. if (!this._physicsEngine) {
  13980. return;
  13981. }
  13982. this._physicsEngine._setGravity(gravity);
  13983. };
  13984. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13985. if (parts.parts) {
  13986. options = parts;
  13987. parts = parts.parts;
  13988. }
  13989. if (!this._physicsEngine) {
  13990. return null;
  13991. }
  13992. for (var index = 0; index < parts.length; index++) {
  13993. var mesh = parts[index].mesh;
  13994. mesh._physicImpostor = parts[index].impostor;
  13995. mesh._physicsMass = options.mass / parts.length;
  13996. mesh._physicsFriction = options.friction;
  13997. mesh._physicRestitution = options.restitution;
  13998. }
  13999. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14000. };
  14001. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14002. for (var index = 0; index < compound.parts.length; index++) {
  14003. var mesh = compound.parts[index].mesh;
  14004. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14005. this._physicsEngine._unregisterMesh(mesh);
  14006. }
  14007. };
  14008. // Misc.
  14009. Scene.prototype.createDefaultCameraOrLight = function () {
  14010. // Light
  14011. if (this.lights.length === 0) {
  14012. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14013. }
  14014. // Camera
  14015. if (!this.activeCamera) {
  14016. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14017. // Compute position
  14018. var worldExtends = this.getWorldExtends();
  14019. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14020. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14021. camera.setTarget(worldCenter);
  14022. this.activeCamera = camera;
  14023. }
  14024. };
  14025. // Tags
  14026. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14027. if (tagsQuery === undefined) {
  14028. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14029. return list;
  14030. }
  14031. var listByTags = [];
  14032. forEach = forEach || (function (item) { return; });
  14033. for (var i in list) {
  14034. var item = list[i];
  14035. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14036. listByTags.push(item);
  14037. forEach(item);
  14038. }
  14039. }
  14040. return listByTags;
  14041. };
  14042. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14043. return this._getByTags(this.meshes, tagsQuery, forEach);
  14044. };
  14045. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14046. return this._getByTags(this.cameras, tagsQuery, forEach);
  14047. };
  14048. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14049. return this._getByTags(this.lights, tagsQuery, forEach);
  14050. };
  14051. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14052. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14053. };
  14054. // Statics
  14055. Scene._FOGMODE_NONE = 0;
  14056. Scene._FOGMODE_EXP = 1;
  14057. Scene._FOGMODE_EXP2 = 2;
  14058. Scene._FOGMODE_LINEAR = 3;
  14059. Scene.MinDeltaTime = 1.0;
  14060. Scene.MaxDeltaTime = 1000.0;
  14061. return Scene;
  14062. })();
  14063. BABYLON.Scene = Scene;
  14064. })(BABYLON || (BABYLON = {}));
  14065. var BABYLON;
  14066. (function (BABYLON) {
  14067. var VertexBuffer = (function () {
  14068. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14069. if (engine instanceof BABYLON.Mesh) {
  14070. this._engine = engine.getScene().getEngine();
  14071. }
  14072. else {
  14073. this._engine = engine;
  14074. }
  14075. this._updatable = updatable;
  14076. this._data = data;
  14077. if (!postponeInternalCreation) {
  14078. this.create();
  14079. }
  14080. this._kind = kind;
  14081. if (stride) {
  14082. this._strideSize = stride;
  14083. return;
  14084. }
  14085. // Deduce stride from kind
  14086. switch (kind) {
  14087. case VertexBuffer.PositionKind:
  14088. this._strideSize = 3;
  14089. break;
  14090. case VertexBuffer.NormalKind:
  14091. this._strideSize = 3;
  14092. break;
  14093. case VertexBuffer.UVKind:
  14094. case VertexBuffer.UV2Kind:
  14095. case VertexBuffer.UV3Kind:
  14096. case VertexBuffer.UV4Kind:
  14097. case VertexBuffer.UV5Kind:
  14098. case VertexBuffer.UV6Kind:
  14099. this._strideSize = 2;
  14100. break;
  14101. case VertexBuffer.ColorKind:
  14102. this._strideSize = 4;
  14103. break;
  14104. case VertexBuffer.MatricesIndicesKind:
  14105. case VertexBuffer.MatricesIndicesExtraKind:
  14106. this._strideSize = 4;
  14107. break;
  14108. case VertexBuffer.MatricesWeightsKind:
  14109. case VertexBuffer.MatricesWeightsExtraKind:
  14110. this._strideSize = 4;
  14111. break;
  14112. }
  14113. }
  14114. // Properties
  14115. VertexBuffer.prototype.isUpdatable = function () {
  14116. return this._updatable;
  14117. };
  14118. VertexBuffer.prototype.getData = function () {
  14119. return this._data;
  14120. };
  14121. VertexBuffer.prototype.getBuffer = function () {
  14122. return this._buffer;
  14123. };
  14124. VertexBuffer.prototype.getStrideSize = function () {
  14125. return this._strideSize;
  14126. };
  14127. // Methods
  14128. VertexBuffer.prototype.create = function (data) {
  14129. if (!data && this._buffer) {
  14130. return; // nothing to do
  14131. }
  14132. data = data || this._data;
  14133. if (!this._buffer) {
  14134. if (this._updatable) {
  14135. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14136. }
  14137. else {
  14138. this._buffer = this._engine.createVertexBuffer(data);
  14139. }
  14140. }
  14141. if (this._updatable) {
  14142. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14143. this._data = data;
  14144. }
  14145. };
  14146. VertexBuffer.prototype.update = function (data) {
  14147. this.create(data);
  14148. };
  14149. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14150. if (!this._buffer) {
  14151. return;
  14152. }
  14153. if (this._updatable) {
  14154. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14155. this._data = null;
  14156. }
  14157. };
  14158. VertexBuffer.prototype.dispose = function () {
  14159. if (!this._buffer) {
  14160. return;
  14161. }
  14162. if (this._engine._releaseBuffer(this._buffer)) {
  14163. this._buffer = null;
  14164. }
  14165. };
  14166. Object.defineProperty(VertexBuffer, "PositionKind", {
  14167. get: function () {
  14168. return VertexBuffer._PositionKind;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. Object.defineProperty(VertexBuffer, "NormalKind", {
  14174. get: function () {
  14175. return VertexBuffer._NormalKind;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(VertexBuffer, "UVKind", {
  14181. get: function () {
  14182. return VertexBuffer._UVKind;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14188. get: function () {
  14189. return VertexBuffer._UV2Kind;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14195. get: function () {
  14196. return VertexBuffer._UV3Kind;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14202. get: function () {
  14203. return VertexBuffer._UV4Kind;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14209. get: function () {
  14210. return VertexBuffer._UV5Kind;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14216. get: function () {
  14217. return VertexBuffer._UV6Kind;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(VertexBuffer, "ColorKind", {
  14223. get: function () {
  14224. return VertexBuffer._ColorKind;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14230. get: function () {
  14231. return VertexBuffer._MatricesIndicesKind;
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14237. get: function () {
  14238. return VertexBuffer._MatricesWeightsKind;
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14244. get: function () {
  14245. return VertexBuffer._MatricesIndicesExtraKind;
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14251. get: function () {
  14252. return VertexBuffer._MatricesWeightsExtraKind;
  14253. },
  14254. enumerable: true,
  14255. configurable: true
  14256. });
  14257. // Enums
  14258. VertexBuffer._PositionKind = "position";
  14259. VertexBuffer._NormalKind = "normal";
  14260. VertexBuffer._UVKind = "uv";
  14261. VertexBuffer._UV2Kind = "uv2";
  14262. VertexBuffer._UV3Kind = "uv3";
  14263. VertexBuffer._UV4Kind = "uv4";
  14264. VertexBuffer._UV5Kind = "uv5";
  14265. VertexBuffer._UV6Kind = "uv6";
  14266. VertexBuffer._ColorKind = "color";
  14267. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14268. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14269. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14270. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14271. return VertexBuffer;
  14272. })();
  14273. BABYLON.VertexBuffer = VertexBuffer;
  14274. })(BABYLON || (BABYLON = {}));
  14275. var BABYLON;
  14276. (function (BABYLON) {
  14277. /**
  14278. * Creates an instance based on a source mesh.
  14279. */
  14280. var InstancedMesh = (function (_super) {
  14281. __extends(InstancedMesh, _super);
  14282. function InstancedMesh(name, source) {
  14283. _super.call(this, name, source.getScene());
  14284. source.instances.push(this);
  14285. this._sourceMesh = source;
  14286. this.position.copyFrom(source.position);
  14287. this.rotation.copyFrom(source.rotation);
  14288. this.scaling.copyFrom(source.scaling);
  14289. if (source.rotationQuaternion) {
  14290. this.rotationQuaternion = source.rotationQuaternion.clone();
  14291. }
  14292. this.infiniteDistance = source.infiniteDistance;
  14293. this.setPivotMatrix(source.getPivotMatrix());
  14294. this.refreshBoundingInfo();
  14295. this._syncSubMeshes();
  14296. }
  14297. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14298. // Methods
  14299. get: function () {
  14300. return this._sourceMesh.receiveShadows;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(InstancedMesh.prototype, "material", {
  14306. get: function () {
  14307. return this._sourceMesh.material;
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14313. get: function () {
  14314. return this._sourceMesh.visibility;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14320. get: function () {
  14321. return this._sourceMesh.skeleton;
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14327. get: function () {
  14328. return this._sourceMesh.renderingGroupId;
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. InstancedMesh.prototype.getTotalVertices = function () {
  14334. return this._sourceMesh.getTotalVertices();
  14335. };
  14336. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14337. get: function () {
  14338. return this._sourceMesh;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14344. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14345. };
  14346. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14347. return this._sourceMesh.isVerticesDataPresent(kind);
  14348. };
  14349. InstancedMesh.prototype.getIndices = function () {
  14350. return this._sourceMesh.getIndices();
  14351. };
  14352. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14353. get: function () {
  14354. return this._sourceMesh._positions;
  14355. },
  14356. enumerable: true,
  14357. configurable: true
  14358. });
  14359. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14360. var meshBB = this._sourceMesh.getBoundingInfo();
  14361. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14362. this._updateBoundingInfo();
  14363. };
  14364. InstancedMesh.prototype._preActivate = function () {
  14365. if (this._currentLOD) {
  14366. this._currentLOD._preActivate();
  14367. }
  14368. };
  14369. InstancedMesh.prototype._activate = function (renderId) {
  14370. if (this._currentLOD) {
  14371. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14372. }
  14373. };
  14374. InstancedMesh.prototype.getLOD = function (camera) {
  14375. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14376. if (this._currentLOD === this.sourceMesh) {
  14377. return this;
  14378. }
  14379. return this._currentLOD;
  14380. };
  14381. InstancedMesh.prototype._syncSubMeshes = function () {
  14382. this.releaseSubMeshes();
  14383. if (this._sourceMesh.subMeshes) {
  14384. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14385. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14386. }
  14387. }
  14388. };
  14389. InstancedMesh.prototype._generatePointsArray = function () {
  14390. return this._sourceMesh._generatePointsArray();
  14391. };
  14392. // Clone
  14393. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14394. var result = this._sourceMesh.createInstance(name);
  14395. // Deep copy
  14396. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14397. // Bounding info
  14398. this.refreshBoundingInfo();
  14399. // Parent
  14400. if (newParent) {
  14401. result.parent = newParent;
  14402. }
  14403. if (!doNotCloneChildren) {
  14404. // Children
  14405. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14406. var mesh = this.getScene().meshes[index];
  14407. if (mesh.parent === this) {
  14408. mesh.clone(mesh.name, result);
  14409. }
  14410. }
  14411. }
  14412. result.computeWorldMatrix(true);
  14413. return result;
  14414. };
  14415. // Dispoe
  14416. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14417. // Remove from mesh
  14418. var index = this._sourceMesh.instances.indexOf(this);
  14419. this._sourceMesh.instances.splice(index, 1);
  14420. _super.prototype.dispose.call(this, doNotRecurse);
  14421. };
  14422. return InstancedMesh;
  14423. })(BABYLON.AbstractMesh);
  14424. BABYLON.InstancedMesh = InstancedMesh;
  14425. })(BABYLON || (BABYLON = {}));
  14426. var BABYLON;
  14427. (function (BABYLON) {
  14428. var _InstancesBatch = (function () {
  14429. function _InstancesBatch() {
  14430. this.mustReturn = false;
  14431. this.visibleInstances = new Array();
  14432. this.renderSelf = new Array();
  14433. }
  14434. return _InstancesBatch;
  14435. })();
  14436. BABYLON._InstancesBatch = _InstancesBatch;
  14437. var Mesh = (function (_super) {
  14438. __extends(Mesh, _super);
  14439. /**
  14440. * @constructor
  14441. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14442. * @param {Scene} scene - The scene to add this mesh to.
  14443. * @param {Node} parent - The parent of this mesh, if it has one
  14444. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14445. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14446. * When false, achieved by calling a clone(), also passing False.
  14447. * This will make creation of children, recursive.
  14448. */
  14449. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14450. if (parent === void 0) { parent = null; }
  14451. _super.call(this, name, scene);
  14452. // Members
  14453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14454. this.instances = new Array();
  14455. this._LODLevels = new Array();
  14456. this._onBeforeRenderCallbacks = new Array();
  14457. this._onAfterRenderCallbacks = new Array();
  14458. this._visibleInstances = {};
  14459. this._renderIdForInstances = new Array();
  14460. this._batchCache = new _InstancesBatch();
  14461. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14462. this._sideOrientation = Mesh._DEFAULTSIDE;
  14463. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14464. if (source) {
  14465. // Geometry
  14466. if (source._geometry) {
  14467. source._geometry.applyToMesh(this);
  14468. }
  14469. // Deep copy
  14470. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14471. this.id = name + "." + source.id;
  14472. // Material
  14473. this.material = source.material;
  14474. var index;
  14475. if (!doNotCloneChildren) {
  14476. // Children
  14477. for (index = 0; index < scene.meshes.length; index++) {
  14478. var mesh = scene.meshes[index];
  14479. if (mesh.parent === source) {
  14480. // doNotCloneChildren is always going to be False
  14481. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14482. }
  14483. }
  14484. }
  14485. // Particles
  14486. for (index = 0; index < scene.particleSystems.length; index++) {
  14487. var system = scene.particleSystems[index];
  14488. if (system.emitter === source) {
  14489. system.clone(system.name, this);
  14490. }
  14491. }
  14492. this.computeWorldMatrix(true);
  14493. }
  14494. // Parent
  14495. if (parent !== null) {
  14496. this.parent = parent;
  14497. }
  14498. }
  14499. Object.defineProperty(Mesh, "FRONTSIDE", {
  14500. get: function () {
  14501. return Mesh._FRONTSIDE;
  14502. },
  14503. enumerable: true,
  14504. configurable: true
  14505. });
  14506. Object.defineProperty(Mesh, "BACKSIDE", {
  14507. get: function () {
  14508. return Mesh._BACKSIDE;
  14509. },
  14510. enumerable: true,
  14511. configurable: true
  14512. });
  14513. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14514. get: function () {
  14515. return Mesh._DOUBLESIDE;
  14516. },
  14517. enumerable: true,
  14518. configurable: true
  14519. });
  14520. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14521. get: function () {
  14522. return Mesh._DEFAULTSIDE;
  14523. },
  14524. enumerable: true,
  14525. configurable: true
  14526. });
  14527. Object.defineProperty(Mesh, "NO_CAP", {
  14528. get: function () {
  14529. return Mesh._NO_CAP;
  14530. },
  14531. enumerable: true,
  14532. configurable: true
  14533. });
  14534. Object.defineProperty(Mesh, "CAP_START", {
  14535. get: function () {
  14536. return Mesh._CAP_START;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. Object.defineProperty(Mesh, "CAP_END", {
  14542. get: function () {
  14543. return Mesh._CAP_END;
  14544. },
  14545. enumerable: true,
  14546. configurable: true
  14547. });
  14548. Object.defineProperty(Mesh, "CAP_ALL", {
  14549. get: function () {
  14550. return Mesh._CAP_ALL;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14556. // Methods
  14557. get: function () {
  14558. return this._LODLevels.length > 0;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Mesh.prototype._sortLODLevels = function () {
  14564. this._LODLevels.sort(function (a, b) {
  14565. if (a.distance < b.distance) {
  14566. return 1;
  14567. }
  14568. if (a.distance > b.distance) {
  14569. return -1;
  14570. }
  14571. return 0;
  14572. });
  14573. };
  14574. /**
  14575. * Add a mesh as LOD level triggered at the given distance.
  14576. * @param {number} distance - the distance from the center of the object to show this level
  14577. * @param {Mesh} mesh - the mesh to be added as LOD level
  14578. * @return {Mesh} this mesh (for chaining)
  14579. */
  14580. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14581. if (mesh && mesh._masterMesh) {
  14582. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14583. return this;
  14584. }
  14585. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14586. this._LODLevels.push(level);
  14587. if (mesh) {
  14588. mesh._masterMesh = this;
  14589. }
  14590. this._sortLODLevels();
  14591. return this;
  14592. };
  14593. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14594. for (var index = 0; index < this._LODLevels.length; index++) {
  14595. var level = this._LODLevels[index];
  14596. if (level.distance === distance) {
  14597. return level.mesh;
  14598. }
  14599. }
  14600. return null;
  14601. };
  14602. /**
  14603. * Remove a mesh from the LOD array
  14604. * @param {Mesh} mesh - the mesh to be removed.
  14605. * @return {Mesh} this mesh (for chaining)
  14606. */
  14607. Mesh.prototype.removeLODLevel = function (mesh) {
  14608. for (var index = 0; index < this._LODLevels.length; index++) {
  14609. if (this._LODLevels[index].mesh === mesh) {
  14610. this._LODLevels.splice(index, 1);
  14611. if (mesh) {
  14612. mesh._masterMesh = null;
  14613. }
  14614. }
  14615. }
  14616. this._sortLODLevels();
  14617. return this;
  14618. };
  14619. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14620. if (!this._LODLevels || this._LODLevels.length === 0) {
  14621. return this;
  14622. }
  14623. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14624. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14625. if (this.onLODLevelSelection) {
  14626. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14627. }
  14628. return this;
  14629. }
  14630. for (var index = 0; index < this._LODLevels.length; index++) {
  14631. var level = this._LODLevels[index];
  14632. if (level.distance < distanceToCamera) {
  14633. if (level.mesh) {
  14634. level.mesh._preActivate();
  14635. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14636. }
  14637. if (this.onLODLevelSelection) {
  14638. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14639. }
  14640. return level.mesh;
  14641. }
  14642. }
  14643. if (this.onLODLevelSelection) {
  14644. this.onLODLevelSelection(distanceToCamera, this, this);
  14645. }
  14646. return this;
  14647. };
  14648. Object.defineProperty(Mesh.prototype, "geometry", {
  14649. get: function () {
  14650. return this._geometry;
  14651. },
  14652. enumerable: true,
  14653. configurable: true
  14654. });
  14655. Mesh.prototype.getTotalVertices = function () {
  14656. if (!this._geometry) {
  14657. return 0;
  14658. }
  14659. return this._geometry.getTotalVertices();
  14660. };
  14661. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14662. if (!this._geometry) {
  14663. return null;
  14664. }
  14665. return this._geometry.getVerticesData(kind, copyWhenShared);
  14666. };
  14667. Mesh.prototype.getVertexBuffer = function (kind) {
  14668. if (!this._geometry) {
  14669. return undefined;
  14670. }
  14671. return this._geometry.getVertexBuffer(kind);
  14672. };
  14673. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14674. if (!this._geometry) {
  14675. if (this._delayInfo) {
  14676. return this._delayInfo.indexOf(kind) !== -1;
  14677. }
  14678. return false;
  14679. }
  14680. return this._geometry.isVerticesDataPresent(kind);
  14681. };
  14682. Mesh.prototype.getVerticesDataKinds = function () {
  14683. if (!this._geometry) {
  14684. var result = [];
  14685. if (this._delayInfo) {
  14686. for (var kind in this._delayInfo) {
  14687. result.push(kind);
  14688. }
  14689. }
  14690. return result;
  14691. }
  14692. return this._geometry.getVerticesDataKinds();
  14693. };
  14694. Mesh.prototype.getTotalIndices = function () {
  14695. if (!this._geometry) {
  14696. return 0;
  14697. }
  14698. return this._geometry.getTotalIndices();
  14699. };
  14700. Mesh.prototype.getIndices = function (copyWhenShared) {
  14701. if (!this._geometry) {
  14702. return [];
  14703. }
  14704. return this._geometry.getIndices(copyWhenShared);
  14705. };
  14706. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14707. get: function () {
  14708. return this._masterMesh !== null && this._masterMesh !== undefined;
  14709. },
  14710. enumerable: true,
  14711. configurable: true
  14712. });
  14713. Mesh.prototype.isReady = function () {
  14714. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14715. return false;
  14716. }
  14717. return _super.prototype.isReady.call(this);
  14718. };
  14719. Mesh.prototype.isDisposed = function () {
  14720. return this._isDisposed;
  14721. };
  14722. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14723. get: function () {
  14724. return this._sideOrientation;
  14725. },
  14726. set: function (sideO) {
  14727. this._sideOrientation = sideO;
  14728. },
  14729. enumerable: true,
  14730. configurable: true
  14731. });
  14732. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14733. get: function () {
  14734. return this._areNormalsFrozen;
  14735. },
  14736. enumerable: true,
  14737. configurable: true
  14738. });
  14739. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14740. Mesh.prototype.freezeNormals = function () {
  14741. this._areNormalsFrozen = true;
  14742. };
  14743. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14744. Mesh.prototype.unfreezeNormals = function () {
  14745. this._areNormalsFrozen = false;
  14746. };
  14747. // Methods
  14748. Mesh.prototype._preActivate = function () {
  14749. var sceneRenderId = this.getScene().getRenderId();
  14750. if (this._preActivateId === sceneRenderId) {
  14751. return;
  14752. }
  14753. this._preActivateId = sceneRenderId;
  14754. this._visibleInstances = null;
  14755. };
  14756. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14757. if (!this._visibleInstances) {
  14758. this._visibleInstances = {};
  14759. this._visibleInstances.defaultRenderId = renderId;
  14760. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14761. }
  14762. if (!this._visibleInstances[renderId]) {
  14763. this._visibleInstances[renderId] = new Array();
  14764. }
  14765. this._visibleInstances[renderId].push(instance);
  14766. };
  14767. Mesh.prototype.refreshBoundingInfo = function () {
  14768. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14769. if (data) {
  14770. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14771. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14772. }
  14773. if (this.subMeshes) {
  14774. for (var index = 0; index < this.subMeshes.length; index++) {
  14775. this.subMeshes[index].refreshBoundingInfo();
  14776. }
  14777. }
  14778. this._updateBoundingInfo();
  14779. };
  14780. Mesh.prototype._createGlobalSubMesh = function () {
  14781. var totalVertices = this.getTotalVertices();
  14782. if (!totalVertices || !this.getIndices()) {
  14783. return null;
  14784. }
  14785. this.releaseSubMeshes();
  14786. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14787. };
  14788. Mesh.prototype.subdivide = function (count) {
  14789. if (count < 1) {
  14790. return;
  14791. }
  14792. var totalIndices = this.getTotalIndices();
  14793. var subdivisionSize = (totalIndices / count) | 0;
  14794. var offset = 0;
  14795. // Ensure that subdivisionSize is a multiple of 3
  14796. while (subdivisionSize % 3 !== 0) {
  14797. subdivisionSize++;
  14798. }
  14799. this.releaseSubMeshes();
  14800. for (var index = 0; index < count; index++) {
  14801. if (offset >= totalIndices) {
  14802. break;
  14803. }
  14804. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14805. offset += subdivisionSize;
  14806. }
  14807. this.synchronizeInstances();
  14808. };
  14809. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14810. if (!this._geometry) {
  14811. var vertexData = new BABYLON.VertexData();
  14812. vertexData.set(data, kind);
  14813. var scene = this.getScene();
  14814. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14815. }
  14816. else {
  14817. this._geometry.setVerticesData(kind, data, updatable, stride);
  14818. }
  14819. };
  14820. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14821. if (!this._geometry) {
  14822. return;
  14823. }
  14824. if (!makeItUnique) {
  14825. this._geometry.updateVerticesData(kind, data, updateExtends);
  14826. }
  14827. else {
  14828. this.makeGeometryUnique();
  14829. this.updateVerticesData(kind, data, updateExtends, false);
  14830. }
  14831. };
  14832. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14833. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14834. if (!this._geometry) {
  14835. return;
  14836. }
  14837. if (!makeItUnique) {
  14838. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14839. }
  14840. else {
  14841. this.makeGeometryUnique();
  14842. this.updateVerticesDataDirectly(kind, data, offset, false);
  14843. }
  14844. };
  14845. // Mesh positions update function :
  14846. // updates the mesh positions according to the positionFunction returned values.
  14847. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14848. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14849. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14850. if (computeNormals === void 0) { computeNormals = true; }
  14851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14852. positionFunction(positions);
  14853. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14854. if (computeNormals) {
  14855. var indices = this.getIndices();
  14856. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14857. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14858. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14859. }
  14860. };
  14861. Mesh.prototype.makeGeometryUnique = function () {
  14862. if (!this._geometry) {
  14863. return;
  14864. }
  14865. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14866. geometry.applyToMesh(this);
  14867. };
  14868. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14869. if (!this._geometry) {
  14870. var vertexData = new BABYLON.VertexData();
  14871. vertexData.indices = indices;
  14872. var scene = this.getScene();
  14873. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14874. }
  14875. else {
  14876. this._geometry.setIndices(indices, totalVertices);
  14877. }
  14878. };
  14879. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14880. var engine = this.getScene().getEngine();
  14881. // Wireframe
  14882. var indexToBind;
  14883. if (this._unIndexed) {
  14884. indexToBind = null;
  14885. }
  14886. else {
  14887. switch (fillMode) {
  14888. case BABYLON.Material.PointFillMode:
  14889. indexToBind = null;
  14890. break;
  14891. case BABYLON.Material.WireFrameFillMode:
  14892. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14893. break;
  14894. default:
  14895. case BABYLON.Material.TriangleFillMode:
  14896. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14897. break;
  14898. }
  14899. }
  14900. // VBOs
  14901. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14902. };
  14903. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14904. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14905. return;
  14906. }
  14907. var engine = this.getScene().getEngine();
  14908. // Draw order
  14909. switch (fillMode) {
  14910. case BABYLON.Material.PointFillMode:
  14911. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14912. break;
  14913. case BABYLON.Material.WireFrameFillMode:
  14914. if (this._unIndexed) {
  14915. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14916. }
  14917. else {
  14918. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14919. }
  14920. break;
  14921. default:
  14922. if (this._unIndexed) {
  14923. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14924. }
  14925. else {
  14926. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14927. }
  14928. }
  14929. };
  14930. Mesh.prototype.registerBeforeRender = function (func) {
  14931. this._onBeforeRenderCallbacks.push(func);
  14932. };
  14933. Mesh.prototype.unregisterBeforeRender = function (func) {
  14934. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14935. if (index > -1) {
  14936. this._onBeforeRenderCallbacks.splice(index, 1);
  14937. }
  14938. };
  14939. Mesh.prototype.registerAfterRender = function (func) {
  14940. this._onAfterRenderCallbacks.push(func);
  14941. };
  14942. Mesh.prototype.unregisterAfterRender = function (func) {
  14943. var index = this._onAfterRenderCallbacks.indexOf(func);
  14944. if (index > -1) {
  14945. this._onAfterRenderCallbacks.splice(index, 1);
  14946. }
  14947. };
  14948. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14949. var scene = this.getScene();
  14950. this._batchCache.mustReturn = false;
  14951. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14952. this._batchCache.visibleInstances[subMeshId] = null;
  14953. if (this._visibleInstances) {
  14954. var currentRenderId = scene.getRenderId();
  14955. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14956. var selfRenderId = this._renderId;
  14957. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14958. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14959. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14960. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14961. }
  14962. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14963. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14964. this._batchCache.mustReturn = true;
  14965. return this._batchCache;
  14966. }
  14967. if (currentRenderId !== selfRenderId) {
  14968. this._batchCache.renderSelf[subMeshId] = false;
  14969. }
  14970. }
  14971. this._renderIdForInstances[subMeshId] = currentRenderId;
  14972. }
  14973. return this._batchCache;
  14974. };
  14975. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14976. var visibleInstances = batch.visibleInstances[subMesh._id];
  14977. var matricesCount = visibleInstances.length + 1;
  14978. var bufferSize = matricesCount * 16 * 4;
  14979. while (this._instancesBufferSize < bufferSize) {
  14980. this._instancesBufferSize *= 2;
  14981. }
  14982. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14983. if (this._worldMatricesInstancesBuffer) {
  14984. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14985. }
  14986. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14987. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14988. }
  14989. var offset = 0;
  14990. var instancesCount = 0;
  14991. var world = this.getWorldMatrix();
  14992. if (batch.renderSelf[subMesh._id]) {
  14993. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14994. offset += 16;
  14995. instancesCount++;
  14996. }
  14997. if (visibleInstances) {
  14998. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14999. var instance = visibleInstances[instanceIndex];
  15000. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15001. offset += 16;
  15002. instancesCount++;
  15003. }
  15004. }
  15005. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15006. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15007. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15008. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15009. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15010. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15011. this._draw(subMesh, fillMode, instancesCount);
  15012. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15013. };
  15014. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15015. var scene = this.getScene();
  15016. var engine = scene.getEngine();
  15017. if (hardwareInstancedRendering) {
  15018. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15019. }
  15020. else {
  15021. if (batch.renderSelf[subMesh._id]) {
  15022. // Draw
  15023. if (onBeforeDraw) {
  15024. onBeforeDraw(false, this.getWorldMatrix());
  15025. }
  15026. this._draw(subMesh, fillMode);
  15027. }
  15028. if (batch.visibleInstances[subMesh._id]) {
  15029. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15030. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15031. // World
  15032. var world = instance.getWorldMatrix();
  15033. if (onBeforeDraw) {
  15034. onBeforeDraw(true, world);
  15035. }
  15036. // Draw
  15037. this._draw(subMesh, fillMode);
  15038. }
  15039. }
  15040. }
  15041. };
  15042. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15043. var scene = this.getScene();
  15044. // Managing instances
  15045. var batch = this._getInstancesRenderList(subMesh._id);
  15046. if (batch.mustReturn) {
  15047. return;
  15048. }
  15049. // Checking geometry state
  15050. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15051. return;
  15052. }
  15053. var callbackIndex;
  15054. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15055. this._onBeforeRenderCallbacks[callbackIndex](this);
  15056. }
  15057. var engine = scene.getEngine();
  15058. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15059. // Material
  15060. var effectiveMaterial = subMesh.getMaterial();
  15061. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15062. return;
  15063. }
  15064. // Outline - step 1
  15065. var savedDepthWrite = engine.getDepthWrite();
  15066. if (this.renderOutline) {
  15067. engine.setDepthWrite(false);
  15068. scene.getOutlineRenderer().render(subMesh, batch);
  15069. engine.setDepthWrite(savedDepthWrite);
  15070. }
  15071. effectiveMaterial._preBind();
  15072. var effect = effectiveMaterial.getEffect();
  15073. // Bind
  15074. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15075. this._bind(subMesh, effect, fillMode);
  15076. var world = this.getWorldMatrix();
  15077. effectiveMaterial.bind(world, this);
  15078. // Alpha mode
  15079. if (enableAlphaMode) {
  15080. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15081. }
  15082. // Draw
  15083. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15084. if (isInstance) {
  15085. effectiveMaterial.bindOnlyWorldMatrix(world);
  15086. }
  15087. });
  15088. // Unbind
  15089. effectiveMaterial.unbind();
  15090. // Outline - step 2
  15091. if (this.renderOutline && savedDepthWrite) {
  15092. engine.setDepthWrite(true);
  15093. engine.setColorWrite(false);
  15094. scene.getOutlineRenderer().render(subMesh, batch);
  15095. engine.setColorWrite(true);
  15096. }
  15097. // Overlay
  15098. if (this.renderOverlay) {
  15099. var currentMode = engine.getAlphaMode();
  15100. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15101. scene.getOutlineRenderer().render(subMesh, batch, true);
  15102. engine.setAlphaMode(currentMode);
  15103. }
  15104. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15105. this._onAfterRenderCallbacks[callbackIndex](this);
  15106. }
  15107. };
  15108. Mesh.prototype.getEmittedParticleSystems = function () {
  15109. var results = new Array();
  15110. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15111. var particleSystem = this.getScene().particleSystems[index];
  15112. if (particleSystem.emitter === this) {
  15113. results.push(particleSystem);
  15114. }
  15115. }
  15116. return results;
  15117. };
  15118. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15119. var results = new Array();
  15120. var descendants = this.getDescendants();
  15121. descendants.push(this);
  15122. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15123. var particleSystem = this.getScene().particleSystems[index];
  15124. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15125. results.push(particleSystem);
  15126. }
  15127. }
  15128. return results;
  15129. };
  15130. Mesh.prototype.getChildren = function () {
  15131. var results = [];
  15132. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15133. var mesh = this.getScene().meshes[index];
  15134. if (mesh.parent === this) {
  15135. results.push(mesh);
  15136. }
  15137. }
  15138. return results;
  15139. };
  15140. Mesh.prototype._checkDelayState = function () {
  15141. var _this = this;
  15142. var that = this;
  15143. var scene = this.getScene();
  15144. if (this._geometry) {
  15145. this._geometry.load(scene);
  15146. }
  15147. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15148. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15149. scene._addPendingData(that);
  15150. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15151. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15152. if (data instanceof ArrayBuffer) {
  15153. _this._delayLoadingFunction(data, _this);
  15154. }
  15155. else {
  15156. _this._delayLoadingFunction(JSON.parse(data), _this);
  15157. }
  15158. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15159. scene._removePendingData(_this);
  15160. }, function () { }, scene.database, getBinaryData);
  15161. }
  15162. };
  15163. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15164. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15165. return false;
  15166. }
  15167. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15168. return false;
  15169. }
  15170. this._checkDelayState();
  15171. return true;
  15172. };
  15173. Mesh.prototype.setMaterialByID = function (id) {
  15174. var materials = this.getScene().materials;
  15175. var index;
  15176. for (index = 0; index < materials.length; index++) {
  15177. if (materials[index].id === id) {
  15178. this.material = materials[index];
  15179. return;
  15180. }
  15181. }
  15182. // Multi
  15183. var multiMaterials = this.getScene().multiMaterials;
  15184. for (index = 0; index < multiMaterials.length; index++) {
  15185. if (multiMaterials[index].id === id) {
  15186. this.material = multiMaterials[index];
  15187. return;
  15188. }
  15189. }
  15190. };
  15191. Mesh.prototype.getAnimatables = function () {
  15192. var results = [];
  15193. if (this.material) {
  15194. results.push(this.material);
  15195. }
  15196. if (this.skeleton) {
  15197. results.push(this.skeleton);
  15198. }
  15199. return results;
  15200. };
  15201. // Geometry
  15202. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15203. // Position
  15204. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15205. return;
  15206. }
  15207. this._resetPointsArrayCache();
  15208. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15209. var temp = [];
  15210. var index;
  15211. for (index = 0; index < data.length; index += 3) {
  15212. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15213. }
  15214. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15215. // Normals
  15216. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15217. return;
  15218. }
  15219. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15220. temp = [];
  15221. for (index = 0; index < data.length; index += 3) {
  15222. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15223. }
  15224. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15225. // flip faces?
  15226. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15227. this.flipFaces();
  15228. }
  15229. };
  15230. // Will apply current transform to mesh and reset world matrix
  15231. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15232. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15233. this.scaling.copyFromFloats(1, 1, 1);
  15234. this.position.copyFromFloats(0, 0, 0);
  15235. this.rotation.copyFromFloats(0, 0, 0);
  15236. //only if quaternion is already set
  15237. if (this.rotationQuaternion) {
  15238. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15239. }
  15240. this._worldMatrix = BABYLON.Matrix.Identity();
  15241. };
  15242. // Cache
  15243. Mesh.prototype._resetPointsArrayCache = function () {
  15244. this._positions = null;
  15245. };
  15246. Mesh.prototype._generatePointsArray = function () {
  15247. if (this._positions)
  15248. return true;
  15249. this._positions = [];
  15250. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15251. if (!data) {
  15252. return false;
  15253. }
  15254. for (var index = 0; index < data.length; index += 3) {
  15255. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15256. }
  15257. return true;
  15258. };
  15259. // Clone
  15260. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15261. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15262. };
  15263. // Dispose
  15264. Mesh.prototype.dispose = function (doNotRecurse) {
  15265. if (this._geometry) {
  15266. this._geometry.releaseForMesh(this, true);
  15267. }
  15268. // Instances
  15269. if (this._worldMatricesInstancesBuffer) {
  15270. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15271. this._worldMatricesInstancesBuffer = null;
  15272. }
  15273. while (this.instances.length) {
  15274. this.instances[0].dispose();
  15275. }
  15276. _super.prototype.dispose.call(this, doNotRecurse);
  15277. };
  15278. // Geometric tools
  15279. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15280. var _this = this;
  15281. var scene = this.getScene();
  15282. var onload = function (img) {
  15283. // Getting height map data
  15284. var canvas = document.createElement("canvas");
  15285. var context = canvas.getContext("2d");
  15286. var heightMapWidth = img.width;
  15287. var heightMapHeight = img.height;
  15288. canvas.width = heightMapWidth;
  15289. canvas.height = heightMapHeight;
  15290. context.drawImage(img, 0, 0);
  15291. // Create VertexData from map data
  15292. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15293. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15294. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15295. //execute success callback, if set
  15296. if (onSuccess) {
  15297. onSuccess(_this);
  15298. }
  15299. };
  15300. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15301. };
  15302. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15303. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15304. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15305. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15306. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15307. return;
  15308. }
  15309. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15310. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15311. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15312. var position = BABYLON.Vector3.Zero();
  15313. var normal = BABYLON.Vector3.Zero();
  15314. var uv = BABYLON.Vector2.Zero();
  15315. for (var index = 0; index < positions.length; index += 3) {
  15316. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15317. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15318. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15319. // Compute height
  15320. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15321. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15322. var pos = (u + v * heightMapWidth) * 4;
  15323. var r = buffer[pos] / 255.0;
  15324. var g = buffer[pos + 1] / 255.0;
  15325. var b = buffer[pos + 2] / 255.0;
  15326. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15327. normal.normalize();
  15328. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15329. position = position.add(normal);
  15330. position.toArray(positions, index);
  15331. }
  15332. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15333. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15334. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15335. };
  15336. Mesh.prototype.convertToFlatShadedMesh = function () {
  15337. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15338. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15339. var kinds = this.getVerticesDataKinds();
  15340. var vbs = [];
  15341. var data = [];
  15342. var newdata = [];
  15343. var updatableNormals = false;
  15344. var kindIndex;
  15345. var kind;
  15346. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15347. kind = kinds[kindIndex];
  15348. var vertexBuffer = this.getVertexBuffer(kind);
  15349. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15350. updatableNormals = vertexBuffer.isUpdatable();
  15351. kinds.splice(kindIndex, 1);
  15352. kindIndex--;
  15353. continue;
  15354. }
  15355. vbs[kind] = vertexBuffer;
  15356. data[kind] = vbs[kind].getData();
  15357. newdata[kind] = [];
  15358. }
  15359. // Save previous submeshes
  15360. var previousSubmeshes = this.subMeshes.slice(0);
  15361. var indices = this.getIndices();
  15362. var totalIndices = this.getTotalIndices();
  15363. // Generating unique vertices per face
  15364. var index;
  15365. for (index = 0; index < totalIndices; index++) {
  15366. var vertexIndex = indices[index];
  15367. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15368. kind = kinds[kindIndex];
  15369. var stride = vbs[kind].getStrideSize();
  15370. for (var offset = 0; offset < stride; offset++) {
  15371. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15372. }
  15373. }
  15374. }
  15375. // Updating faces & normal
  15376. var normals = [];
  15377. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15378. for (index = 0; index < totalIndices; index += 3) {
  15379. indices[index] = index;
  15380. indices[index + 1] = index + 1;
  15381. indices[index + 2] = index + 2;
  15382. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15383. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15384. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15385. var p1p2 = p1.subtract(p2);
  15386. var p3p2 = p3.subtract(p2);
  15387. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15388. // Store same normals for every vertex
  15389. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15390. normals.push(normal.x);
  15391. normals.push(normal.y);
  15392. normals.push(normal.z);
  15393. }
  15394. }
  15395. this.setIndices(indices);
  15396. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15397. // Updating vertex buffers
  15398. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15399. kind = kinds[kindIndex];
  15400. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15401. }
  15402. // Updating submeshes
  15403. this.releaseSubMeshes();
  15404. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15405. var previousOne = previousSubmeshes[submeshIndex];
  15406. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15407. }
  15408. this.synchronizeInstances();
  15409. };
  15410. Mesh.prototype.convertToUnIndexedMesh = function () {
  15411. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15412. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15413. var kinds = this.getVerticesDataKinds();
  15414. var vbs = [];
  15415. var data = [];
  15416. var newdata = [];
  15417. var updatableNormals = false;
  15418. var kindIndex;
  15419. var kind;
  15420. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15421. kind = kinds[kindIndex];
  15422. var vertexBuffer = this.getVertexBuffer(kind);
  15423. vbs[kind] = vertexBuffer;
  15424. data[kind] = vbs[kind].getData();
  15425. newdata[kind] = [];
  15426. }
  15427. // Save previous submeshes
  15428. var previousSubmeshes = this.subMeshes.slice(0);
  15429. var indices = this.getIndices();
  15430. var totalIndices = this.getTotalIndices();
  15431. // Generating unique vertices per face
  15432. var index;
  15433. for (index = 0; index < totalIndices; index++) {
  15434. var vertexIndex = indices[index];
  15435. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15436. kind = kinds[kindIndex];
  15437. var stride = vbs[kind].getStrideSize();
  15438. for (var offset = 0; offset < stride; offset++) {
  15439. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15440. }
  15441. }
  15442. }
  15443. // Updating indices
  15444. for (index = 0; index < totalIndices; index += 3) {
  15445. indices[index] = index;
  15446. indices[index + 1] = index + 1;
  15447. indices[index + 2] = index + 2;
  15448. }
  15449. this.setIndices(indices);
  15450. // Updating vertex buffers
  15451. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15452. kind = kinds[kindIndex];
  15453. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15454. }
  15455. // Updating submeshes
  15456. this.releaseSubMeshes();
  15457. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15458. var previousOne = previousSubmeshes[submeshIndex];
  15459. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15460. }
  15461. this._unIndexed = true;
  15462. this.synchronizeInstances();
  15463. };
  15464. // will inverse faces orientations, and invert normals too if specified
  15465. Mesh.prototype.flipFaces = function (flipNormals) {
  15466. if (flipNormals === void 0) { flipNormals = false; }
  15467. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15468. var i;
  15469. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15470. for (i = 0; i < vertex_data.normals.length; i++) {
  15471. vertex_data.normals[i] *= -1;
  15472. }
  15473. }
  15474. var temp;
  15475. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15476. // reassign indices
  15477. temp = vertex_data.indices[i + 1];
  15478. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15479. vertex_data.indices[i + 2] = temp;
  15480. }
  15481. vertex_data.applyToMesh(this);
  15482. };
  15483. // Instances
  15484. Mesh.prototype.createInstance = function (name) {
  15485. return new BABYLON.InstancedMesh(name, this);
  15486. };
  15487. Mesh.prototype.synchronizeInstances = function () {
  15488. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15489. var instance = this.instances[instanceIndex];
  15490. instance._syncSubMeshes();
  15491. }
  15492. };
  15493. /**
  15494. * Simplify the mesh according to the given array of settings.
  15495. * Function will return immediately and will simplify async.
  15496. * @param settings a collection of simplification settings.
  15497. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15498. * @param type the type of simplification to run.
  15499. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15500. */
  15501. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15502. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15503. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15504. this.getScene().simplificationQueue.addTask({
  15505. settings: settings,
  15506. parallelProcessing: parallelProcessing,
  15507. mesh: this,
  15508. simplificationType: simplificationType,
  15509. successCallback: successCallback
  15510. });
  15511. };
  15512. /**
  15513. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15514. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15515. * This should be used together with the simplification to avoid disappearing triangles.
  15516. * @param successCallback an optional success callback to be called after the optimization finished.
  15517. */
  15518. Mesh.prototype.optimizeIndices = function (successCallback) {
  15519. var _this = this;
  15520. var indices = this.getIndices();
  15521. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15522. var vectorPositions = [];
  15523. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15524. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15525. }
  15526. var dupes = [];
  15527. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15528. var realPos = vectorPositions.length - 1 - iteration;
  15529. var testedPosition = vectorPositions[realPos];
  15530. for (var j = 0; j < realPos; ++j) {
  15531. var againstPosition = vectorPositions[j];
  15532. if (testedPosition.equals(againstPosition)) {
  15533. dupes[realPos] = j;
  15534. break;
  15535. }
  15536. }
  15537. }, function () {
  15538. for (var i = 0; i < indices.length; ++i) {
  15539. indices[i] = dupes[indices[i]] || indices[i];
  15540. }
  15541. //indices are now reordered
  15542. var originalSubMeshes = _this.subMeshes.slice(0);
  15543. _this.setIndices(indices);
  15544. _this.subMeshes = originalSubMeshes;
  15545. if (successCallback) {
  15546. successCallback(_this);
  15547. }
  15548. });
  15549. };
  15550. // Statics
  15551. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15552. var mesh = new Mesh(parsedMesh.name, scene);
  15553. mesh.id = parsedMesh.id;
  15554. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15555. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15556. if (parsedMesh.rotationQuaternion) {
  15557. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15558. }
  15559. else if (parsedMesh.rotation) {
  15560. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15561. }
  15562. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15563. if (parsedMesh.localMatrix) {
  15564. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15565. }
  15566. else if (parsedMesh.pivotMatrix) {
  15567. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15568. }
  15569. mesh.setEnabled(parsedMesh.isEnabled);
  15570. mesh.isVisible = parsedMesh.isVisible;
  15571. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15572. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15573. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15574. if (parsedMesh.applyFog !== undefined) {
  15575. mesh.applyFog = parsedMesh.applyFog;
  15576. }
  15577. if (parsedMesh.pickable !== undefined) {
  15578. mesh.isPickable = parsedMesh.pickable;
  15579. }
  15580. if (parsedMesh.alphaIndex !== undefined) {
  15581. mesh.alphaIndex = parsedMesh.alphaIndex;
  15582. }
  15583. mesh.receiveShadows = parsedMesh.receiveShadows;
  15584. mesh.billboardMode = parsedMesh.billboardMode;
  15585. if (parsedMesh.visibility !== undefined) {
  15586. mesh.visibility = parsedMesh.visibility;
  15587. }
  15588. mesh.checkCollisions = parsedMesh.checkCollisions;
  15589. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15590. // freezeWorldMatrix
  15591. if (parsedMesh.freezeWorldMatrix) {
  15592. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15593. }
  15594. // Parent
  15595. if (parsedMesh.parentId) {
  15596. mesh._waitingParentId = parsedMesh.parentId;
  15597. }
  15598. // Actions
  15599. if (parsedMesh.actions !== undefined) {
  15600. mesh._waitingActions = parsedMesh.actions;
  15601. }
  15602. // Geometry
  15603. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15604. if (parsedMesh.delayLoadingFile) {
  15605. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15606. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15607. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15608. if (parsedMesh._binaryInfo) {
  15609. mesh._binaryInfo = parsedMesh._binaryInfo;
  15610. }
  15611. mesh._delayInfo = [];
  15612. if (parsedMesh.hasUVs) {
  15613. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15614. }
  15615. if (parsedMesh.hasUVs2) {
  15616. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15617. }
  15618. if (parsedMesh.hasUVs3) {
  15619. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15620. }
  15621. if (parsedMesh.hasUVs4) {
  15622. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15623. }
  15624. if (parsedMesh.hasUVs5) {
  15625. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15626. }
  15627. if (parsedMesh.hasUVs6) {
  15628. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15629. }
  15630. if (parsedMesh.hasColors) {
  15631. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15632. }
  15633. if (parsedMesh.hasMatricesIndices) {
  15634. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15635. }
  15636. if (parsedMesh.hasMatricesWeights) {
  15637. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15638. }
  15639. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15640. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15641. mesh._checkDelayState();
  15642. }
  15643. }
  15644. else {
  15645. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15646. }
  15647. // Material
  15648. if (parsedMesh.materialId) {
  15649. mesh.setMaterialByID(parsedMesh.materialId);
  15650. }
  15651. else {
  15652. mesh.material = null;
  15653. }
  15654. // Skeleton
  15655. if (parsedMesh.skeletonId > -1) {
  15656. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15657. if (parsedMesh.numBoneInfluencers) {
  15658. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15659. }
  15660. }
  15661. // Physics
  15662. if (parsedMesh.physicsImpostor) {
  15663. if (!scene.isPhysicsEnabled()) {
  15664. scene.enablePhysics();
  15665. }
  15666. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15667. }
  15668. // Animations
  15669. if (parsedMesh.animations) {
  15670. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15671. var parsedAnimation = parsedMesh.animations[animationIndex];
  15672. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15673. }
  15674. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15675. }
  15676. if (parsedMesh.autoAnimate) {
  15677. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15678. }
  15679. // Layer Mask
  15680. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15681. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15682. }
  15683. else {
  15684. mesh.layerMask = 0x0FFFFFFF;
  15685. }
  15686. // Instances
  15687. if (parsedMesh.instances) {
  15688. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15689. var parsedInstance = parsedMesh.instances[index];
  15690. var instance = mesh.createInstance(parsedInstance.name);
  15691. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15692. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15693. if (parsedInstance.rotationQuaternion) {
  15694. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15695. }
  15696. else if (parsedInstance.rotation) {
  15697. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15698. }
  15699. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15700. instance.checkCollisions = mesh.checkCollisions;
  15701. if (parsedMesh.animations) {
  15702. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15703. parsedAnimation = parsedMesh.animations[animationIndex];
  15704. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15705. }
  15706. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15707. }
  15708. }
  15709. }
  15710. return mesh;
  15711. };
  15712. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15713. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15714. pathArray: pathArray,
  15715. closeArray: closeArray,
  15716. closePath: closePath,
  15717. offset: offset,
  15718. updatable: updatable,
  15719. sideOrientation: sideOrientation,
  15720. instance: instance
  15721. }, scene);
  15722. };
  15723. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15724. var options = {
  15725. radius: radius,
  15726. tessellation: tessellation,
  15727. sideOrientation: sideOrientation,
  15728. updatable: updatable
  15729. };
  15730. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15731. };
  15732. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15733. var options = {
  15734. size: size,
  15735. sideOrientation: sideOrientation,
  15736. updatable: updatable
  15737. };
  15738. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15739. };
  15740. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15741. var options = {
  15742. segments: segments,
  15743. diameterX: diameter,
  15744. diameterY: diameter,
  15745. diameterZ: diameter,
  15746. sideOrientation: sideOrientation,
  15747. updatable: updatable
  15748. };
  15749. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15750. };
  15751. // Cylinder and cone
  15752. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15753. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15754. if (scene !== undefined) {
  15755. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15756. updatable = scene;
  15757. }
  15758. scene = subdivisions;
  15759. subdivisions = 1;
  15760. }
  15761. var options = {
  15762. height: height,
  15763. diameterTop: diameterTop,
  15764. diameterBottom: diameterBottom,
  15765. tessellation: tessellation,
  15766. subdivisions: subdivisions,
  15767. sideOrientation: sideOrientation,
  15768. updatable: updatable
  15769. };
  15770. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15771. };
  15772. // Torus (Code from SharpDX.org)
  15773. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15774. var options = {
  15775. diameter: diameter,
  15776. thickness: thickness,
  15777. tessellation: tessellation,
  15778. sideOrientation: sideOrientation,
  15779. updatable: updatable
  15780. };
  15781. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15782. };
  15783. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15784. var options = {
  15785. radius: radius,
  15786. tube: tube,
  15787. radialSegments: radialSegments,
  15788. tubularSegments: tubularSegments,
  15789. p: p,
  15790. q: q,
  15791. sideOrientation: sideOrientation,
  15792. updatable: updatable
  15793. };
  15794. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15795. };
  15796. // Lines
  15797. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15798. var options = {
  15799. points: points,
  15800. updatable: updatable,
  15801. instance: instance
  15802. };
  15803. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15804. };
  15805. // Dashed Lines
  15806. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15807. var options = {
  15808. points: points,
  15809. dashSize: dashSize,
  15810. gapSize: gapSize,
  15811. dashNb: dashNb,
  15812. updatable: updatable
  15813. };
  15814. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15815. };
  15816. // Extrusion
  15817. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15818. var options = {
  15819. shape: shape,
  15820. path: path,
  15821. scale: scale,
  15822. rotation: rotation,
  15823. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15824. sideOrientation: sideOrientation,
  15825. instance: instance,
  15826. updatable: updatable
  15827. };
  15828. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15829. };
  15830. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15831. var options = {
  15832. shape: shape,
  15833. path: path,
  15834. scaleFunction: scaleFunction,
  15835. rotationFunction: rotationFunction,
  15836. ribbonCloseArray: ribbonCloseArray,
  15837. ribbonClosePath: ribbonClosePath,
  15838. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15839. sideOrientation: sideOrientation,
  15840. instance: instance,
  15841. updatable: updatable
  15842. };
  15843. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15844. };
  15845. // Lathe
  15846. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15847. var options = {
  15848. shape: shape,
  15849. radius: radius,
  15850. tessellation: tessellation,
  15851. sideOrientation: sideOrientation,
  15852. updatable: updatable
  15853. };
  15854. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15855. };
  15856. // Plane & ground
  15857. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15858. var options = {
  15859. size: size,
  15860. width: size,
  15861. height: size,
  15862. sideOrientation: sideOrientation,
  15863. updatable: updatable
  15864. };
  15865. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15866. };
  15867. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15868. var options = {
  15869. width: width,
  15870. height: height,
  15871. subdivisions: subdivisions,
  15872. updatable: updatable
  15873. };
  15874. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15875. };
  15876. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15877. var options = {
  15878. xmin: xmin,
  15879. zmin: zmin,
  15880. xmax: xmax,
  15881. zmax: zmax,
  15882. subdivisions: subdivisions,
  15883. precision: precision,
  15884. updatable: updatable
  15885. };
  15886. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15887. };
  15888. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15889. var options = {
  15890. width: width,
  15891. height: height,
  15892. subdivisions: subdivisions,
  15893. minHeight: minHeight,
  15894. maxHeight: maxHeight,
  15895. updatable: updatable,
  15896. onReady: onReady
  15897. };
  15898. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15899. };
  15900. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15901. var options = {
  15902. path: path,
  15903. radius: radius,
  15904. tessellation: tessellation,
  15905. radiusFunction: radiusFunction,
  15906. arc: 1,
  15907. cap: cap,
  15908. updatable: updatable,
  15909. sideOrientation: sideOrientation,
  15910. instance: instance
  15911. };
  15912. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15913. };
  15914. Mesh.CreatePolyhedron = function (name, options, scene) {
  15915. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15916. };
  15917. Mesh.CreateIcoSphere = function (name, options, scene) {
  15918. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15919. };
  15920. // Decals
  15921. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15922. var options = {
  15923. position: position,
  15924. normal: normal,
  15925. size: size,
  15926. angle: angle
  15927. };
  15928. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15929. };
  15930. // Skeletons
  15931. /**
  15932. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15933. */
  15934. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15935. var source;
  15936. if (!this._sourcePositions) {
  15937. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15938. this._sourcePositions = new Float32Array(source);
  15939. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15940. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15941. }
  15942. }
  15943. return this._sourcePositions;
  15944. };
  15945. /**
  15946. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15947. */
  15948. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15949. var source;
  15950. if (!this._sourceNormals) {
  15951. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15952. this._sourceNormals = new Float32Array(source);
  15953. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15954. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15955. }
  15956. }
  15957. return this._sourceNormals;
  15958. };
  15959. /**
  15960. * Update the vertex buffers by applying transformation from the bones
  15961. * @param {skeleton} skeleton to apply
  15962. */
  15963. Mesh.prototype.applySkeleton = function (skeleton) {
  15964. if (!this.geometry) {
  15965. return;
  15966. }
  15967. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  15968. return;
  15969. }
  15970. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  15971. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15972. return this;
  15973. }
  15974. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15975. return this;
  15976. }
  15977. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15978. return this;
  15979. }
  15980. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15981. return this;
  15982. }
  15983. if (!this._sourcePositions) {
  15984. this.setPositionsForCPUSkinning();
  15985. }
  15986. if (!this._sourceNormals) {
  15987. this.setNormalsForCPUSkinning();
  15988. }
  15989. // positionsData checks for not being Float32Array will only pass at most once
  15990. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15991. if (!(positionsData instanceof Float32Array)) {
  15992. positionsData = new Float32Array(positionsData);
  15993. }
  15994. // normalsData checks for not being Float32Array will only pass at most once
  15995. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15996. if (!(normalsData instanceof Float32Array)) {
  15997. normalsData = new Float32Array(normalsData);
  15998. }
  15999. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16000. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16001. var needExtras = this.numBoneInfluencers > 4;
  16002. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16003. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16004. var skeletonMatrices = skeleton.getTransformMatrices();
  16005. var tempVector3 = BABYLON.Vector3.Zero();
  16006. var finalMatrix = new BABYLON.Matrix();
  16007. var tempMatrix = new BABYLON.Matrix();
  16008. var matWeightIdx = 0;
  16009. var inf;
  16010. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16011. var weight;
  16012. for (inf = 0; inf < 4; inf++) {
  16013. weight = matricesWeightsData[matWeightIdx + inf];
  16014. if (weight > 0) {
  16015. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16016. finalMatrix.addToSelf(tempMatrix);
  16017. }
  16018. else
  16019. break;
  16020. }
  16021. if (needExtras) {
  16022. for (inf = 0; inf < 4; inf++) {
  16023. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16024. if (weight > 0) {
  16025. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16026. finalMatrix.addToSelf(tempMatrix);
  16027. }
  16028. else
  16029. break;
  16030. }
  16031. }
  16032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16033. tempVector3.toArray(positionsData, index);
  16034. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16035. tempVector3.toArray(normalsData, index);
  16036. finalMatrix.reset();
  16037. }
  16038. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16039. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16040. return this;
  16041. };
  16042. // Tools
  16043. Mesh.MinMax = function (meshes) {
  16044. var minVector = null;
  16045. var maxVector = null;
  16046. for (var i in meshes) {
  16047. var mesh = meshes[i];
  16048. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16049. if (!minVector) {
  16050. minVector = boundingBox.minimumWorld;
  16051. maxVector = boundingBox.maximumWorld;
  16052. continue;
  16053. }
  16054. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16055. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16056. }
  16057. return {
  16058. min: minVector,
  16059. max: maxVector
  16060. };
  16061. };
  16062. Mesh.Center = function (meshesOrMinMaxVector) {
  16063. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16064. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16065. };
  16066. /**
  16067. * Merge the array of meshes into a single mesh for performance reasons.
  16068. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16069. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16070. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16071. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16072. */
  16073. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16074. if (disposeSource === void 0) { disposeSource = true; }
  16075. var index;
  16076. if (!allow32BitsIndices) {
  16077. var totalVertices = 0;
  16078. // Counting vertices
  16079. for (index = 0; index < meshes.length; index++) {
  16080. if (meshes[index]) {
  16081. totalVertices += meshes[index].getTotalVertices();
  16082. if (totalVertices > 65536) {
  16083. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16084. return null;
  16085. }
  16086. }
  16087. }
  16088. }
  16089. // Merge
  16090. var vertexData;
  16091. var otherVertexData;
  16092. var source;
  16093. for (index = 0; index < meshes.length; index++) {
  16094. if (meshes[index]) {
  16095. meshes[index].computeWorldMatrix(true);
  16096. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16097. otherVertexData.transform(meshes[index].getWorldMatrix());
  16098. if (vertexData) {
  16099. vertexData.merge(otherVertexData);
  16100. }
  16101. else {
  16102. vertexData = otherVertexData;
  16103. source = meshes[index];
  16104. }
  16105. }
  16106. }
  16107. if (!meshSubclass) {
  16108. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16109. }
  16110. vertexData.applyToMesh(meshSubclass);
  16111. // Setting properties
  16112. meshSubclass.material = source.material;
  16113. meshSubclass.checkCollisions = source.checkCollisions;
  16114. // Cleaning
  16115. if (disposeSource) {
  16116. for (index = 0; index < meshes.length; index++) {
  16117. if (meshes[index]) {
  16118. meshes[index].dispose();
  16119. }
  16120. }
  16121. }
  16122. return meshSubclass;
  16123. };
  16124. // Consts
  16125. Mesh._FRONTSIDE = 0;
  16126. Mesh._BACKSIDE = 1;
  16127. Mesh._DOUBLESIDE = 2;
  16128. Mesh._DEFAULTSIDE = 0;
  16129. Mesh._NO_CAP = 0;
  16130. Mesh._CAP_START = 1;
  16131. Mesh._CAP_END = 2;
  16132. Mesh._CAP_ALL = 3;
  16133. return Mesh;
  16134. })(BABYLON.AbstractMesh);
  16135. BABYLON.Mesh = Mesh;
  16136. })(BABYLON || (BABYLON = {}));
  16137. var BABYLON;
  16138. (function (BABYLON) {
  16139. var SubMesh = (function () {
  16140. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16141. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16142. this.materialIndex = materialIndex;
  16143. this.verticesStart = verticesStart;
  16144. this.verticesCount = verticesCount;
  16145. this.indexStart = indexStart;
  16146. this.indexCount = indexCount;
  16147. this._renderId = 0;
  16148. this._mesh = mesh;
  16149. this._renderingMesh = renderingMesh || mesh;
  16150. mesh.subMeshes.push(this);
  16151. this._trianglePlanes = [];
  16152. this._id = mesh.subMeshes.length - 1;
  16153. if (createBoundingBox) {
  16154. this.refreshBoundingInfo();
  16155. mesh.computeWorldMatrix(true);
  16156. }
  16157. }
  16158. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16159. get: function () {
  16160. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. SubMesh.prototype.getBoundingInfo = function () {
  16166. if (this.IsGlobal) {
  16167. return this._mesh.getBoundingInfo();
  16168. }
  16169. return this._boundingInfo;
  16170. };
  16171. SubMesh.prototype.getMesh = function () {
  16172. return this._mesh;
  16173. };
  16174. SubMesh.prototype.getRenderingMesh = function () {
  16175. return this._renderingMesh;
  16176. };
  16177. SubMesh.prototype.getMaterial = function () {
  16178. var rootMaterial = this._renderingMesh.material;
  16179. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16180. var multiMaterial = rootMaterial;
  16181. return multiMaterial.getSubMaterial(this.materialIndex);
  16182. }
  16183. if (!rootMaterial) {
  16184. return this._mesh.getScene().defaultMaterial;
  16185. }
  16186. return rootMaterial;
  16187. };
  16188. // Methods
  16189. SubMesh.prototype.refreshBoundingInfo = function () {
  16190. if (this.IsGlobal) {
  16191. return;
  16192. }
  16193. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16194. if (!data) {
  16195. this._boundingInfo = this._mesh._boundingInfo;
  16196. return;
  16197. }
  16198. var indices = this._renderingMesh.getIndices();
  16199. var extend;
  16200. //is this the only submesh?
  16201. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16202. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16203. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16204. }
  16205. else {
  16206. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16207. }
  16208. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16209. };
  16210. SubMesh.prototype._checkCollision = function (collider) {
  16211. return this.getBoundingInfo()._checkCollision(collider);
  16212. };
  16213. SubMesh.prototype.updateBoundingInfo = function (world) {
  16214. if (!this.getBoundingInfo()) {
  16215. this.refreshBoundingInfo();
  16216. }
  16217. this.getBoundingInfo()._update(world);
  16218. };
  16219. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16220. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16221. };
  16222. SubMesh.prototype.render = function (enableAlphaMode) {
  16223. this._renderingMesh.render(this, enableAlphaMode);
  16224. };
  16225. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16226. if (!this._linesIndexBuffer) {
  16227. var linesIndices = [];
  16228. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16229. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16230. }
  16231. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16232. this.linesIndexCount = linesIndices.length;
  16233. }
  16234. return this._linesIndexBuffer;
  16235. };
  16236. SubMesh.prototype.canIntersects = function (ray) {
  16237. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16238. };
  16239. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16240. var intersectInfo = null;
  16241. // Triangles test
  16242. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16243. var p0 = positions[indices[index]];
  16244. var p1 = positions[indices[index + 1]];
  16245. var p2 = positions[indices[index + 2]];
  16246. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16247. if (currentIntersectInfo) {
  16248. if (currentIntersectInfo.distance < 0) {
  16249. continue;
  16250. }
  16251. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16252. intersectInfo = currentIntersectInfo;
  16253. intersectInfo.faceId = index / 3;
  16254. if (fastCheck) {
  16255. break;
  16256. }
  16257. }
  16258. }
  16259. }
  16260. return intersectInfo;
  16261. };
  16262. // Clone
  16263. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16264. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16265. if (!this.IsGlobal) {
  16266. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16267. }
  16268. return result;
  16269. };
  16270. // Dispose
  16271. SubMesh.prototype.dispose = function () {
  16272. if (this._linesIndexBuffer) {
  16273. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16274. this._linesIndexBuffer = null;
  16275. }
  16276. // Remove from mesh
  16277. var index = this._mesh.subMeshes.indexOf(this);
  16278. this._mesh.subMeshes.splice(index, 1);
  16279. };
  16280. // Statics
  16281. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16282. var minVertexIndex = Number.MAX_VALUE;
  16283. var maxVertexIndex = -Number.MAX_VALUE;
  16284. renderingMesh = renderingMesh || mesh;
  16285. var indices = renderingMesh.getIndices();
  16286. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16287. var vertexIndex = indices[index];
  16288. if (vertexIndex < minVertexIndex)
  16289. minVertexIndex = vertexIndex;
  16290. if (vertexIndex > maxVertexIndex)
  16291. maxVertexIndex = vertexIndex;
  16292. }
  16293. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16294. };
  16295. return SubMesh;
  16296. })();
  16297. BABYLON.SubMesh = SubMesh;
  16298. })(BABYLON || (BABYLON = {}));
  16299. var BABYLON;
  16300. (function (BABYLON) {
  16301. var MeshBuilder = (function () {
  16302. function MeshBuilder() {
  16303. }
  16304. MeshBuilder.CreateBox = function (name, options, scene) {
  16305. var box = new BABYLON.Mesh(name, scene);
  16306. var vertexData = BABYLON.VertexData.CreateBox(options);
  16307. vertexData.applyToMesh(box, options.updatable);
  16308. return box;
  16309. };
  16310. MeshBuilder.CreateSphere = function (name, options, scene) {
  16311. var sphere = new BABYLON.Mesh(name, scene);
  16312. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16313. vertexData.applyToMesh(sphere, options.updatable);
  16314. return sphere;
  16315. };
  16316. MeshBuilder.CreateDisc = function (name, options, scene) {
  16317. var disc = new BABYLON.Mesh(name, scene);
  16318. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16319. vertexData.applyToMesh(disc, options.updatable);
  16320. return disc;
  16321. };
  16322. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16323. var sphere = new BABYLON.Mesh(name, scene);
  16324. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16325. vertexData.applyToMesh(sphere, options.updatable);
  16326. return sphere;
  16327. };
  16328. ;
  16329. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16330. var pathArray = options.pathArray;
  16331. var closeArray = options.closeArray;
  16332. var closePath = options.closePath;
  16333. var offset = options.offset;
  16334. var sideOrientation = options.sideOrientation;
  16335. var instance = options.instance;
  16336. var updatable = options.updatable;
  16337. if (instance) {
  16338. // positionFunction : ribbon case
  16339. // only pathArray and sideOrientation parameters are taken into account for positions update
  16340. var positionFunction = function (positions) {
  16341. var minlg = pathArray[0].length;
  16342. var i = 0;
  16343. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16344. for (var si = 1; si <= ns; si++) {
  16345. for (var p = 0; p < pathArray.length; p++) {
  16346. var path = pathArray[p];
  16347. var l = path.length;
  16348. minlg = (minlg < l) ? minlg : l;
  16349. var j = 0;
  16350. while (j < minlg) {
  16351. positions[i] = path[j].x;
  16352. positions[i + 1] = path[j].y;
  16353. positions[i + 2] = path[j].z;
  16354. j++;
  16355. i += 3;
  16356. }
  16357. if (instance._closePath) {
  16358. positions[i] = path[0].x;
  16359. positions[i + 1] = path[0].y;
  16360. positions[i + 2] = path[0].z;
  16361. i += 3;
  16362. }
  16363. }
  16364. }
  16365. };
  16366. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16367. positionFunction(positions);
  16368. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16369. if (!(instance.areNormalsFrozen)) {
  16370. var indices = instance.getIndices();
  16371. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16372. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16373. if (instance._closePath) {
  16374. var indexFirst = 0;
  16375. var indexLast = 0;
  16376. for (var p = 0; p < pathArray.length; p++) {
  16377. indexFirst = instance._idx[p] * 3;
  16378. if (p + 1 < pathArray.length) {
  16379. indexLast = (instance._idx[p + 1] - 1) * 3;
  16380. }
  16381. else {
  16382. indexLast = normals.length - 3;
  16383. }
  16384. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16385. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16386. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16387. normals[indexLast] = normals[indexFirst];
  16388. normals[indexLast + 1] = normals[indexFirst + 1];
  16389. normals[indexLast + 2] = normals[indexFirst + 2];
  16390. }
  16391. }
  16392. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16393. }
  16394. return instance;
  16395. }
  16396. else {
  16397. var ribbon = new BABYLON.Mesh(name, scene);
  16398. ribbon.sideOrientation = sideOrientation;
  16399. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16400. if (closePath) {
  16401. ribbon._idx = vertexData._idx;
  16402. }
  16403. ribbon._closePath = closePath;
  16404. ribbon._closeArray = closeArray;
  16405. vertexData.applyToMesh(ribbon, updatable);
  16406. return ribbon;
  16407. }
  16408. };
  16409. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16410. var cylinder = new BABYLON.Mesh(name, scene);
  16411. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16412. vertexData.applyToMesh(cylinder, options.updatable);
  16413. return cylinder;
  16414. };
  16415. MeshBuilder.CreateTorus = function (name, options, scene) {
  16416. var torus = new BABYLON.Mesh(name, scene);
  16417. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16418. vertexData.applyToMesh(torus, options.updatable);
  16419. return torus;
  16420. };
  16421. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16422. var torusKnot = new BABYLON.Mesh(name, scene);
  16423. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16424. vertexData.applyToMesh(torusKnot, options.updatable);
  16425. return torusKnot;
  16426. };
  16427. MeshBuilder.CreateLines = function (name, options, scene) {
  16428. var instance = options.instance;
  16429. var points = options.points;
  16430. if (instance) {
  16431. var positionFunction = function (positions) {
  16432. var i = 0;
  16433. for (var p = 0; p < points.length; p++) {
  16434. positions[i] = points[p].x;
  16435. positions[i + 1] = points[p].y;
  16436. positions[i + 2] = points[p].z;
  16437. i += 3;
  16438. }
  16439. };
  16440. instance.updateMeshPositions(positionFunction, false);
  16441. return instance;
  16442. }
  16443. // lines creation
  16444. var lines = new BABYLON.LinesMesh(name, scene);
  16445. var vertexData = BABYLON.VertexData.CreateLines(options);
  16446. vertexData.applyToMesh(lines, options.updatable);
  16447. return lines;
  16448. };
  16449. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16450. var points = options.points;
  16451. var instance = options.instance;
  16452. var gapSize = options.gapSize;
  16453. var dashNb = options.dashNb;
  16454. var dashSize = options.dashSize;
  16455. if (instance) {
  16456. var positionFunction = function (positions) {
  16457. var curvect = BABYLON.Vector3.Zero();
  16458. var nbSeg = positions.length / 6;
  16459. var lg = 0;
  16460. var nb = 0;
  16461. var shft = 0;
  16462. var dashshft = 0;
  16463. var curshft = 0;
  16464. var p = 0;
  16465. var i = 0;
  16466. var j = 0;
  16467. for (i = 0; i < points.length - 1; i++) {
  16468. points[i + 1].subtractToRef(points[i], curvect);
  16469. lg += curvect.length();
  16470. }
  16471. shft = lg / nbSeg;
  16472. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16473. for (i = 0; i < points.length - 1; i++) {
  16474. points[i + 1].subtractToRef(points[i], curvect);
  16475. nb = Math.floor(curvect.length() / shft);
  16476. curvect.normalize();
  16477. j = 0;
  16478. while (j < nb && p < positions.length) {
  16479. curshft = shft * j;
  16480. positions[p] = points[i].x + curshft * curvect.x;
  16481. positions[p + 1] = points[i].y + curshft * curvect.y;
  16482. positions[p + 2] = points[i].z + curshft * curvect.z;
  16483. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16484. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16485. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16486. p += 6;
  16487. j++;
  16488. }
  16489. }
  16490. while (p < positions.length) {
  16491. positions[p] = points[i].x;
  16492. positions[p + 1] = points[i].y;
  16493. positions[p + 2] = points[i].z;
  16494. p += 3;
  16495. }
  16496. };
  16497. instance.updateMeshPositions(positionFunction, false);
  16498. return instance;
  16499. }
  16500. // dashed lines creation
  16501. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16502. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16503. vertexData.applyToMesh(dashedLines, options.updatable);
  16504. dashedLines.dashSize = dashSize;
  16505. dashedLines.gapSize = gapSize;
  16506. return dashedLines;
  16507. };
  16508. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16509. var path = options.path;
  16510. var shape = options.shape;
  16511. var scale = options.scale || 1;
  16512. var rotation = options.rotation || 0;
  16513. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16514. var updatable = options.updatable;
  16515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16516. var instance = options.instance;
  16517. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16518. };
  16519. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16520. var path = options.path;
  16521. var shape = options.shape;
  16522. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16523. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16524. var ribbonCloseArray = options.ribbonCloseArray || false;
  16525. var ribbonClosePath = options.ribbonClosePath || false;
  16526. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16527. var updatable = options.updatable;
  16528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16529. var instance = options.instance;
  16530. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16531. };
  16532. MeshBuilder.CreateLathe = function (name, options, scene) {
  16533. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16534. var closed = (options.closed === undefined) ? true : options.closed;
  16535. var shape = options.shape;
  16536. var radius = options.radius || 1;
  16537. var tessellation = options.tessellation || 64;
  16538. var updatable = options.updatable;
  16539. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16540. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16541. var pi2 = Math.PI * 2;
  16542. var paths = new Array();
  16543. var i = 0;
  16544. var p = 0;
  16545. var step = pi2 / tessellation * arc;
  16546. var rotated;
  16547. var path = new Array();
  16548. ;
  16549. for (i = 0; i <= tessellation; i++) {
  16550. var path = [];
  16551. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16552. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16553. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16554. }
  16555. for (p = 0; p < shape.length; p++) {
  16556. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16557. path.push(rotated);
  16558. }
  16559. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16560. 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));
  16561. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16562. }
  16563. paths.push(path);
  16564. }
  16565. // lathe ribbon
  16566. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16567. return lathe;
  16568. };
  16569. MeshBuilder.CreatePlane = function (name, options, scene) {
  16570. var plane = new BABYLON.Mesh(name, scene);
  16571. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16572. vertexData.applyToMesh(plane, options.updatable);
  16573. if (options.sourcePlane) {
  16574. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16575. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16576. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16577. plane.rotate(vectorProduct, product);
  16578. }
  16579. return plane;
  16580. };
  16581. MeshBuilder.CreateGround = function (name, options, scene) {
  16582. var ground = new BABYLON.GroundMesh(name, scene);
  16583. ground._setReady(false);
  16584. ground._subdivisions = options.subdivisions || 1;
  16585. ground._width = options.width || 1;
  16586. ground._height = options.height || 1;
  16587. ground._maxX = ground._width / 2;
  16588. ground._maxZ = ground._height / 2;
  16589. ground._minX = -ground._maxX;
  16590. ground._minZ = -ground._maxZ;
  16591. var vertexData = BABYLON.VertexData.CreateGround(options);
  16592. vertexData.applyToMesh(ground, options.updatable);
  16593. ground._setReady(true);
  16594. return ground;
  16595. };
  16596. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16597. var tiledGround = new BABYLON.Mesh(name, scene);
  16598. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16599. vertexData.applyToMesh(tiledGround, options.updatable);
  16600. return tiledGround;
  16601. };
  16602. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16603. var width = options.width || 10;
  16604. var height = options.height || 10;
  16605. var subdivisions = options.subdivisions || 1;
  16606. var minHeight = options.minHeight;
  16607. var maxHeight = options.maxHeight || 10;
  16608. var updatable = options.updatable;
  16609. var onReady = options.onReady;
  16610. var ground = new BABYLON.GroundMesh(name, scene);
  16611. ground._subdivisions = subdivisions;
  16612. ground._width = width;
  16613. ground._height = height;
  16614. ground._maxX = ground._width / 2;
  16615. ground._maxZ = ground._height / 2;
  16616. ground._minX = -ground._maxX;
  16617. ground._minZ = -ground._maxZ;
  16618. ground._setReady(false);
  16619. var onload = function (img) {
  16620. // Getting height map data
  16621. var canvas = document.createElement("canvas");
  16622. var context = canvas.getContext("2d");
  16623. var bufferWidth = img.width;
  16624. var bufferHeight = img.height;
  16625. canvas.width = bufferWidth;
  16626. canvas.height = bufferHeight;
  16627. context.drawImage(img, 0, 0);
  16628. // Create VertexData from map data
  16629. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16630. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16631. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16632. width: width, height: height,
  16633. subdivisions: subdivisions,
  16634. minHeight: minHeight, maxHeight: maxHeight,
  16635. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16636. });
  16637. vertexData.applyToMesh(ground, updatable);
  16638. ground._setReady(true);
  16639. //execute ready callback, if set
  16640. if (onReady) {
  16641. onReady(ground);
  16642. }
  16643. };
  16644. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16645. return ground;
  16646. };
  16647. MeshBuilder.CreateTube = function (name, options, scene) {
  16648. var path = options.path;
  16649. var radius = options.radius || 1;
  16650. var tessellation = options.tessellation || 64;
  16651. var radiusFunction = options.radiusFunction;
  16652. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16653. var updatable = options.updatable;
  16654. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16655. var instance = options.instance;
  16656. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16657. // tube geometry
  16658. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16659. var tangents = path3D.getTangents();
  16660. var normals = path3D.getNormals();
  16661. var distances = path3D.getDistances();
  16662. var pi2 = Math.PI * 2;
  16663. var step = pi2 / tessellation * arc;
  16664. var returnRadius = function () { return radius; };
  16665. var radiusFunctionFinal = radiusFunction || returnRadius;
  16666. var circlePath;
  16667. var rad;
  16668. var normal;
  16669. var rotated;
  16670. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16671. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16672. for (var i = 0; i < path.length; i++) {
  16673. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16674. circlePath = Array(); // current circle array
  16675. normal = normals[i]; // current normal
  16676. for (var t = 0; t < tessellation; t++) {
  16677. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16678. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16679. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16680. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16681. circlePath[t] = rotated;
  16682. }
  16683. circlePaths[index] = circlePath;
  16684. index++;
  16685. }
  16686. // cap
  16687. var capPath = function (nbPoints, pathIndex) {
  16688. var pointCap = Array();
  16689. for (var i = 0; i < nbPoints; i++) {
  16690. pointCap.push(path[pathIndex]);
  16691. }
  16692. return pointCap;
  16693. };
  16694. switch (cap) {
  16695. case BABYLON.Mesh.NO_CAP:
  16696. break;
  16697. case BABYLON.Mesh.CAP_START:
  16698. circlePaths[0] = capPath(tessellation, 0);
  16699. circlePaths[1] = circlePaths[2].slice(0);
  16700. break;
  16701. case BABYLON.Mesh.CAP_END:
  16702. circlePaths[index] = circlePaths[index - 1].slice(0);
  16703. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16704. break;
  16705. case BABYLON.Mesh.CAP_ALL:
  16706. circlePaths[0] = capPath(tessellation, 0);
  16707. circlePaths[1] = circlePaths[2].slice(0);
  16708. circlePaths[index] = circlePaths[index - 1].slice(0);
  16709. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16710. break;
  16711. default:
  16712. break;
  16713. }
  16714. return circlePaths;
  16715. };
  16716. var path3D;
  16717. var pathArray;
  16718. if (instance) {
  16719. var arc = options.arc || instance.arc;
  16720. path3D = (instance.path3D).update(path);
  16721. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16722. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16723. instance.path3D = path3D;
  16724. instance.pathArray = pathArray;
  16725. instance.arc = arc;
  16726. return instance;
  16727. }
  16728. // tube creation
  16729. path3D = new BABYLON.Path3D(path);
  16730. var newPathArray = new Array();
  16731. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16732. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16733. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16734. tube.pathArray = pathArray;
  16735. tube.path3D = path3D;
  16736. tube.tessellation = tessellation;
  16737. tube.cap = cap;
  16738. tube.arc = options.arc;
  16739. return tube;
  16740. };
  16741. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16742. var polyhedron = new BABYLON.Mesh(name, scene);
  16743. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16744. vertexData.applyToMesh(polyhedron, options.updatable);
  16745. return polyhedron;
  16746. };
  16747. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16748. var indices = sourceMesh.getIndices();
  16749. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16750. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16751. var position = options.position || BABYLON.Vector3.Zero();
  16752. var normal = options.normal || BABYLON.Vector3.Up();
  16753. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16754. var angle = options.angle || 0;
  16755. // Getting correct rotation
  16756. if (!normal) {
  16757. var target = new BABYLON.Vector3(0, 0, 1);
  16758. var camera = sourceMesh.getScene().activeCamera;
  16759. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16760. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16761. }
  16762. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16763. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16764. var pitch = Math.atan2(normal.y, len);
  16765. // Matrix
  16766. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16767. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16768. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16769. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16770. var vertexData = new BABYLON.VertexData();
  16771. vertexData.indices = [];
  16772. vertexData.positions = [];
  16773. vertexData.normals = [];
  16774. vertexData.uvs = [];
  16775. var currentVertexDataIndex = 0;
  16776. var extractDecalVector3 = function (indexId) {
  16777. var vertexId = indices[indexId];
  16778. var result = new BABYLON.PositionNormalVertex();
  16779. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16780. // Send vector to decal local world
  16781. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16782. // Get normal
  16783. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16784. return result;
  16785. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16786. var clip = function (vertices, axis) {
  16787. if (vertices.length === 0) {
  16788. return vertices;
  16789. }
  16790. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16791. var clipVertices = function (v0, v1) {
  16792. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16793. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16794. };
  16795. var result = new Array();
  16796. for (var index = 0; index < vertices.length; index += 3) {
  16797. var v1Out;
  16798. var v2Out;
  16799. var v3Out;
  16800. var total = 0;
  16801. var nV1, nV2, nV3, nV4;
  16802. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16803. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16804. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16805. v1Out = d1 > 0;
  16806. v2Out = d2 > 0;
  16807. v3Out = d3 > 0;
  16808. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16809. switch (total) {
  16810. case 0:
  16811. result.push(vertices[index]);
  16812. result.push(vertices[index + 1]);
  16813. result.push(vertices[index + 2]);
  16814. break;
  16815. case 1:
  16816. if (v1Out) {
  16817. nV1 = vertices[index + 1];
  16818. nV2 = vertices[index + 2];
  16819. nV3 = clipVertices(vertices[index], nV1);
  16820. nV4 = clipVertices(vertices[index], nV2);
  16821. }
  16822. if (v2Out) {
  16823. nV1 = vertices[index];
  16824. nV2 = vertices[index + 2];
  16825. nV3 = clipVertices(vertices[index + 1], nV1);
  16826. nV4 = clipVertices(vertices[index + 1], nV2);
  16827. result.push(nV3);
  16828. result.push(nV2.clone());
  16829. result.push(nV1.clone());
  16830. result.push(nV2.clone());
  16831. result.push(nV3.clone());
  16832. result.push(nV4);
  16833. break;
  16834. }
  16835. if (v3Out) {
  16836. nV1 = vertices[index];
  16837. nV2 = vertices[index + 1];
  16838. nV3 = clipVertices(vertices[index + 2], nV1);
  16839. nV4 = clipVertices(vertices[index + 2], nV2);
  16840. }
  16841. result.push(nV1.clone());
  16842. result.push(nV2.clone());
  16843. result.push(nV3);
  16844. result.push(nV4);
  16845. result.push(nV3.clone());
  16846. result.push(nV2.clone());
  16847. break;
  16848. case 2:
  16849. if (!v1Out) {
  16850. nV1 = vertices[index].clone();
  16851. nV2 = clipVertices(nV1, vertices[index + 1]);
  16852. nV3 = clipVertices(nV1, vertices[index + 2]);
  16853. result.push(nV1);
  16854. result.push(nV2);
  16855. result.push(nV3);
  16856. }
  16857. if (!v2Out) {
  16858. nV1 = vertices[index + 1].clone();
  16859. nV2 = clipVertices(nV1, vertices[index + 2]);
  16860. nV3 = clipVertices(nV1, vertices[index]);
  16861. result.push(nV1);
  16862. result.push(nV2);
  16863. result.push(nV3);
  16864. }
  16865. if (!v3Out) {
  16866. nV1 = vertices[index + 2].clone();
  16867. nV2 = clipVertices(nV1, vertices[index]);
  16868. nV3 = clipVertices(nV1, vertices[index + 1]);
  16869. result.push(nV1);
  16870. result.push(nV2);
  16871. result.push(nV3);
  16872. }
  16873. break;
  16874. case 3:
  16875. break;
  16876. }
  16877. }
  16878. return result;
  16879. };
  16880. for (var index = 0; index < indices.length; index += 3) {
  16881. var faceVertices = new Array();
  16882. faceVertices.push(extractDecalVector3(index));
  16883. faceVertices.push(extractDecalVector3(index + 1));
  16884. faceVertices.push(extractDecalVector3(index + 2));
  16885. // Clip
  16886. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16887. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16888. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16889. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16890. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16891. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16892. if (faceVertices.length === 0) {
  16893. continue;
  16894. }
  16895. // Add UVs and get back to world
  16896. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16897. var vertex = faceVertices[vIndex];
  16898. //TODO check for Int32Array
  16899. vertexData.indices.push(currentVertexDataIndex);
  16900. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16901. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16902. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16903. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16904. currentVertexDataIndex++;
  16905. }
  16906. }
  16907. // Return mesh
  16908. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16909. vertexData.applyToMesh(decal);
  16910. decal.position = position.clone();
  16911. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16912. return decal;
  16913. };
  16914. // Privates
  16915. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16916. // extrusion geometry
  16917. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16918. var tangents = path3D.getTangents();
  16919. var normals = path3D.getNormals();
  16920. var binormals = path3D.getBinormals();
  16921. var distances = path3D.getDistances();
  16922. var angle = 0;
  16923. var returnScale = function () { return scale; };
  16924. var returnRotation = function () { return rotation; };
  16925. var rotate = custom ? rotateFunction : returnRotation;
  16926. var scl = custom ? scaleFunction : returnScale;
  16927. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16928. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16929. for (var i = 0; i < curve.length; i++) {
  16930. var shapePath = new Array();
  16931. var angleStep = rotate(i, distances[i]);
  16932. var scaleRatio = scl(i, distances[i]);
  16933. for (var p = 0; p < shape.length; p++) {
  16934. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16935. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16936. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  16937. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  16938. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  16939. shapePath[p] = rotated;
  16940. }
  16941. shapePaths[index] = shapePath;
  16942. angle += angleStep;
  16943. index++;
  16944. }
  16945. // cap
  16946. var capPath = function (shapePath) {
  16947. var pointCap = Array();
  16948. var barycenter = BABYLON.Vector3.Zero();
  16949. var i;
  16950. for (i = 0; i < shapePath.length; i++) {
  16951. barycenter.addInPlace(shapePath[i]);
  16952. }
  16953. barycenter.scaleInPlace(1 / shapePath.length);
  16954. for (i = 0; i < shapePath.length; i++) {
  16955. pointCap.push(barycenter);
  16956. }
  16957. return pointCap;
  16958. };
  16959. switch (cap) {
  16960. case BABYLON.Mesh.NO_CAP:
  16961. break;
  16962. case BABYLON.Mesh.CAP_START:
  16963. shapePaths[0] = capPath(shapePaths[2]);
  16964. shapePaths[1] = shapePaths[2].slice(0);
  16965. break;
  16966. case BABYLON.Mesh.CAP_END:
  16967. shapePaths[index] = shapePaths[index - 1];
  16968. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16969. break;
  16970. case BABYLON.Mesh.CAP_ALL:
  16971. shapePaths[0] = capPath(shapePaths[2]);
  16972. shapePaths[1] = shapePaths[2].slice(0);
  16973. shapePaths[index] = shapePaths[index - 1];
  16974. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16975. break;
  16976. default:
  16977. break;
  16978. }
  16979. return shapePaths;
  16980. };
  16981. var path3D;
  16982. var pathArray;
  16983. if (instance) {
  16984. path3D = (instance.path3D).update(curve);
  16985. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16986. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16987. return instance;
  16988. }
  16989. // extruded shape creation
  16990. path3D = new BABYLON.Path3D(curve);
  16991. var newShapePaths = new Array();
  16992. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16993. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16994. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16995. extrudedGeneric.pathArray = pathArray;
  16996. extrudedGeneric.path3D = path3D;
  16997. extrudedGeneric.cap = cap;
  16998. return extrudedGeneric;
  16999. };
  17000. return MeshBuilder;
  17001. })();
  17002. BABYLON.MeshBuilder = MeshBuilder;
  17003. })(BABYLON || (BABYLON = {}));
  17004. var BABYLON;
  17005. (function (BABYLON) {
  17006. var BaseTexture = (function () {
  17007. function BaseTexture(scene) {
  17008. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17009. this.hasAlpha = false;
  17010. this.getAlphaFromRGB = false;
  17011. this.level = 1;
  17012. this.isCube = false;
  17013. this.isRenderTarget = false;
  17014. this.animations = new Array();
  17015. this.coordinatesIndex = 0;
  17016. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17017. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17018. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17019. this.anisotropicFilteringLevel = 4;
  17020. this._scene = scene;
  17021. this._scene.textures.push(this);
  17022. }
  17023. BaseTexture.prototype.getScene = function () {
  17024. return this._scene;
  17025. };
  17026. BaseTexture.prototype.getTextureMatrix = function () {
  17027. return null;
  17028. };
  17029. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17030. return null;
  17031. };
  17032. BaseTexture.prototype.getInternalTexture = function () {
  17033. return this._texture;
  17034. };
  17035. BaseTexture.prototype.isReady = function () {
  17036. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17037. return true;
  17038. }
  17039. if (this._texture) {
  17040. return this._texture.isReady;
  17041. }
  17042. return false;
  17043. };
  17044. BaseTexture.prototype.getSize = function () {
  17045. if (this._texture._width) {
  17046. return { width: this._texture._width, height: this._texture._height };
  17047. }
  17048. if (this._texture._size) {
  17049. return { width: this._texture._size, height: this._texture._size };
  17050. }
  17051. return { width: 0, height: 0 };
  17052. };
  17053. BaseTexture.prototype.getBaseSize = function () {
  17054. if (!this.isReady())
  17055. return { width: 0, height: 0 };
  17056. if (this._texture._size) {
  17057. return { width: this._texture._size, height: this._texture._size };
  17058. }
  17059. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17060. };
  17061. BaseTexture.prototype.scale = function (ratio) {
  17062. };
  17063. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17064. get: function () {
  17065. return false;
  17066. },
  17067. enumerable: true,
  17068. configurable: true
  17069. });
  17070. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17071. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17072. for (var index = 0; index < texturesCache.length; index++) {
  17073. var texturesCacheEntry = texturesCache[index];
  17074. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17075. texturesCache.splice(index, 1);
  17076. return;
  17077. }
  17078. }
  17079. };
  17080. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17081. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17082. for (var index = 0; index < texturesCache.length; index++) {
  17083. var texturesCacheEntry = texturesCache[index];
  17084. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17085. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17086. texturesCacheEntry.references++;
  17087. return texturesCacheEntry;
  17088. }
  17089. }
  17090. }
  17091. return null;
  17092. };
  17093. BaseTexture.prototype.delayLoad = function () {
  17094. };
  17095. BaseTexture.prototype.clone = function () {
  17096. return null;
  17097. };
  17098. BaseTexture.prototype.releaseInternalTexture = function () {
  17099. if (this._texture) {
  17100. this._scene.getEngine().releaseInternalTexture(this._texture);
  17101. delete this._texture;
  17102. }
  17103. };
  17104. BaseTexture.prototype.dispose = function () {
  17105. // Animations
  17106. this.getScene().stopAnimation(this);
  17107. // Remove from scene
  17108. var index = this._scene.textures.indexOf(this);
  17109. if (index >= 0) {
  17110. this._scene.textures.splice(index, 1);
  17111. }
  17112. if (this._texture === undefined) {
  17113. return;
  17114. }
  17115. // Release
  17116. this.releaseInternalTexture();
  17117. // Callback
  17118. if (this.onDispose) {
  17119. this.onDispose();
  17120. }
  17121. };
  17122. BaseTexture.prototype.serialize = function () {
  17123. var serializationObject = {};
  17124. if (!this.name) {
  17125. return null;
  17126. }
  17127. serializationObject.name = this.name;
  17128. serializationObject.hasAlpha = this.hasAlpha;
  17129. serializationObject.level = this.level;
  17130. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17131. serializationObject.coordinatesMode = this.coordinatesMode;
  17132. serializationObject.wrapU = this.wrapU;
  17133. serializationObject.wrapV = this.wrapV;
  17134. // Animations
  17135. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17136. return serializationObject;
  17137. };
  17138. return BaseTexture;
  17139. })();
  17140. BABYLON.BaseTexture = BaseTexture;
  17141. })(BABYLON || (BABYLON = {}));
  17142. var BABYLON;
  17143. (function (BABYLON) {
  17144. var Texture = (function (_super) {
  17145. __extends(Texture, _super);
  17146. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17147. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17148. if (onLoad === void 0) { onLoad = null; }
  17149. if (onError === void 0) { onError = null; }
  17150. if (buffer === void 0) { buffer = null; }
  17151. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17152. _super.call(this, scene);
  17153. this.uOffset = 0;
  17154. this.vOffset = 0;
  17155. this.uScale = 1.0;
  17156. this.vScale = 1.0;
  17157. this.uAng = 0;
  17158. this.vAng = 0;
  17159. this.wAng = 0;
  17160. this.name = url;
  17161. this.url = url;
  17162. this._noMipmap = noMipmap;
  17163. this._invertY = invertY;
  17164. this._samplingMode = samplingMode;
  17165. this._buffer = buffer;
  17166. this._deleteBuffer = deleteBuffer;
  17167. if (!url) {
  17168. return;
  17169. }
  17170. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17171. if (!this._texture) {
  17172. if (!scene.useDelayedTextureLoading) {
  17173. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17174. if (deleteBuffer) {
  17175. delete this._buffer;
  17176. }
  17177. }
  17178. else {
  17179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17180. }
  17181. }
  17182. else {
  17183. BABYLON.Tools.SetImmediate(function () {
  17184. if (onLoad) {
  17185. onLoad();
  17186. }
  17187. });
  17188. }
  17189. }
  17190. Texture.prototype.delayLoad = function () {
  17191. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17192. return;
  17193. }
  17194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17195. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17196. if (!this._texture) {
  17197. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17198. if (this._deleteBuffer) {
  17199. delete this._buffer;
  17200. }
  17201. }
  17202. };
  17203. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17204. if (!this._texture) {
  17205. return;
  17206. }
  17207. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17208. };
  17209. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17210. x *= this.uScale;
  17211. y *= this.vScale;
  17212. x -= 0.5 * this.uScale;
  17213. y -= 0.5 * this.vScale;
  17214. z -= 0.5;
  17215. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17216. t.x += 0.5 * this.uScale + this.uOffset;
  17217. t.y += 0.5 * this.vScale + this.vOffset;
  17218. t.z += 0.5;
  17219. };
  17220. Texture.prototype.getTextureMatrix = function () {
  17221. if (this.uOffset === this._cachedUOffset &&
  17222. this.vOffset === this._cachedVOffset &&
  17223. this.uScale === this._cachedUScale &&
  17224. this.vScale === this._cachedVScale &&
  17225. this.uAng === this._cachedUAng &&
  17226. this.vAng === this._cachedVAng &&
  17227. this.wAng === this._cachedWAng) {
  17228. return this._cachedTextureMatrix;
  17229. }
  17230. this._cachedUOffset = this.uOffset;
  17231. this._cachedVOffset = this.vOffset;
  17232. this._cachedUScale = this.uScale;
  17233. this._cachedVScale = this.vScale;
  17234. this._cachedUAng = this.uAng;
  17235. this._cachedVAng = this.vAng;
  17236. this._cachedWAng = this.wAng;
  17237. if (!this._cachedTextureMatrix) {
  17238. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17239. this._rowGenerationMatrix = new BABYLON.Matrix();
  17240. this._t0 = BABYLON.Vector3.Zero();
  17241. this._t1 = BABYLON.Vector3.Zero();
  17242. this._t2 = BABYLON.Vector3.Zero();
  17243. }
  17244. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17245. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17246. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17247. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17248. this._t1.subtractInPlace(this._t0);
  17249. this._t2.subtractInPlace(this._t0);
  17250. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17251. this._cachedTextureMatrix.m[0] = this._t1.x;
  17252. this._cachedTextureMatrix.m[1] = this._t1.y;
  17253. this._cachedTextureMatrix.m[2] = this._t1.z;
  17254. this._cachedTextureMatrix.m[4] = this._t2.x;
  17255. this._cachedTextureMatrix.m[5] = this._t2.y;
  17256. this._cachedTextureMatrix.m[6] = this._t2.z;
  17257. this._cachedTextureMatrix.m[8] = this._t0.x;
  17258. this._cachedTextureMatrix.m[9] = this._t0.y;
  17259. this._cachedTextureMatrix.m[10] = this._t0.z;
  17260. return this._cachedTextureMatrix;
  17261. };
  17262. Texture.prototype.getReflectionTextureMatrix = function () {
  17263. if (this.uOffset === this._cachedUOffset &&
  17264. this.vOffset === this._cachedVOffset &&
  17265. this.uScale === this._cachedUScale &&
  17266. this.vScale === this._cachedVScale &&
  17267. this.coordinatesMode === this._cachedCoordinatesMode) {
  17268. return this._cachedTextureMatrix;
  17269. }
  17270. if (!this._cachedTextureMatrix) {
  17271. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17272. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17273. }
  17274. this._cachedCoordinatesMode = this.coordinatesMode;
  17275. switch (this.coordinatesMode) {
  17276. case Texture.PLANAR_MODE:
  17277. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17278. this._cachedTextureMatrix[0] = this.uScale;
  17279. this._cachedTextureMatrix[5] = this.vScale;
  17280. this._cachedTextureMatrix[12] = this.uOffset;
  17281. this._cachedTextureMatrix[13] = this.vOffset;
  17282. break;
  17283. case Texture.PROJECTION_MODE:
  17284. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17285. this._projectionModeMatrix.m[0] = 0.5;
  17286. this._projectionModeMatrix.m[5] = -0.5;
  17287. this._projectionModeMatrix.m[10] = 0.0;
  17288. this._projectionModeMatrix.m[12] = 0.5;
  17289. this._projectionModeMatrix.m[13] = 0.5;
  17290. this._projectionModeMatrix.m[14] = 1.0;
  17291. this._projectionModeMatrix.m[15] = 1.0;
  17292. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17293. break;
  17294. default:
  17295. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17296. break;
  17297. }
  17298. return this._cachedTextureMatrix;
  17299. };
  17300. Texture.prototype.clone = function () {
  17301. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17302. // Base texture
  17303. newTexture.hasAlpha = this.hasAlpha;
  17304. newTexture.level = this.level;
  17305. newTexture.wrapU = this.wrapU;
  17306. newTexture.wrapV = this.wrapV;
  17307. newTexture.coordinatesIndex = this.coordinatesIndex;
  17308. newTexture.coordinatesMode = this.coordinatesMode;
  17309. // Texture
  17310. newTexture.uOffset = this.uOffset;
  17311. newTexture.vOffset = this.vOffset;
  17312. newTexture.uScale = this.uScale;
  17313. newTexture.vScale = this.vScale;
  17314. newTexture.uAng = this.uAng;
  17315. newTexture.vAng = this.vAng;
  17316. newTexture.wAng = this.wAng;
  17317. return newTexture;
  17318. };
  17319. Texture.prototype.serialize = function () {
  17320. if (!this.name) {
  17321. return null;
  17322. }
  17323. var serializationObject = _super.prototype.serialize.call(this);
  17324. serializationObject.uOffset = this.uOffset;
  17325. serializationObject.vOffset = this.vOffset;
  17326. serializationObject.uScale = this.uScale;
  17327. serializationObject.vScale = this.vScale;
  17328. serializationObject.uAng = this.uAng;
  17329. serializationObject.vAng = this.vAng;
  17330. serializationObject.wAng = this.wAng;
  17331. return serializationObject;
  17332. };
  17333. // Statics
  17334. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17335. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17336. if (onLoad === void 0) { onLoad = null; }
  17337. if (onError === void 0) { onError = null; }
  17338. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17339. };
  17340. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17341. if (parsedTexture.isCube) {
  17342. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17343. }
  17344. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17345. return null;
  17346. }
  17347. var texture;
  17348. if (parsedTexture.mirrorPlane) {
  17349. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17350. texture._waitingRenderList = parsedTexture.renderList;
  17351. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17352. }
  17353. else if (parsedTexture.isRenderTarget) {
  17354. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17355. texture._waitingRenderList = parsedTexture.renderList;
  17356. }
  17357. else {
  17358. if (parsedTexture.base64String) {
  17359. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17360. }
  17361. else {
  17362. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17363. }
  17364. }
  17365. texture.name = parsedTexture.name;
  17366. texture.hasAlpha = parsedTexture.hasAlpha;
  17367. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17368. texture.level = parsedTexture.level;
  17369. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17370. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17371. texture.uOffset = parsedTexture.uOffset;
  17372. texture.vOffset = parsedTexture.vOffset;
  17373. texture.uScale = parsedTexture.uScale;
  17374. texture.vScale = parsedTexture.vScale;
  17375. texture.uAng = parsedTexture.uAng;
  17376. texture.vAng = parsedTexture.vAng;
  17377. texture.wAng = parsedTexture.wAng;
  17378. texture.wrapU = parsedTexture.wrapU;
  17379. texture.wrapV = parsedTexture.wrapV;
  17380. // Animations
  17381. if (parsedTexture.animations) {
  17382. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17383. var parsedAnimation = parsedTexture.animations[animationIndex];
  17384. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17385. }
  17386. }
  17387. return texture;
  17388. };
  17389. // Constants
  17390. Texture.NEAREST_SAMPLINGMODE = 1;
  17391. Texture.BILINEAR_SAMPLINGMODE = 2;
  17392. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17393. Texture.EXPLICIT_MODE = 0;
  17394. Texture.SPHERICAL_MODE = 1;
  17395. Texture.PLANAR_MODE = 2;
  17396. Texture.CUBIC_MODE = 3;
  17397. Texture.PROJECTION_MODE = 4;
  17398. Texture.SKYBOX_MODE = 5;
  17399. Texture.INVCUBIC_MODE = 6;
  17400. Texture.EQUIRECTANGULAR_MODE = 7;
  17401. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17402. Texture.CLAMP_ADDRESSMODE = 0;
  17403. Texture.WRAP_ADDRESSMODE = 1;
  17404. Texture.MIRROR_ADDRESSMODE = 2;
  17405. return Texture;
  17406. })(BABYLON.BaseTexture);
  17407. BABYLON.Texture = Texture;
  17408. })(BABYLON || (BABYLON = {}));
  17409. var BABYLON;
  17410. (function (BABYLON) {
  17411. var CubeTexture = (function (_super) {
  17412. __extends(CubeTexture, _super);
  17413. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17414. _super.call(this, scene);
  17415. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17416. this.name = rootUrl;
  17417. this.url = rootUrl;
  17418. this._noMipmap = noMipmap;
  17419. this.hasAlpha = false;
  17420. if (!rootUrl) {
  17421. return;
  17422. }
  17423. this._texture = this._getFromCache(rootUrl, noMipmap);
  17424. if (!extensions) {
  17425. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17426. }
  17427. this._extensions = extensions;
  17428. if (!this._texture) {
  17429. if (!scene.useDelayedTextureLoading) {
  17430. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17431. }
  17432. else {
  17433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17434. }
  17435. }
  17436. this.isCube = true;
  17437. this._textureMatrix = BABYLON.Matrix.Identity();
  17438. }
  17439. CubeTexture.prototype.clone = function () {
  17440. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17441. // Base texture
  17442. newTexture.level = this.level;
  17443. newTexture.wrapU = this.wrapU;
  17444. newTexture.wrapV = this.wrapV;
  17445. newTexture.coordinatesIndex = this.coordinatesIndex;
  17446. newTexture.coordinatesMode = this.coordinatesMode;
  17447. return newTexture;
  17448. };
  17449. // Methods
  17450. CubeTexture.prototype.delayLoad = function () {
  17451. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17452. return;
  17453. }
  17454. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17455. this._texture = this._getFromCache(this.url, this._noMipmap);
  17456. if (!this._texture) {
  17457. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17458. }
  17459. };
  17460. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17461. return this._textureMatrix;
  17462. };
  17463. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17464. var texture = null;
  17465. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17466. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17467. texture.name = parsedTexture.name;
  17468. texture.hasAlpha = parsedTexture.hasAlpha;
  17469. texture.level = parsedTexture.level;
  17470. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17471. }
  17472. return texture;
  17473. };
  17474. CubeTexture.prototype.serialize = function () {
  17475. if (!this.name) {
  17476. return null;
  17477. }
  17478. var serializationObject = {};
  17479. serializationObject.name = this.name;
  17480. serializationObject.hasAlpha = this.hasAlpha;
  17481. serializationObject.isCube = true;
  17482. serializationObject.level = this.level;
  17483. serializationObject.coordinatesMode = this.coordinatesMode;
  17484. return serializationObject;
  17485. };
  17486. return CubeTexture;
  17487. })(BABYLON.BaseTexture);
  17488. BABYLON.CubeTexture = CubeTexture;
  17489. })(BABYLON || (BABYLON = {}));
  17490. var BABYLON;
  17491. (function (BABYLON) {
  17492. var RenderTargetTexture = (function (_super) {
  17493. __extends(RenderTargetTexture, _super);
  17494. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17495. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17496. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17497. if (isCube === void 0) { isCube = false; }
  17498. _super.call(this, null, scene, !generateMipMaps);
  17499. this.isCube = isCube;
  17500. this.renderList = new Array();
  17501. this.renderParticles = true;
  17502. this.renderSprites = false;
  17503. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17504. this._currentRefreshId = -1;
  17505. this._refreshRate = 1;
  17506. this.name = name;
  17507. this.isRenderTarget = true;
  17508. this._size = size;
  17509. this._generateMipMaps = generateMipMaps;
  17510. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17511. if (isCube) {
  17512. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17513. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17514. this._textureMatrix = BABYLON.Matrix.Identity();
  17515. }
  17516. else {
  17517. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17518. }
  17519. // Rendering groups
  17520. this._renderingManager = new BABYLON.RenderingManager(scene);
  17521. }
  17522. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17523. get: function () {
  17524. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17525. },
  17526. enumerable: true,
  17527. configurable: true
  17528. });
  17529. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17530. get: function () {
  17531. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17532. },
  17533. enumerable: true,
  17534. configurable: true
  17535. });
  17536. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17537. get: function () {
  17538. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17539. },
  17540. enumerable: true,
  17541. configurable: true
  17542. });
  17543. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17544. this._currentRefreshId = -1;
  17545. };
  17546. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17547. get: function () {
  17548. return this._refreshRate;
  17549. },
  17550. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17551. set: function (value) {
  17552. this._refreshRate = value;
  17553. this.resetRefreshCounter();
  17554. },
  17555. enumerable: true,
  17556. configurable: true
  17557. });
  17558. RenderTargetTexture.prototype._shouldRender = function () {
  17559. if (this._currentRefreshId === -1) {
  17560. this._currentRefreshId = 1;
  17561. return true;
  17562. }
  17563. if (this.refreshRate === this._currentRefreshId) {
  17564. this._currentRefreshId = 1;
  17565. return true;
  17566. }
  17567. this._currentRefreshId++;
  17568. return false;
  17569. };
  17570. RenderTargetTexture.prototype.isReady = function () {
  17571. if (!this.getScene().renderTargetsEnabled) {
  17572. return false;
  17573. }
  17574. return _super.prototype.isReady.call(this);
  17575. };
  17576. RenderTargetTexture.prototype.getRenderSize = function () {
  17577. return this._size;
  17578. };
  17579. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17580. get: function () {
  17581. return true;
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. RenderTargetTexture.prototype.scale = function (ratio) {
  17587. var newSize = this._size * ratio;
  17588. this.resize(newSize, this._generateMipMaps);
  17589. };
  17590. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17591. if (this.isCube) {
  17592. return this._textureMatrix;
  17593. }
  17594. return _super.prototype.getReflectionTextureMatrix.call(this);
  17595. };
  17596. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17597. this.releaseInternalTexture();
  17598. if (this.isCube) {
  17599. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17600. }
  17601. else {
  17602. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17603. }
  17604. };
  17605. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17606. var scene = this.getScene();
  17607. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17608. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17609. }
  17610. if (this._waitingRenderList) {
  17611. this.renderList = [];
  17612. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17613. var id = this._waitingRenderList[index];
  17614. this.renderList.push(scene.getMeshByID(id));
  17615. }
  17616. delete this._waitingRenderList;
  17617. }
  17618. if (this.renderList && this.renderList.length === 0) {
  17619. return;
  17620. }
  17621. // Prepare renderingManager
  17622. this._renderingManager.reset();
  17623. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17624. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17625. var mesh = currentRenderList[meshIndex];
  17626. if (mesh) {
  17627. if (!mesh.isReady()) {
  17628. // Reset _currentRefreshId
  17629. this.resetRefreshCounter();
  17630. continue;
  17631. }
  17632. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17633. mesh._activate(scene.getRenderId());
  17634. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17635. var subMesh = mesh.subMeshes[subIndex];
  17636. scene._activeIndices += subMesh.indexCount;
  17637. this._renderingManager.dispatch(subMesh);
  17638. }
  17639. }
  17640. }
  17641. }
  17642. if (this.isCube) {
  17643. for (var face = 0; face < 6; face++) {
  17644. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17645. scene.incrementRenderId();
  17646. }
  17647. }
  17648. else {
  17649. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17650. }
  17651. if (this.onAfterUnbind) {
  17652. this.onAfterUnbind();
  17653. }
  17654. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17655. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17656. }
  17657. scene.resetCachedMaterial();
  17658. };
  17659. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17660. var scene = this.getScene();
  17661. var engine = scene.getEngine();
  17662. // Bind
  17663. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17664. if (this.isCube) {
  17665. engine.bindFramebuffer(this._texture, faceIndex);
  17666. }
  17667. else {
  17668. engine.bindFramebuffer(this._texture);
  17669. }
  17670. }
  17671. if (this.onBeforeRender) {
  17672. this.onBeforeRender(faceIndex);
  17673. }
  17674. // Clear
  17675. if (this.onClear) {
  17676. this.onClear(engine);
  17677. }
  17678. else {
  17679. engine.clear(scene.clearColor, true, true);
  17680. }
  17681. if (!this._doNotChangeAspectRatio) {
  17682. scene.updateTransformMatrix(true);
  17683. }
  17684. // Render
  17685. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17686. if (useCameraPostProcess) {
  17687. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17688. }
  17689. if (!this._doNotChangeAspectRatio) {
  17690. scene.updateTransformMatrix(true);
  17691. }
  17692. if (this.onAfterRender) {
  17693. this.onAfterRender(faceIndex);
  17694. }
  17695. // Dump ?
  17696. if (dumpForDebug) {
  17697. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17698. }
  17699. // Unbind
  17700. if (!this.isCube || faceIndex === 5) {
  17701. if (this.isCube) {
  17702. if (faceIndex === 5) {
  17703. engine.generateMipMapsForCubemap(this._texture);
  17704. }
  17705. }
  17706. engine.unBindFramebuffer(this._texture, this.isCube);
  17707. }
  17708. };
  17709. RenderTargetTexture.prototype.clone = function () {
  17710. var textureSize = this.getSize();
  17711. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17712. // Base texture
  17713. newTexture.hasAlpha = this.hasAlpha;
  17714. newTexture.level = this.level;
  17715. // RenderTarget Texture
  17716. newTexture.coordinatesMode = this.coordinatesMode;
  17717. newTexture.renderList = this.renderList.slice(0);
  17718. return newTexture;
  17719. };
  17720. RenderTargetTexture.prototype.serialize = function () {
  17721. if (!this.name) {
  17722. return null;
  17723. }
  17724. var serializationObject = _super.prototype.serialize.call(this);
  17725. serializationObject.renderTargetSize = this.getRenderSize();
  17726. serializationObject.renderList = [];
  17727. for (var index = 0; index < this.renderList.length; index++) {
  17728. serializationObject.renderList.push(this.renderList[index].id);
  17729. }
  17730. return serializationObject;
  17731. };
  17732. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17733. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17734. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17735. return RenderTargetTexture;
  17736. })(BABYLON.Texture);
  17737. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17738. })(BABYLON || (BABYLON = {}));
  17739. var BABYLON;
  17740. (function (BABYLON) {
  17741. var ProceduralTexture = (function (_super) {
  17742. __extends(ProceduralTexture, _super);
  17743. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17744. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17745. _super.call(this, null, scene, !generateMipMaps);
  17746. this.isEnabled = true;
  17747. this._currentRefreshId = -1;
  17748. this._refreshRate = 1;
  17749. this._vertexDeclaration = [2];
  17750. this._vertexStrideSize = 2 * 4;
  17751. this._uniforms = new Array();
  17752. this._samplers = new Array();
  17753. this._textures = new Array();
  17754. this._floats = new Array();
  17755. this._floatsArrays = {};
  17756. this._colors3 = new Array();
  17757. this._colors4 = new Array();
  17758. this._vectors2 = new Array();
  17759. this._vectors3 = new Array();
  17760. this._matrices = new Array();
  17761. this._fallbackTextureUsed = false;
  17762. scene._proceduralTextures.push(this);
  17763. this.name = name;
  17764. this.isRenderTarget = true;
  17765. this._size = size;
  17766. this._generateMipMaps = generateMipMaps;
  17767. this.setFragment(fragment);
  17768. this._fallbackTexture = fallbackTexture;
  17769. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17770. // VBO
  17771. var vertices = [];
  17772. vertices.push(1, 1);
  17773. vertices.push(-1, 1);
  17774. vertices.push(-1, -1);
  17775. vertices.push(1, -1);
  17776. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17777. // Indices
  17778. var indices = [];
  17779. indices.push(0);
  17780. indices.push(1);
  17781. indices.push(2);
  17782. indices.push(0);
  17783. indices.push(2);
  17784. indices.push(3);
  17785. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17786. }
  17787. ProceduralTexture.prototype.reset = function () {
  17788. if (this._effect === undefined) {
  17789. return;
  17790. }
  17791. var engine = this.getScene().getEngine();
  17792. engine._releaseEffect(this._effect);
  17793. };
  17794. ProceduralTexture.prototype.isReady = function () {
  17795. var _this = this;
  17796. var engine = this.getScene().getEngine();
  17797. var shaders;
  17798. if (!this._fragment) {
  17799. return false;
  17800. }
  17801. if (this._fallbackTextureUsed) {
  17802. return true;
  17803. }
  17804. if (this._fragment.fragmentElement !== undefined) {
  17805. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17806. }
  17807. else {
  17808. shaders = { vertex: "procedural", fragment: this._fragment };
  17809. }
  17810. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17811. _this.releaseInternalTexture();
  17812. if (_this._fallbackTexture) {
  17813. _this._texture = _this._fallbackTexture._texture;
  17814. _this._texture.references++;
  17815. }
  17816. _this._fallbackTextureUsed = true;
  17817. });
  17818. return this._effect.isReady();
  17819. };
  17820. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17821. this._currentRefreshId = -1;
  17822. };
  17823. ProceduralTexture.prototype.setFragment = function (fragment) {
  17824. this._fragment = fragment;
  17825. };
  17826. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17827. get: function () {
  17828. return this._refreshRate;
  17829. },
  17830. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17831. set: function (value) {
  17832. this._refreshRate = value;
  17833. this.resetRefreshCounter();
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. ProceduralTexture.prototype._shouldRender = function () {
  17839. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17840. return false;
  17841. }
  17842. if (this._fallbackTextureUsed) {
  17843. return false;
  17844. }
  17845. if (this._currentRefreshId === -1) {
  17846. this._currentRefreshId = 1;
  17847. return true;
  17848. }
  17849. if (this.refreshRate === this._currentRefreshId) {
  17850. this._currentRefreshId = 1;
  17851. return true;
  17852. }
  17853. this._currentRefreshId++;
  17854. return false;
  17855. };
  17856. ProceduralTexture.prototype.getRenderSize = function () {
  17857. return this._size;
  17858. };
  17859. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17860. if (this._fallbackTextureUsed) {
  17861. return;
  17862. }
  17863. this.releaseInternalTexture();
  17864. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17865. };
  17866. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17867. if (this._uniforms.indexOf(uniformName) === -1) {
  17868. this._uniforms.push(uniformName);
  17869. }
  17870. };
  17871. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17872. if (this._samplers.indexOf(name) === -1) {
  17873. this._samplers.push(name);
  17874. }
  17875. this._textures[name] = texture;
  17876. return this;
  17877. };
  17878. ProceduralTexture.prototype.setFloat = function (name, value) {
  17879. this._checkUniform(name);
  17880. this._floats[name] = value;
  17881. return this;
  17882. };
  17883. ProceduralTexture.prototype.setFloats = function (name, value) {
  17884. this._checkUniform(name);
  17885. this._floatsArrays[name] = value;
  17886. return this;
  17887. };
  17888. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17889. this._checkUniform(name);
  17890. this._colors3[name] = value;
  17891. return this;
  17892. };
  17893. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17894. this._checkUniform(name);
  17895. this._colors4[name] = value;
  17896. return this;
  17897. };
  17898. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17899. this._checkUniform(name);
  17900. this._vectors2[name] = value;
  17901. return this;
  17902. };
  17903. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17904. this._checkUniform(name);
  17905. this._vectors3[name] = value;
  17906. return this;
  17907. };
  17908. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17909. this._checkUniform(name);
  17910. this._matrices[name] = value;
  17911. return this;
  17912. };
  17913. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17914. var scene = this.getScene();
  17915. var engine = scene.getEngine();
  17916. engine.bindFramebuffer(this._texture);
  17917. // Clear
  17918. engine.clear(scene.clearColor, true, true);
  17919. // Render
  17920. engine.enableEffect(this._effect);
  17921. engine.setState(false);
  17922. // Texture
  17923. for (var name in this._textures) {
  17924. this._effect.setTexture(name, this._textures[name]);
  17925. }
  17926. // Float
  17927. for (name in this._floats) {
  17928. this._effect.setFloat(name, this._floats[name]);
  17929. }
  17930. // Floats
  17931. for (name in this._floatsArrays) {
  17932. this._effect.setArray(name, this._floatsArrays[name]);
  17933. }
  17934. // Color3
  17935. for (name in this._colors3) {
  17936. this._effect.setColor3(name, this._colors3[name]);
  17937. }
  17938. // Color4
  17939. for (name in this._colors4) {
  17940. var color = this._colors4[name];
  17941. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17942. }
  17943. // Vector2
  17944. for (name in this._vectors2) {
  17945. this._effect.setVector2(name, this._vectors2[name]);
  17946. }
  17947. // Vector3
  17948. for (name in this._vectors3) {
  17949. this._effect.setVector3(name, this._vectors3[name]);
  17950. }
  17951. // Matrix
  17952. for (name in this._matrices) {
  17953. this._effect.setMatrix(name, this._matrices[name]);
  17954. }
  17955. // VBOs
  17956. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17957. // Draw order
  17958. engine.draw(true, 0, 6);
  17959. // Unbind
  17960. engine.unBindFramebuffer(this._texture);
  17961. };
  17962. ProceduralTexture.prototype.clone = function () {
  17963. var textureSize = this.getSize();
  17964. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17965. // Base texture
  17966. newTexture.hasAlpha = this.hasAlpha;
  17967. newTexture.level = this.level;
  17968. // RenderTarget Texture
  17969. newTexture.coordinatesMode = this.coordinatesMode;
  17970. return newTexture;
  17971. };
  17972. ProceduralTexture.prototype.dispose = function () {
  17973. var index = this.getScene()._proceduralTextures.indexOf(this);
  17974. if (index >= 0) {
  17975. this.getScene()._proceduralTextures.splice(index, 1);
  17976. }
  17977. _super.prototype.dispose.call(this);
  17978. };
  17979. return ProceduralTexture;
  17980. })(BABYLON.Texture);
  17981. BABYLON.ProceduralTexture = ProceduralTexture;
  17982. })(BABYLON || (BABYLON = {}));
  17983. var BABYLON;
  17984. (function (BABYLON) {
  17985. var MirrorTexture = (function (_super) {
  17986. __extends(MirrorTexture, _super);
  17987. function MirrorTexture(name, size, scene, generateMipMaps) {
  17988. var _this = this;
  17989. _super.call(this, name, size, scene, generateMipMaps, true);
  17990. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17991. this._transformMatrix = BABYLON.Matrix.Zero();
  17992. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17993. this.onBeforeRender = function () {
  17994. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17995. _this._savedViewMatrix = scene.getViewMatrix();
  17996. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17997. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17998. scene.clipPlane = _this.mirrorPlane;
  17999. scene.getEngine().cullBackFaces = false;
  18000. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18001. };
  18002. this.onAfterRender = function () {
  18003. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18004. scene.getEngine().cullBackFaces = true;
  18005. scene._mirroredCameraPosition = null;
  18006. delete scene.clipPlane;
  18007. };
  18008. }
  18009. MirrorTexture.prototype.clone = function () {
  18010. var textureSize = this.getSize();
  18011. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18012. // Base texture
  18013. newTexture.hasAlpha = this.hasAlpha;
  18014. newTexture.level = this.level;
  18015. // Mirror Texture
  18016. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18017. newTexture.renderList = this.renderList.slice(0);
  18018. return newTexture;
  18019. };
  18020. MirrorTexture.prototype.serialize = function () {
  18021. if (!this.name) {
  18022. return null;
  18023. }
  18024. var serializationObject = _super.prototype.serialize.call(this);
  18025. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18026. return serializationObject;
  18027. };
  18028. return MirrorTexture;
  18029. })(BABYLON.RenderTargetTexture);
  18030. BABYLON.MirrorTexture = MirrorTexture;
  18031. })(BABYLON || (BABYLON = {}));
  18032. var BABYLON;
  18033. (function (BABYLON) {
  18034. var DynamicTexture = (function (_super) {
  18035. __extends(DynamicTexture, _super);
  18036. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18038. _super.call(this, null, scene, !generateMipMaps);
  18039. this.name = name;
  18040. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18041. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18042. this._generateMipMaps = generateMipMaps;
  18043. if (options.getContext) {
  18044. this._canvas = options;
  18045. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18046. }
  18047. else {
  18048. this._canvas = document.createElement("canvas");
  18049. if (options.width) {
  18050. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18051. }
  18052. else {
  18053. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18054. }
  18055. }
  18056. var textureSize = this.getSize();
  18057. this._canvas.width = textureSize.width;
  18058. this._canvas.height = textureSize.height;
  18059. this._context = this._canvas.getContext("2d");
  18060. }
  18061. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18062. get: function () {
  18063. return true;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. DynamicTexture.prototype.scale = function (ratio) {
  18069. var textureSize = this.getSize();
  18070. textureSize.width *= ratio;
  18071. textureSize.height *= ratio;
  18072. this._canvas.width = textureSize.width;
  18073. this._canvas.height = textureSize.height;
  18074. this.releaseInternalTexture();
  18075. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18076. };
  18077. DynamicTexture.prototype.getContext = function () {
  18078. return this._context;
  18079. };
  18080. DynamicTexture.prototype.clear = function () {
  18081. var size = this.getSize();
  18082. this._context.fillRect(0, 0, size.width, size.height);
  18083. };
  18084. DynamicTexture.prototype.update = function (invertY) {
  18085. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18086. };
  18087. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18088. if (update === void 0) { update = true; }
  18089. var size = this.getSize();
  18090. if (clearColor) {
  18091. this._context.fillStyle = clearColor;
  18092. this._context.fillRect(0, 0, size.width, size.height);
  18093. }
  18094. this._context.font = font;
  18095. if (x === null) {
  18096. var textSize = this._context.measureText(text);
  18097. x = (size.width - textSize.width) / 2;
  18098. }
  18099. this._context.fillStyle = color;
  18100. this._context.fillText(text, x, y);
  18101. if (update) {
  18102. this.update(invertY);
  18103. }
  18104. };
  18105. DynamicTexture.prototype.clone = function () {
  18106. var textureSize = this.getSize();
  18107. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18108. // Base texture
  18109. newTexture.hasAlpha = this.hasAlpha;
  18110. newTexture.level = this.level;
  18111. // Dynamic Texture
  18112. newTexture.wrapU = this.wrapU;
  18113. newTexture.wrapV = this.wrapV;
  18114. return newTexture;
  18115. };
  18116. return DynamicTexture;
  18117. })(BABYLON.Texture);
  18118. BABYLON.DynamicTexture = DynamicTexture;
  18119. })(BABYLON || (BABYLON = {}));
  18120. var BABYLON;
  18121. (function (BABYLON) {
  18122. var VideoTexture = (function (_super) {
  18123. __extends(VideoTexture, _super);
  18124. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18125. var _this = this;
  18126. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18127. if (invertY === void 0) { invertY = false; }
  18128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18129. _super.call(this, null, scene, !generateMipMaps, invertY);
  18130. this._autoLaunch = true;
  18131. this.name = name;
  18132. this.video = document.createElement("video");
  18133. this.video.autoplay = false;
  18134. this.video.loop = true;
  18135. this.video.addEventListener("canplaythrough", function () {
  18136. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18137. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18138. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18139. }
  18140. else {
  18141. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18142. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18143. generateMipMaps = false;
  18144. }
  18145. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18146. _this._texture.isReady = true;
  18147. });
  18148. urls.forEach(function (url) {
  18149. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18150. var source = document.createElement("source");
  18151. source.src = url;
  18152. _this.video.appendChild(source);
  18153. });
  18154. this._lastUpdate = BABYLON.Tools.Now;
  18155. }
  18156. VideoTexture.prototype.update = function () {
  18157. if (this._autoLaunch) {
  18158. this._autoLaunch = false;
  18159. this.video.play();
  18160. }
  18161. var now = BABYLON.Tools.Now;
  18162. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18163. return false;
  18164. }
  18165. this._lastUpdate = now;
  18166. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18167. return true;
  18168. };
  18169. return VideoTexture;
  18170. })(BABYLON.Texture);
  18171. BABYLON.VideoTexture = VideoTexture;
  18172. })(BABYLON || (BABYLON = {}));
  18173. var BABYLON;
  18174. (function (BABYLON) {
  18175. var CustomProceduralTexture = (function (_super) {
  18176. __extends(CustomProceduralTexture, _super);
  18177. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18178. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18179. this._animate = true;
  18180. this._time = 0;
  18181. this._texturePath = texturePath;
  18182. //Try to load json
  18183. this.loadJson(texturePath);
  18184. this.refreshRate = 1;
  18185. }
  18186. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18187. var _this = this;
  18188. var that = this;
  18189. function noConfigFile() {
  18190. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18191. try {
  18192. that.setFragment(that._texturePath);
  18193. }
  18194. catch (ex) {
  18195. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18196. }
  18197. }
  18198. var configFileUrl = jsonUrl + "/config.json";
  18199. var xhr = new XMLHttpRequest();
  18200. xhr.open("GET", configFileUrl, true);
  18201. xhr.addEventListener("load", function () {
  18202. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18203. try {
  18204. _this._config = JSON.parse(xhr.response);
  18205. _this.updateShaderUniforms();
  18206. _this.updateTextures();
  18207. _this.setFragment(_this._texturePath + "/custom");
  18208. _this._animate = _this._config.animate;
  18209. _this.refreshRate = _this._config.refreshrate;
  18210. }
  18211. catch (ex) {
  18212. noConfigFile();
  18213. }
  18214. }
  18215. else {
  18216. noConfigFile();
  18217. }
  18218. }, false);
  18219. xhr.addEventListener("error", function () {
  18220. noConfigFile();
  18221. }, false);
  18222. try {
  18223. xhr.send();
  18224. }
  18225. catch (ex) {
  18226. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18227. }
  18228. };
  18229. CustomProceduralTexture.prototype.isReady = function () {
  18230. if (!_super.prototype.isReady.call(this)) {
  18231. return false;
  18232. }
  18233. for (var name in this._textures) {
  18234. var texture = this._textures[name];
  18235. if (!texture.isReady()) {
  18236. return false;
  18237. }
  18238. }
  18239. return true;
  18240. };
  18241. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18242. if (this._animate) {
  18243. this._time += this.getScene().getAnimationRatio() * 0.03;
  18244. this.updateShaderUniforms();
  18245. }
  18246. _super.prototype.render.call(this, useCameraPostProcess);
  18247. };
  18248. CustomProceduralTexture.prototype.updateTextures = function () {
  18249. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18250. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18251. }
  18252. };
  18253. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18254. if (this._config) {
  18255. for (var j = 0; j < this._config.uniforms.length; j++) {
  18256. var uniform = this._config.uniforms[j];
  18257. switch (uniform.type) {
  18258. case "float":
  18259. this.setFloat(uniform.name, uniform.value);
  18260. break;
  18261. case "color3":
  18262. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18263. break;
  18264. case "color4":
  18265. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18266. break;
  18267. case "vector2":
  18268. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18269. break;
  18270. case "vector3":
  18271. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18272. break;
  18273. }
  18274. }
  18275. }
  18276. this.setFloat("time", this._time);
  18277. };
  18278. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18279. get: function () {
  18280. return this._animate;
  18281. },
  18282. set: function (value) {
  18283. this._animate = value;
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. return CustomProceduralTexture;
  18289. })(BABYLON.ProceduralTexture);
  18290. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18291. })(BABYLON || (BABYLON = {}));
  18292. var BABYLON;
  18293. (function (BABYLON) {
  18294. var EffectFallbacks = (function () {
  18295. function EffectFallbacks() {
  18296. this._defines = {};
  18297. this._currentRank = 32;
  18298. this._maxRank = -1;
  18299. }
  18300. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18301. if (!this._defines[rank]) {
  18302. if (rank < this._currentRank) {
  18303. this._currentRank = rank;
  18304. }
  18305. if (rank > this._maxRank) {
  18306. this._maxRank = rank;
  18307. }
  18308. this._defines[rank] = new Array();
  18309. }
  18310. this._defines[rank].push(define);
  18311. };
  18312. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18313. this._meshRank = rank;
  18314. this._mesh = mesh;
  18315. if (rank > this._maxRank) {
  18316. this._maxRank = rank;
  18317. }
  18318. };
  18319. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18320. get: function () {
  18321. return this._currentRank <= this._maxRank;
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18327. var currentFallbacks = this._defines[this._currentRank];
  18328. for (var index = 0; index < currentFallbacks.length; index++) {
  18329. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18330. }
  18331. if (this._mesh && this._currentRank === this._meshRank) {
  18332. this._mesh.computeBonesUsingShaders = false;
  18333. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18334. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18335. }
  18336. this._currentRank++;
  18337. return currentDefines;
  18338. };
  18339. return EffectFallbacks;
  18340. })();
  18341. BABYLON.EffectFallbacks = EffectFallbacks;
  18342. var Effect = (function () {
  18343. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18344. var _this = this;
  18345. this._isReady = false;
  18346. this._compilationError = "";
  18347. this._valueCache = [];
  18348. this._engine = engine;
  18349. this.name = baseName;
  18350. this.defines = defines;
  18351. this._uniformsNames = uniformsNames.concat(samplers);
  18352. this._samplers = samplers;
  18353. this._attributesNames = attributesNames;
  18354. this.onError = onError;
  18355. this.onCompiled = onCompiled;
  18356. var vertexSource;
  18357. var fragmentSource;
  18358. if (baseName.vertexElement) {
  18359. vertexSource = document.getElementById(baseName.vertexElement);
  18360. if (!vertexSource) {
  18361. vertexSource = baseName.vertexElement;
  18362. }
  18363. }
  18364. else {
  18365. vertexSource = baseName.vertex || baseName;
  18366. }
  18367. if (baseName.fragmentElement) {
  18368. fragmentSource = document.getElementById(baseName.fragmentElement);
  18369. if (!fragmentSource) {
  18370. fragmentSource = baseName.fragmentElement;
  18371. }
  18372. }
  18373. else {
  18374. fragmentSource = baseName.fragment || baseName;
  18375. }
  18376. this._loadVertexShader(vertexSource, function (vertexCode) {
  18377. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18378. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18379. });
  18380. });
  18381. }
  18382. // Properties
  18383. Effect.prototype.isReady = function () {
  18384. return this._isReady;
  18385. };
  18386. Effect.prototype.getProgram = function () {
  18387. return this._program;
  18388. };
  18389. Effect.prototype.getAttributesNames = function () {
  18390. return this._attributesNames;
  18391. };
  18392. Effect.prototype.getAttributeLocation = function (index) {
  18393. return this._attributes[index];
  18394. };
  18395. Effect.prototype.getAttributeLocationByName = function (name) {
  18396. var index = this._attributesNames.indexOf(name);
  18397. return this._attributes[index];
  18398. };
  18399. Effect.prototype.getAttributesCount = function () {
  18400. return this._attributes.length;
  18401. };
  18402. Effect.prototype.getUniformIndex = function (uniformName) {
  18403. return this._uniformsNames.indexOf(uniformName);
  18404. };
  18405. Effect.prototype.getUniform = function (uniformName) {
  18406. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18407. };
  18408. Effect.prototype.getSamplers = function () {
  18409. return this._samplers;
  18410. };
  18411. Effect.prototype.getCompilationError = function () {
  18412. return this._compilationError;
  18413. };
  18414. // Methods
  18415. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18416. // DOM element ?
  18417. if (vertex instanceof HTMLElement) {
  18418. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18419. callback(vertexCode);
  18420. return;
  18421. }
  18422. // Is in local store ?
  18423. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18424. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18425. return;
  18426. }
  18427. var vertexShaderUrl;
  18428. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18429. vertexShaderUrl = vertex;
  18430. }
  18431. else {
  18432. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18433. }
  18434. // Vertex shader
  18435. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18436. };
  18437. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18438. // DOM element ?
  18439. if (fragment instanceof HTMLElement) {
  18440. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18441. callback(fragmentCode);
  18442. return;
  18443. }
  18444. // Is in local store ?
  18445. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18446. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18447. return;
  18448. }
  18449. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18450. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18451. return;
  18452. }
  18453. var fragmentShaderUrl;
  18454. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18455. fragmentShaderUrl = fragment;
  18456. }
  18457. else {
  18458. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18459. }
  18460. // Fragment shader
  18461. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18462. };
  18463. Effect.prototype._dumpShadersName = function () {
  18464. if (this.name.vertexElement) {
  18465. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18466. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18467. }
  18468. else if (this.name.vertex) {
  18469. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18470. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18471. }
  18472. else {
  18473. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18474. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18475. }
  18476. };
  18477. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18478. try {
  18479. var engine = this._engine;
  18480. if (!engine.getCaps().highPrecisionShaderSupported) {
  18481. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18482. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18483. }
  18484. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18485. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18486. this._attributes = engine.getAttributes(this._program, attributesNames);
  18487. for (var index = 0; index < this._samplers.length; index++) {
  18488. var sampler = this.getUniform(this._samplers[index]);
  18489. if (sampler == null) {
  18490. this._samplers.splice(index, 1);
  18491. index--;
  18492. }
  18493. }
  18494. engine.bindSamplers(this);
  18495. this._isReady = true;
  18496. if (this.onCompiled) {
  18497. this.onCompiled(this);
  18498. }
  18499. }
  18500. catch (e) {
  18501. // Is it a problem with precision?
  18502. if (e.message.indexOf("highp") !== -1) {
  18503. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18504. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18505. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18506. return;
  18507. }
  18508. // Let's go through fallbacks then
  18509. if (fallbacks && fallbacks.isMoreFallbacks) {
  18510. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18511. this._dumpShadersName();
  18512. defines = fallbacks.reduce(defines);
  18513. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18514. }
  18515. else {
  18516. BABYLON.Tools.Error("Unable to compile effect: ");
  18517. this._dumpShadersName();
  18518. BABYLON.Tools.Error("Defines: " + defines);
  18519. BABYLON.Tools.Error("Error: " + e.message);
  18520. this._compilationError = e.message;
  18521. if (this.onError) {
  18522. this.onError(this, this._compilationError);
  18523. }
  18524. }
  18525. }
  18526. };
  18527. Object.defineProperty(Effect.prototype, "isSupported", {
  18528. get: function () {
  18529. return this._compilationError === "";
  18530. },
  18531. enumerable: true,
  18532. configurable: true
  18533. });
  18534. Effect.prototype._bindTexture = function (channel, texture) {
  18535. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18536. };
  18537. Effect.prototype.setTexture = function (channel, texture) {
  18538. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18539. };
  18540. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18541. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18542. };
  18543. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18544. if (!this._valueCache[uniformName]) {
  18545. this._valueCache[uniformName] = new BABYLON.Matrix();
  18546. }
  18547. for (var index = 0; index < 16; index++) {
  18548. this._valueCache[uniformName].m[index] = matrix.m[index];
  18549. }
  18550. };
  18551. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18552. if (!this._valueCache[uniformName]) {
  18553. this._valueCache[uniformName] = [x, y];
  18554. return;
  18555. }
  18556. this._valueCache[uniformName][0] = x;
  18557. this._valueCache[uniformName][1] = y;
  18558. };
  18559. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18560. if (!this._valueCache[uniformName]) {
  18561. this._valueCache[uniformName] = [x, y, z];
  18562. return;
  18563. }
  18564. this._valueCache[uniformName][0] = x;
  18565. this._valueCache[uniformName][1] = y;
  18566. this._valueCache[uniformName][2] = z;
  18567. };
  18568. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18569. if (!this._valueCache[uniformName]) {
  18570. this._valueCache[uniformName] = [x, y, z, w];
  18571. return;
  18572. }
  18573. this._valueCache[uniformName][0] = x;
  18574. this._valueCache[uniformName][1] = y;
  18575. this._valueCache[uniformName][2] = z;
  18576. this._valueCache[uniformName][3] = w;
  18577. };
  18578. Effect.prototype.setArray = function (uniformName, array) {
  18579. this._engine.setArray(this.getUniform(uniformName), array);
  18580. return this;
  18581. };
  18582. Effect.prototype.setArray2 = function (uniformName, array) {
  18583. this._engine.setArray2(this.getUniform(uniformName), array);
  18584. return this;
  18585. };
  18586. Effect.prototype.setArray3 = function (uniformName, array) {
  18587. this._engine.setArray3(this.getUniform(uniformName), array);
  18588. return this;
  18589. };
  18590. Effect.prototype.setArray4 = function (uniformName, array) {
  18591. this._engine.setArray4(this.getUniform(uniformName), array);
  18592. return this;
  18593. };
  18594. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18595. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18596. return this;
  18597. };
  18598. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18599. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18600. // return this;
  18601. // this._cacheMatrix(uniformName, matrix);
  18602. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18603. return this;
  18604. };
  18605. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18606. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18607. return this;
  18608. };
  18609. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18610. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18611. return this;
  18612. };
  18613. Effect.prototype.setFloat = function (uniformName, value) {
  18614. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18615. return this;
  18616. this._valueCache[uniformName] = value;
  18617. this._engine.setFloat(this.getUniform(uniformName), value);
  18618. return this;
  18619. };
  18620. Effect.prototype.setBool = function (uniformName, bool) {
  18621. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18622. return this;
  18623. this._valueCache[uniformName] = bool;
  18624. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18625. return this;
  18626. };
  18627. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18628. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18629. return this;
  18630. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18631. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18632. return this;
  18633. };
  18634. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18635. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18636. return this;
  18637. this._cacheFloat2(uniformName, x, y);
  18638. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18639. return this;
  18640. };
  18641. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18642. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18643. return this;
  18644. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18645. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18646. return this;
  18647. };
  18648. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18649. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18650. return this;
  18651. this._cacheFloat3(uniformName, x, y, z);
  18652. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18653. return this;
  18654. };
  18655. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18656. 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)
  18657. return this;
  18658. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18659. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18660. return this;
  18661. };
  18662. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18663. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18664. return this;
  18665. this._cacheFloat4(uniformName, x, y, z, w);
  18666. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18667. return this;
  18668. };
  18669. Effect.prototype.setColor3 = function (uniformName, color3) {
  18670. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18671. return this;
  18672. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18673. this._engine.setColor3(this.getUniform(uniformName), color3);
  18674. return this;
  18675. };
  18676. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18677. 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)
  18678. return this;
  18679. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18680. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18681. return this;
  18682. };
  18683. // Statics
  18684. Effect.ShadersStore = {};
  18685. return Effect;
  18686. })();
  18687. BABYLON.Effect = Effect;
  18688. })(BABYLON || (BABYLON = {}));
  18689. var BABYLON;
  18690. (function (BABYLON) {
  18691. var MaterialDefines = (function () {
  18692. function MaterialDefines() {
  18693. }
  18694. MaterialDefines.prototype.isEqual = function (other) {
  18695. for (var index = 0; index < this._keys.length; index++) {
  18696. var prop = this._keys[index];
  18697. if (this[prop] !== other[prop]) {
  18698. return false;
  18699. }
  18700. }
  18701. return true;
  18702. };
  18703. MaterialDefines.prototype.cloneTo = function (other) {
  18704. for (var index = 0; index < this._keys.length; index++) {
  18705. var prop = this._keys[index];
  18706. other[prop] = this[prop];
  18707. }
  18708. };
  18709. MaterialDefines.prototype.reset = function () {
  18710. for (var index = 0; index < this._keys.length; index++) {
  18711. var prop = this._keys[index];
  18712. if (typeof (this[prop]) === "number") {
  18713. this[prop] = 0;
  18714. }
  18715. else {
  18716. this[prop] = false;
  18717. }
  18718. }
  18719. };
  18720. MaterialDefines.prototype.toString = function () {
  18721. var result = "";
  18722. for (var index = 0; index < this._keys.length; index++) {
  18723. var prop = this._keys[index];
  18724. if (typeof (this[prop]) === "number") {
  18725. result += "#define " + prop + " " + this[prop] + "\n";
  18726. }
  18727. else if (this[prop]) {
  18728. result += "#define " + prop + "\n";
  18729. }
  18730. }
  18731. return result;
  18732. };
  18733. return MaterialDefines;
  18734. })();
  18735. BABYLON.MaterialDefines = MaterialDefines;
  18736. var Material = (function () {
  18737. function Material(name, scene, doNotAdd) {
  18738. this.name = name;
  18739. this.checkReadyOnEveryCall = false;
  18740. this.checkReadyOnlyOnce = false;
  18741. this.state = "";
  18742. this.alpha = 1.0;
  18743. this.backFaceCulling = true;
  18744. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18745. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18746. this.disableDepthWrite = false;
  18747. this.fogEnabled = true;
  18748. this._wasPreviouslyReady = false;
  18749. this._fillMode = Material.TriangleFillMode;
  18750. this.pointSize = 1.0;
  18751. this.zOffset = 0;
  18752. this.id = name;
  18753. this._scene = scene;
  18754. if (!doNotAdd) {
  18755. scene.materials.push(this);
  18756. }
  18757. }
  18758. Object.defineProperty(Material, "TriangleFillMode", {
  18759. get: function () {
  18760. return Material._TriangleFillMode;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(Material, "WireFrameFillMode", {
  18766. get: function () {
  18767. return Material._WireFrameFillMode;
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(Material, "PointFillMode", {
  18773. get: function () {
  18774. return Material._PointFillMode;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18780. get: function () {
  18781. return Material._ClockWiseSideOrientation;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18787. get: function () {
  18788. return Material._CounterClockWiseSideOrientation;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(Material.prototype, "wireframe", {
  18794. get: function () {
  18795. return this._fillMode === Material.WireFrameFillMode;
  18796. },
  18797. set: function (value) {
  18798. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Object.defineProperty(Material.prototype, "pointsCloud", {
  18804. get: function () {
  18805. return this._fillMode === Material.PointFillMode;
  18806. },
  18807. set: function (value) {
  18808. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. Object.defineProperty(Material.prototype, "fillMode", {
  18814. get: function () {
  18815. return this._fillMode;
  18816. },
  18817. set: function (value) {
  18818. this._fillMode = value;
  18819. },
  18820. enumerable: true,
  18821. configurable: true
  18822. });
  18823. Object.defineProperty(Material.prototype, "isFrozen", {
  18824. get: function () {
  18825. return this.checkReadyOnlyOnce;
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. Material.prototype.freeze = function () {
  18831. this.checkReadyOnlyOnce = true;
  18832. };
  18833. Material.prototype.unfreeze = function () {
  18834. this.checkReadyOnlyOnce = false;
  18835. };
  18836. Material.prototype.isReady = function (mesh, useInstances) {
  18837. return true;
  18838. };
  18839. Material.prototype.getEffect = function () {
  18840. return this._effect;
  18841. };
  18842. Material.prototype.getScene = function () {
  18843. return this._scene;
  18844. };
  18845. Material.prototype.needAlphaBlending = function () {
  18846. return (this.alpha < 1.0);
  18847. };
  18848. Material.prototype.needAlphaTesting = function () {
  18849. return false;
  18850. };
  18851. Material.prototype.getAlphaTestTexture = function () {
  18852. return null;
  18853. };
  18854. Material.prototype.trackCreation = function (onCompiled, onError) {
  18855. };
  18856. Material.prototype.markDirty = function () {
  18857. this._wasPreviouslyReady = false;
  18858. };
  18859. Material.prototype._preBind = function () {
  18860. var engine = this._scene.getEngine();
  18861. engine.enableEffect(this._effect);
  18862. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18863. };
  18864. Material.prototype.bind = function (world, mesh) {
  18865. this._scene._cachedMaterial = this;
  18866. if (this.onBind) {
  18867. this.onBind(this, mesh);
  18868. }
  18869. if (this.disableDepthWrite) {
  18870. var engine = this._scene.getEngine();
  18871. this._cachedDepthWriteState = engine.getDepthWrite();
  18872. engine.setDepthWrite(false);
  18873. }
  18874. };
  18875. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18876. };
  18877. Material.prototype.unbind = function () {
  18878. if (this.disableDepthWrite) {
  18879. var engine = this._scene.getEngine();
  18880. engine.setDepthWrite(this._cachedDepthWriteState);
  18881. }
  18882. };
  18883. Material.prototype.clone = function (name) {
  18884. return null;
  18885. };
  18886. Material.prototype.getBindedMeshes = function () {
  18887. var result = new Array();
  18888. for (var index = 0; index < this._scene.meshes.length; index++) {
  18889. var mesh = this._scene.meshes[index];
  18890. if (mesh.material === this) {
  18891. result.push(mesh);
  18892. }
  18893. }
  18894. return result;
  18895. };
  18896. Material.prototype.dispose = function (forceDisposeEffect) {
  18897. // Animations
  18898. this.getScene().stopAnimation(this);
  18899. // Remove from scene
  18900. var index = this._scene.materials.indexOf(this);
  18901. if (index >= 0) {
  18902. this._scene.materials.splice(index, 1);
  18903. }
  18904. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18905. if (forceDisposeEffect && this._effect) {
  18906. this._scene.getEngine()._releaseEffect(this._effect);
  18907. this._effect = null;
  18908. }
  18909. // Remove from meshes
  18910. for (index = 0; index < this._scene.meshes.length; index++) {
  18911. var mesh = this._scene.meshes[index];
  18912. if (mesh.material === this) {
  18913. mesh.material = null;
  18914. }
  18915. }
  18916. // Callback
  18917. if (this.onDispose) {
  18918. this.onDispose();
  18919. }
  18920. };
  18921. Material.prototype.copyTo = function (other) {
  18922. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18923. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18924. other.alpha = this.alpha;
  18925. other.fillMode = this.fillMode;
  18926. other.backFaceCulling = this.backFaceCulling;
  18927. other.fogEnabled = this.fogEnabled;
  18928. other.wireframe = this.wireframe;
  18929. other.zOffset = this.zOffset;
  18930. other.alphaMode = this.alphaMode;
  18931. other.sideOrientation = this.sideOrientation;
  18932. other.disableDepthWrite = this.disableDepthWrite;
  18933. other.pointSize = this.pointSize;
  18934. other.pointsCloud = this.pointsCloud;
  18935. };
  18936. Material.prototype.serialize = function () {
  18937. var serializationObject = {};
  18938. serializationObject.name = this.name;
  18939. serializationObject.alpha = this.alpha;
  18940. serializationObject.id = this.id;
  18941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18942. serializationObject.backFaceCulling = this.backFaceCulling;
  18943. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18944. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18945. return serializationObject;
  18946. };
  18947. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18948. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18949. multiMaterial.id = parsedMultiMaterial.id;
  18950. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18951. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18952. var subMatId = parsedMultiMaterial.materials[matIndex];
  18953. if (subMatId) {
  18954. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18955. }
  18956. else {
  18957. multiMaterial.subMaterials.push(null);
  18958. }
  18959. }
  18960. return multiMaterial;
  18961. };
  18962. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18963. if (!parsedMaterial.customType) {
  18964. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18965. }
  18966. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18967. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18968. ;
  18969. };
  18970. Material._TriangleFillMode = 0;
  18971. Material._WireFrameFillMode = 1;
  18972. Material._PointFillMode = 2;
  18973. Material._ClockWiseSideOrientation = 0;
  18974. Material._CounterClockWiseSideOrientation = 1;
  18975. return Material;
  18976. })();
  18977. BABYLON.Material = Material;
  18978. })(BABYLON || (BABYLON = {}));
  18979. var BABYLON;
  18980. (function (BABYLON) {
  18981. var maxSimultaneousLights = 4;
  18982. var FresnelParameters = (function () {
  18983. function FresnelParameters() {
  18984. this.isEnabled = true;
  18985. this.leftColor = BABYLON.Color3.White();
  18986. this.rightColor = BABYLON.Color3.Black();
  18987. this.bias = 0;
  18988. this.power = 1;
  18989. }
  18990. FresnelParameters.prototype.clone = function () {
  18991. var newFresnelParameters = new FresnelParameters();
  18992. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18993. return new FresnelParameters;
  18994. };
  18995. FresnelParameters.prototype.serialize = function () {
  18996. var serializationObject = {};
  18997. serializationObject.isEnabled = this.isEnabled;
  18998. serializationObject.leftColor = this.leftColor;
  18999. serializationObject.rightColor = this.rightColor;
  19000. serializationObject.bias = this.bias;
  19001. serializationObject.power = this.power;
  19002. return serializationObject;
  19003. };
  19004. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19005. var fresnelParameters = new FresnelParameters();
  19006. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19007. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19008. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19009. fresnelParameters.bias = parsedFresnelParameters.bias;
  19010. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19011. return fresnelParameters;
  19012. };
  19013. return FresnelParameters;
  19014. })();
  19015. BABYLON.FresnelParameters = FresnelParameters;
  19016. var StandardMaterialDefines = (function (_super) {
  19017. __extends(StandardMaterialDefines, _super);
  19018. function StandardMaterialDefines() {
  19019. _super.call(this);
  19020. this.DIFFUSE = false;
  19021. this.AMBIENT = false;
  19022. this.OPACITY = false;
  19023. this.OPACITYRGB = false;
  19024. this.REFLECTION = false;
  19025. this.EMISSIVE = false;
  19026. this.SPECULAR = false;
  19027. this.BUMP = false;
  19028. this.SPECULAROVERALPHA = false;
  19029. this.CLIPPLANE = false;
  19030. this.ALPHATEST = false;
  19031. this.ALPHAFROMDIFFUSE = false;
  19032. this.POINTSIZE = false;
  19033. this.FOG = false;
  19034. this.LIGHT0 = false;
  19035. this.LIGHT1 = false;
  19036. this.LIGHT2 = false;
  19037. this.LIGHT3 = false;
  19038. this.SPOTLIGHT0 = false;
  19039. this.SPOTLIGHT1 = false;
  19040. this.SPOTLIGHT2 = false;
  19041. this.SPOTLIGHT3 = false;
  19042. this.HEMILIGHT0 = false;
  19043. this.HEMILIGHT1 = false;
  19044. this.HEMILIGHT2 = false;
  19045. this.HEMILIGHT3 = false;
  19046. this.POINTLIGHT0 = false;
  19047. this.POINTLIGHT1 = false;
  19048. this.POINTLIGHT2 = false;
  19049. this.POINTLIGHT3 = false;
  19050. this.DIRLIGHT0 = false;
  19051. this.DIRLIGHT1 = false;
  19052. this.DIRLIGHT2 = false;
  19053. this.DIRLIGHT3 = false;
  19054. this.SPECULARTERM = false;
  19055. this.SHADOW0 = false;
  19056. this.SHADOW1 = false;
  19057. this.SHADOW2 = false;
  19058. this.SHADOW3 = false;
  19059. this.SHADOWS = false;
  19060. this.SHADOWVSM0 = false;
  19061. this.SHADOWVSM1 = false;
  19062. this.SHADOWVSM2 = false;
  19063. this.SHADOWVSM3 = false;
  19064. this.SHADOWPCF0 = false;
  19065. this.SHADOWPCF1 = false;
  19066. this.SHADOWPCF2 = false;
  19067. this.SHADOWPCF3 = false;
  19068. this.DIFFUSEFRESNEL = false;
  19069. this.OPACITYFRESNEL = false;
  19070. this.REFLECTIONFRESNEL = false;
  19071. this.EMISSIVEFRESNEL = false;
  19072. this.FRESNEL = false;
  19073. this.NORMAL = false;
  19074. this.UV1 = false;
  19075. this.UV2 = false;
  19076. this.VERTEXCOLOR = false;
  19077. this.VERTEXALPHA = false;
  19078. this.NUM_BONE_INFLUENCERS = 0;
  19079. this.BonesPerMesh = 0;
  19080. this.INSTANCES = false;
  19081. this.GLOSSINESS = false;
  19082. this.ROUGHNESS = false;
  19083. this.EMISSIVEASILLUMINATION = false;
  19084. this.LINKEMISSIVEWITHDIFFUSE = false;
  19085. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19086. this.LIGHTMAP = false;
  19087. this.USELIGHTMAPASSHADOWMAP = false;
  19088. this.REFLECTIONMAP_3D = false;
  19089. this.REFLECTIONMAP_SPHERICAL = false;
  19090. this.REFLECTIONMAP_PLANAR = false;
  19091. this.REFLECTIONMAP_CUBIC = false;
  19092. this.REFLECTIONMAP_PROJECTION = false;
  19093. this.REFLECTIONMAP_SKYBOX = false;
  19094. this.REFLECTIONMAP_EXPLICIT = false;
  19095. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19096. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19097. this.INVERTCUBICMAP = false;
  19098. this.LOGARITHMICDEPTH = false;
  19099. this._keys = Object.keys(this);
  19100. }
  19101. return StandardMaterialDefines;
  19102. })(BABYLON.MaterialDefines);
  19103. var StandardMaterial = (function (_super) {
  19104. __extends(StandardMaterial, _super);
  19105. function StandardMaterial(name, scene) {
  19106. var _this = this;
  19107. _super.call(this, name, scene);
  19108. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19109. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19110. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19111. this.specularPower = 64;
  19112. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19113. this.useAlphaFromDiffuseTexture = false;
  19114. this.useEmissiveAsIllumination = false;
  19115. this.linkEmissiveWithDiffuse = false;
  19116. this.useReflectionFresnelFromSpecular = false;
  19117. this.useSpecularOverAlpha = false;
  19118. this.disableLighting = false;
  19119. this.roughness = 0;
  19120. this.useLightmapAsShadowmap = false;
  19121. this.useGlossinessFromSpecularMapAlpha = false;
  19122. this._renderTargets = new BABYLON.SmartArray(16);
  19123. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19124. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19125. this._defines = new StandardMaterialDefines();
  19126. this._cachedDefines = new StandardMaterialDefines();
  19127. this._cachedDefines.BonesPerMesh = -1;
  19128. this.getRenderTargetTextures = function () {
  19129. _this._renderTargets.reset();
  19130. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19131. _this._renderTargets.push(_this.reflectionTexture);
  19132. }
  19133. return _this._renderTargets;
  19134. };
  19135. }
  19136. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19137. get: function () {
  19138. return this._useLogarithmicDepth;
  19139. },
  19140. set: function (value) {
  19141. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19142. },
  19143. enumerable: true,
  19144. configurable: true
  19145. });
  19146. StandardMaterial.prototype.needAlphaBlending = function () {
  19147. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19148. };
  19149. StandardMaterial.prototype.needAlphaTesting = function () {
  19150. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19151. };
  19152. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19153. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19154. };
  19155. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19156. return this.diffuseTexture;
  19157. };
  19158. // Methods
  19159. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19160. if (!mesh) {
  19161. return true;
  19162. }
  19163. if (this._defines.INSTANCES !== useInstances) {
  19164. return false;
  19165. }
  19166. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19167. return true;
  19168. }
  19169. return false;
  19170. };
  19171. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19172. var lightIndex = 0;
  19173. var needNormals = false;
  19174. for (var index = 0; index < scene.lights.length; index++) {
  19175. var light = scene.lights[index];
  19176. if (!light.isEnabled()) {
  19177. continue;
  19178. }
  19179. // Excluded check
  19180. if (light._excludedMeshesIds.length > 0) {
  19181. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19182. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19183. if (excludedMesh) {
  19184. light.excludedMeshes.push(excludedMesh);
  19185. }
  19186. }
  19187. light._excludedMeshesIds = [];
  19188. }
  19189. // Included check
  19190. if (light._includedOnlyMeshesIds.length > 0) {
  19191. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19192. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19193. if (includedOnlyMesh) {
  19194. light.includedOnlyMeshes.push(includedOnlyMesh);
  19195. }
  19196. }
  19197. light._includedOnlyMeshesIds = [];
  19198. }
  19199. if (!light.canAffectMesh(mesh)) {
  19200. continue;
  19201. }
  19202. needNormals = true;
  19203. defines["LIGHT" + lightIndex] = true;
  19204. var type;
  19205. if (light instanceof BABYLON.SpotLight) {
  19206. type = "SPOTLIGHT" + lightIndex;
  19207. }
  19208. else if (light instanceof BABYLON.HemisphericLight) {
  19209. type = "HEMILIGHT" + lightIndex;
  19210. }
  19211. else if (light instanceof BABYLON.PointLight) {
  19212. type = "POINTLIGHT" + lightIndex;
  19213. }
  19214. else {
  19215. type = "DIRLIGHT" + lightIndex;
  19216. }
  19217. defines[type] = true;
  19218. // Specular
  19219. if (!light.specular.equalsFloats(0, 0, 0)) {
  19220. defines["SPECULARTERM"] = true;
  19221. }
  19222. // Shadows
  19223. if (scene.shadowsEnabled) {
  19224. var shadowGenerator = light.getShadowGenerator();
  19225. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19226. defines["SHADOW" + lightIndex] = true;
  19227. defines["SHADOWS"] = true;
  19228. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19229. defines["SHADOWVSM" + lightIndex] = true;
  19230. }
  19231. if (shadowGenerator.usePoissonSampling) {
  19232. defines["SHADOWPCF" + lightIndex] = true;
  19233. }
  19234. }
  19235. }
  19236. lightIndex++;
  19237. if (lightIndex === maxSimultaneousLights)
  19238. break;
  19239. }
  19240. return needNormals;
  19241. };
  19242. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19243. var lightIndex = 0;
  19244. var depthValuesAlreadySet = false;
  19245. for (var index = 0; index < scene.lights.length; index++) {
  19246. var light = scene.lights[index];
  19247. if (!light.isEnabled()) {
  19248. continue;
  19249. }
  19250. if (!light.canAffectMesh(mesh)) {
  19251. continue;
  19252. }
  19253. if (light instanceof BABYLON.PointLight) {
  19254. // Point Light
  19255. light.transferToEffect(effect, "vLightData" + lightIndex);
  19256. }
  19257. else if (light instanceof BABYLON.DirectionalLight) {
  19258. // Directional Light
  19259. light.transferToEffect(effect, "vLightData" + lightIndex);
  19260. }
  19261. else if (light instanceof BABYLON.SpotLight) {
  19262. // Spot Light
  19263. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19264. }
  19265. else if (light instanceof BABYLON.HemisphericLight) {
  19266. // Hemispheric Light
  19267. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19268. }
  19269. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19270. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19271. if (defines["SPECULARTERM"]) {
  19272. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19273. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19274. }
  19275. // Shadows
  19276. if (scene.shadowsEnabled) {
  19277. var shadowGenerator = light.getShadowGenerator();
  19278. if (mesh.receiveShadows && shadowGenerator) {
  19279. if (!light.needCube()) {
  19280. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19281. }
  19282. else {
  19283. if (!depthValuesAlreadySet) {
  19284. depthValuesAlreadySet = true;
  19285. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19286. }
  19287. }
  19288. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19289. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19290. }
  19291. }
  19292. lightIndex++;
  19293. if (lightIndex === maxSimultaneousLights)
  19294. break;
  19295. }
  19296. };
  19297. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19298. if (this.isFrozen) {
  19299. if (this._wasPreviouslyReady) {
  19300. return true;
  19301. }
  19302. }
  19303. var scene = this.getScene();
  19304. if (!this.checkReadyOnEveryCall) {
  19305. if (this._renderId === scene.getRenderId()) {
  19306. if (this._checkCache(scene, mesh, useInstances)) {
  19307. return true;
  19308. }
  19309. }
  19310. }
  19311. var engine = scene.getEngine();
  19312. var needNormals = false;
  19313. var needUVs = false;
  19314. this._defines.reset();
  19315. // Textures
  19316. if (scene.texturesEnabled) {
  19317. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19318. if (!this.diffuseTexture.isReady()) {
  19319. return false;
  19320. }
  19321. else {
  19322. needUVs = true;
  19323. this._defines.DIFFUSE = true;
  19324. }
  19325. }
  19326. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19327. if (!this.ambientTexture.isReady()) {
  19328. return false;
  19329. }
  19330. else {
  19331. needUVs = true;
  19332. this._defines.AMBIENT = true;
  19333. }
  19334. }
  19335. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19336. if (!this.opacityTexture.isReady()) {
  19337. return false;
  19338. }
  19339. else {
  19340. needUVs = true;
  19341. this._defines.OPACITY = true;
  19342. if (this.opacityTexture.getAlphaFromRGB) {
  19343. this._defines.OPACITYRGB = true;
  19344. }
  19345. }
  19346. }
  19347. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19348. if (!this.reflectionTexture.isReady()) {
  19349. return false;
  19350. }
  19351. else {
  19352. needNormals = true;
  19353. this._defines.REFLECTION = true;
  19354. if (this.roughness > 0) {
  19355. this._defines.ROUGHNESS = true;
  19356. }
  19357. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19358. this._defines.INVERTCUBICMAP = true;
  19359. }
  19360. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19361. switch (this.reflectionTexture.coordinatesMode) {
  19362. case BABYLON.Texture.CUBIC_MODE:
  19363. case BABYLON.Texture.INVCUBIC_MODE:
  19364. this._defines.REFLECTIONMAP_CUBIC = true;
  19365. break;
  19366. case BABYLON.Texture.EXPLICIT_MODE:
  19367. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19368. break;
  19369. case BABYLON.Texture.PLANAR_MODE:
  19370. this._defines.REFLECTIONMAP_PLANAR = true;
  19371. break;
  19372. case BABYLON.Texture.PROJECTION_MODE:
  19373. this._defines.REFLECTIONMAP_PROJECTION = true;
  19374. break;
  19375. case BABYLON.Texture.SKYBOX_MODE:
  19376. this._defines.REFLECTIONMAP_SKYBOX = true;
  19377. break;
  19378. case BABYLON.Texture.SPHERICAL_MODE:
  19379. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19380. break;
  19381. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19382. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19383. break;
  19384. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19385. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19386. break;
  19387. }
  19388. }
  19389. }
  19390. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19391. if (!this.emissiveTexture.isReady()) {
  19392. return false;
  19393. }
  19394. else {
  19395. needUVs = true;
  19396. this._defines.EMISSIVE = true;
  19397. }
  19398. }
  19399. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19400. if (!this.lightmapTexture.isReady()) {
  19401. return false;
  19402. }
  19403. else {
  19404. needUVs = true;
  19405. this._defines.LIGHTMAP = true;
  19406. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19407. }
  19408. }
  19409. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19410. if (!this.specularTexture.isReady()) {
  19411. return false;
  19412. }
  19413. else {
  19414. needUVs = true;
  19415. this._defines.SPECULAR = true;
  19416. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19417. }
  19418. }
  19419. }
  19420. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19421. if (!this.bumpTexture.isReady()) {
  19422. return false;
  19423. }
  19424. else {
  19425. needUVs = true;
  19426. this._defines.BUMP = true;
  19427. }
  19428. }
  19429. // Effect
  19430. if (scene.clipPlane) {
  19431. this._defines.CLIPPLANE = true;
  19432. }
  19433. if (engine.getAlphaTesting()) {
  19434. this._defines.ALPHATEST = true;
  19435. }
  19436. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19437. this._defines.ALPHAFROMDIFFUSE = true;
  19438. }
  19439. if (this.useEmissiveAsIllumination) {
  19440. this._defines.EMISSIVEASILLUMINATION = true;
  19441. }
  19442. if (this.linkEmissiveWithDiffuse) {
  19443. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19444. }
  19445. if (this.useReflectionFresnelFromSpecular) {
  19446. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19447. }
  19448. if (this.useLogarithmicDepth) {
  19449. this._defines.LOGARITHMICDEPTH = true;
  19450. }
  19451. // Point size
  19452. if (this.pointsCloud || scene.forcePointsCloud) {
  19453. this._defines.POINTSIZE = true;
  19454. }
  19455. // Fog
  19456. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19457. this._defines.FOG = true;
  19458. }
  19459. if (scene.lightsEnabled && !this.disableLighting) {
  19460. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19461. }
  19462. if (StandardMaterial.FresnelEnabled) {
  19463. // Fresnel
  19464. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19465. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19466. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19467. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19468. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19469. this._defines.DIFFUSEFRESNEL = true;
  19470. }
  19471. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19472. this._defines.OPACITYFRESNEL = true;
  19473. }
  19474. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19475. this._defines.REFLECTIONFRESNEL = true;
  19476. }
  19477. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19478. this._defines.EMISSIVEFRESNEL = true;
  19479. }
  19480. needNormals = true;
  19481. this._defines.FRESNEL = true;
  19482. }
  19483. }
  19484. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19485. this._defines.SPECULAROVERALPHA = true;
  19486. }
  19487. // Attribs
  19488. if (mesh) {
  19489. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19490. this._defines.NORMAL = true;
  19491. }
  19492. if (needUVs) {
  19493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19494. this._defines.UV1 = true;
  19495. }
  19496. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19497. this._defines.UV2 = true;
  19498. }
  19499. }
  19500. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19501. this._defines.VERTEXCOLOR = true;
  19502. if (mesh.hasVertexAlpha) {
  19503. this._defines.VERTEXALPHA = true;
  19504. }
  19505. }
  19506. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19507. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19508. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19509. }
  19510. // Instances
  19511. if (useInstances) {
  19512. this._defines.INSTANCES = true;
  19513. }
  19514. }
  19515. // Get correct effect
  19516. if (!this._defines.isEqual(this._cachedDefines)) {
  19517. this._defines.cloneTo(this._cachedDefines);
  19518. scene.resetCachedMaterial();
  19519. // Fallbacks
  19520. var fallbacks = new BABYLON.EffectFallbacks();
  19521. if (this._defines.REFLECTION) {
  19522. fallbacks.addFallback(0, "REFLECTION");
  19523. }
  19524. if (this._defines.SPECULAR) {
  19525. fallbacks.addFallback(0, "SPECULAR");
  19526. }
  19527. if (this._defines.BUMP) {
  19528. fallbacks.addFallback(0, "BUMP");
  19529. }
  19530. if (this._defines.SPECULAROVERALPHA) {
  19531. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19532. }
  19533. if (this._defines.FOG) {
  19534. fallbacks.addFallback(1, "FOG");
  19535. }
  19536. if (this._defines.POINTSIZE) {
  19537. fallbacks.addFallback(0, "POINTSIZE");
  19538. }
  19539. if (this._defines.LOGARITHMICDEPTH) {
  19540. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19541. }
  19542. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19543. if (!this._defines["LIGHT" + lightIndex]) {
  19544. continue;
  19545. }
  19546. if (lightIndex > 0) {
  19547. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19548. }
  19549. if (this._defines["SHADOW" + lightIndex]) {
  19550. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19551. }
  19552. if (this._defines["SHADOWPCF" + lightIndex]) {
  19553. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19554. }
  19555. if (this._defines["SHADOWVSM" + lightIndex]) {
  19556. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19557. }
  19558. }
  19559. if (this._defines.SPECULARTERM) {
  19560. fallbacks.addFallback(0, "SPECULARTERM");
  19561. }
  19562. if (this._defines.DIFFUSEFRESNEL) {
  19563. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19564. }
  19565. if (this._defines.OPACITYFRESNEL) {
  19566. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19567. }
  19568. if (this._defines.REFLECTIONFRESNEL) {
  19569. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19570. }
  19571. if (this._defines.EMISSIVEFRESNEL) {
  19572. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19573. }
  19574. if (this._defines.FRESNEL) {
  19575. fallbacks.addFallback(4, "FRESNEL");
  19576. }
  19577. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19578. fallbacks.addCPUSkinningFallback(0, mesh);
  19579. }
  19580. //Attributes
  19581. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19582. if (this._defines.NORMAL) {
  19583. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19584. }
  19585. if (this._defines.UV1) {
  19586. attribs.push(BABYLON.VertexBuffer.UVKind);
  19587. }
  19588. if (this._defines.UV2) {
  19589. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19590. }
  19591. if (this._defines.VERTEXCOLOR) {
  19592. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19593. }
  19594. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19595. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19596. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19597. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19598. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19599. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19600. }
  19601. }
  19602. if (this._defines.INSTANCES) {
  19603. attribs.push("world0");
  19604. attribs.push("world1");
  19605. attribs.push("world2");
  19606. attribs.push("world3");
  19607. }
  19608. // Legacy browser patch
  19609. var shaderName = "default";
  19610. if (!scene.getEngine().getCaps().standardDerivatives) {
  19611. shaderName = "legacydefault";
  19612. }
  19613. var join = this._defines.toString();
  19614. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19615. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19616. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19617. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19618. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19619. "vFogInfos", "vFogColor", "pointSize",
  19620. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19621. "mBones",
  19622. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19623. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19624. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19625. "logarithmicDepthConstant"
  19626. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19627. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19628. ], join, fallbacks, this.onCompiled, this.onError);
  19629. }
  19630. if (!this._effect.isReady()) {
  19631. return false;
  19632. }
  19633. this._renderId = scene.getRenderId();
  19634. this._wasPreviouslyReady = true;
  19635. if (mesh) {
  19636. if (!mesh._materialDefines) {
  19637. mesh._materialDefines = new StandardMaterialDefines();
  19638. }
  19639. this._defines.cloneTo(mesh._materialDefines);
  19640. }
  19641. return true;
  19642. };
  19643. StandardMaterial.prototype.unbind = function () {
  19644. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19645. this._effect.setTexture("reflection2DSampler", null);
  19646. }
  19647. _super.prototype.unbind.call(this);
  19648. };
  19649. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19650. this._effect.setMatrix("world", world);
  19651. };
  19652. StandardMaterial.prototype.bind = function (world, mesh) {
  19653. var scene = this.getScene();
  19654. // Matrices
  19655. this.bindOnlyWorldMatrix(world);
  19656. // Bones
  19657. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19658. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19659. }
  19660. if (scene.getCachedMaterial() !== this) {
  19661. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19662. if (StandardMaterial.FresnelEnabled) {
  19663. // Fresnel
  19664. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19665. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19666. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19667. }
  19668. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19669. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19670. }
  19671. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19672. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19673. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19674. }
  19675. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19676. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19677. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19678. }
  19679. }
  19680. // Textures
  19681. if (scene.texturesEnabled) {
  19682. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19683. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19684. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19685. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19686. }
  19687. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19688. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19689. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19690. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19691. }
  19692. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19693. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19694. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19695. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19696. }
  19697. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19698. if (this.reflectionTexture.isCube) {
  19699. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19700. }
  19701. else {
  19702. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19703. }
  19704. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19705. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19706. }
  19707. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19708. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19709. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19710. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19711. }
  19712. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19713. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19714. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19715. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19716. }
  19717. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19718. this._effect.setTexture("specularSampler", this.specularTexture);
  19719. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19720. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19721. }
  19722. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19723. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19724. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19725. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19726. }
  19727. }
  19728. // Clip plane
  19729. if (scene.clipPlane) {
  19730. var clipPlane = scene.clipPlane;
  19731. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19732. }
  19733. // Point size
  19734. if (this.pointsCloud) {
  19735. this._effect.setFloat("pointSize", this.pointSize);
  19736. }
  19737. // Colors
  19738. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19739. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19740. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19741. if (this._defines.SPECULARTERM) {
  19742. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19743. }
  19744. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19745. }
  19746. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19747. // Diffuse
  19748. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19749. // Lights
  19750. if (scene.lightsEnabled && !this.disableLighting) {
  19751. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19752. }
  19753. // View
  19754. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19755. this._effect.setMatrix("view", scene.getViewMatrix());
  19756. }
  19757. // Fog
  19758. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19759. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19760. this._effect.setColor3("vFogColor", scene.fogColor);
  19761. }
  19762. // Log. depth
  19763. if (this._defines.LOGARITHMICDEPTH) {
  19764. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19765. }
  19766. }
  19767. _super.prototype.bind.call(this, world, mesh);
  19768. };
  19769. StandardMaterial.prototype.getAnimatables = function () {
  19770. var results = [];
  19771. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19772. results.push(this.diffuseTexture);
  19773. }
  19774. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19775. results.push(this.ambientTexture);
  19776. }
  19777. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19778. results.push(this.opacityTexture);
  19779. }
  19780. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19781. results.push(this.reflectionTexture);
  19782. }
  19783. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19784. results.push(this.emissiveTexture);
  19785. }
  19786. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19787. results.push(this.specularTexture);
  19788. }
  19789. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19790. results.push(this.bumpTexture);
  19791. }
  19792. return results;
  19793. };
  19794. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19795. if (this.diffuseTexture) {
  19796. this.diffuseTexture.dispose();
  19797. }
  19798. if (this.ambientTexture) {
  19799. this.ambientTexture.dispose();
  19800. }
  19801. if (this.opacityTexture) {
  19802. this.opacityTexture.dispose();
  19803. }
  19804. if (this.reflectionTexture) {
  19805. this.reflectionTexture.dispose();
  19806. }
  19807. if (this.emissiveTexture) {
  19808. this.emissiveTexture.dispose();
  19809. }
  19810. if (this.specularTexture) {
  19811. this.specularTexture.dispose();
  19812. }
  19813. if (this.bumpTexture) {
  19814. this.bumpTexture.dispose();
  19815. }
  19816. _super.prototype.dispose.call(this, forceDisposeEffect);
  19817. };
  19818. StandardMaterial.prototype.clone = function (name) {
  19819. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19820. // Base material
  19821. this.copyTo(newStandardMaterial);
  19822. // Standard material
  19823. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19824. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19825. }
  19826. if (this.ambientTexture && this.ambientTexture.clone) {
  19827. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19828. }
  19829. if (this.opacityTexture && this.opacityTexture.clone) {
  19830. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19831. }
  19832. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19833. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19834. }
  19835. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19836. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19837. }
  19838. if (this.specularTexture && this.specularTexture.clone) {
  19839. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19840. }
  19841. if (this.bumpTexture && this.bumpTexture.clone) {
  19842. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19843. }
  19844. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19845. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19846. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19847. }
  19848. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19849. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19850. newStandardMaterial.specularColor = this.specularColor.clone();
  19851. newStandardMaterial.specularPower = this.specularPower;
  19852. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19853. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19854. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19855. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19856. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19857. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19858. newStandardMaterial.roughness = this.roughness;
  19859. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19860. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19861. }
  19862. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19863. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19864. }
  19865. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19866. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19867. }
  19868. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19869. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19870. }
  19871. return newStandardMaterial;
  19872. };
  19873. StandardMaterial.prototype.serialize = function () {
  19874. var serializationObject = _super.prototype.serialize.call(this);
  19875. serializationObject.ambient = this.ambientColor.asArray();
  19876. serializationObject.diffuse = this.diffuseColor.asArray();
  19877. serializationObject.specular = this.specularColor.asArray();
  19878. serializationObject.specularPower = this.specularPower;
  19879. serializationObject.emissive = this.emissiveColor.asArray();
  19880. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19881. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19882. if (this.diffuseTexture) {
  19883. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19884. }
  19885. if (this.diffuseFresnelParameters) {
  19886. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19887. }
  19888. if (this.ambientTexture) {
  19889. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19890. }
  19891. if (this.opacityTexture) {
  19892. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19893. }
  19894. if (this.opacityFresnelParameters) {
  19895. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19896. }
  19897. if (this.reflectionTexture) {
  19898. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19899. }
  19900. if (this.reflectionFresnelParameters) {
  19901. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19902. }
  19903. if (this.emissiveTexture) {
  19904. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19905. }
  19906. if (this.lightmapTexture) {
  19907. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19908. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19909. }
  19910. if (this.emissiveFresnelParameters) {
  19911. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19912. }
  19913. if (this.specularTexture) {
  19914. serializationObject.specularTexture = this.specularTexture.serialize();
  19915. }
  19916. if (this.bumpTexture) {
  19917. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19918. }
  19919. return serializationObject;
  19920. };
  19921. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19922. var material = new StandardMaterial(source.name, scene);
  19923. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19924. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19925. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19926. material.specularPower = source.specularPower;
  19927. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19928. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19929. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19930. material.alpha = source.alpha;
  19931. material.id = source.id;
  19932. if (source.disableDepthWrite) {
  19933. material.disableDepthWrite = source.disableDepthWrite;
  19934. }
  19935. BABYLON.Tags.AddTagsTo(material, source.tags);
  19936. material.backFaceCulling = source.backFaceCulling;
  19937. material.wireframe = source.wireframe;
  19938. if (source.diffuseTexture) {
  19939. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19940. }
  19941. if (source.diffuseFresnelParameters) {
  19942. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19943. }
  19944. if (source.ambientTexture) {
  19945. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19946. }
  19947. if (source.opacityTexture) {
  19948. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19949. }
  19950. if (source.opacityFresnelParameters) {
  19951. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19952. }
  19953. if (source.reflectionTexture) {
  19954. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19955. }
  19956. if (source.reflectionFresnelParameters) {
  19957. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19958. }
  19959. if (source.emissiveTexture) {
  19960. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19961. }
  19962. if (source.lightmapTexture) {
  19963. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19964. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19965. }
  19966. if (source.emissiveFresnelParameters) {
  19967. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19968. }
  19969. if (source.specularTexture) {
  19970. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19971. }
  19972. if (source.bumpTexture) {
  19973. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19974. }
  19975. if (source.checkReadyOnlyOnce) {
  19976. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19977. }
  19978. return material;
  19979. };
  19980. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19981. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19982. // Statics
  19983. // Flags used to enable or disable a type of texture for all Standard Materials
  19984. StandardMaterial.DiffuseTextureEnabled = true;
  19985. StandardMaterial.AmbientTextureEnabled = true;
  19986. StandardMaterial.OpacityTextureEnabled = true;
  19987. StandardMaterial.ReflectionTextureEnabled = true;
  19988. StandardMaterial.EmissiveTextureEnabled = true;
  19989. StandardMaterial.SpecularTextureEnabled = true;
  19990. StandardMaterial.BumpTextureEnabled = true;
  19991. StandardMaterial.FresnelEnabled = true;
  19992. StandardMaterial.LightmapEnabled = true;
  19993. return StandardMaterial;
  19994. })(BABYLON.Material);
  19995. BABYLON.StandardMaterial = StandardMaterial;
  19996. })(BABYLON || (BABYLON = {}));
  19997. var BABYLON;
  19998. (function (BABYLON) {
  19999. var MultiMaterial = (function (_super) {
  20000. __extends(MultiMaterial, _super);
  20001. function MultiMaterial(name, scene) {
  20002. _super.call(this, name, scene, true);
  20003. this.subMaterials = new Array();
  20004. scene.multiMaterials.push(this);
  20005. }
  20006. // Properties
  20007. MultiMaterial.prototype.getSubMaterial = function (index) {
  20008. if (index < 0 || index >= this.subMaterials.length) {
  20009. return this.getScene().defaultMaterial;
  20010. }
  20011. return this.subMaterials[index];
  20012. };
  20013. // Methods
  20014. MultiMaterial.prototype.isReady = function (mesh) {
  20015. for (var index = 0; index < this.subMaterials.length; index++) {
  20016. var subMaterial = this.subMaterials[index];
  20017. if (subMaterial) {
  20018. if (!this.subMaterials[index].isReady(mesh)) {
  20019. return false;
  20020. }
  20021. }
  20022. }
  20023. return true;
  20024. };
  20025. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20026. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20027. for (var index = 0; index < this.subMaterials.length; index++) {
  20028. var subMaterial = null;
  20029. if (cloneChildren) {
  20030. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20031. }
  20032. else {
  20033. subMaterial = this.subMaterials[index];
  20034. }
  20035. newMultiMaterial.subMaterials.push(subMaterial);
  20036. }
  20037. return newMultiMaterial;
  20038. };
  20039. MultiMaterial.prototype.serialize = function () {
  20040. var serializationObject = {};
  20041. serializationObject.name = this.name;
  20042. serializationObject.id = this.id;
  20043. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20044. serializationObject.materials = [];
  20045. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20046. var subMat = this.subMaterials[matIndex];
  20047. if (subMat) {
  20048. serializationObject.materials.push(subMat.id);
  20049. }
  20050. else {
  20051. serializationObject.materials.push(null);
  20052. }
  20053. }
  20054. return serializationObject;
  20055. };
  20056. return MultiMaterial;
  20057. })(BABYLON.Material);
  20058. BABYLON.MultiMaterial = MultiMaterial;
  20059. })(BABYLON || (BABYLON = {}));
  20060. var BABYLON;
  20061. (function (BABYLON) {
  20062. var SceneLoader = (function () {
  20063. function SceneLoader() {
  20064. }
  20065. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20066. get: function () {
  20067. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20068. },
  20069. set: function (value) {
  20070. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20076. get: function () {
  20077. return SceneLoader._ShowLoadingScreen;
  20078. },
  20079. set: function (value) {
  20080. SceneLoader._ShowLoadingScreen = value;
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20086. var dotPosition = sceneFilename.lastIndexOf(".");
  20087. var queryStringPosition = sceneFilename.indexOf("?");
  20088. if (queryStringPosition === -1) {
  20089. queryStringPosition = sceneFilename.length;
  20090. }
  20091. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20092. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20093. var plugin = this._registeredPlugins[index];
  20094. if (plugin.extensions.indexOf(extension) !== -1) {
  20095. return plugin;
  20096. }
  20097. }
  20098. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20099. };
  20100. // Public functions
  20101. SceneLoader.RegisterPlugin = function (plugin) {
  20102. plugin.extensions = plugin.extensions.toLowerCase();
  20103. SceneLoader._registeredPlugins.push(plugin);
  20104. };
  20105. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20106. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20107. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20108. return;
  20109. }
  20110. var loadingToken = {};
  20111. scene._addPendingData(loadingToken);
  20112. var manifestChecked = function (success) {
  20113. scene.database = database;
  20114. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20115. var importMeshFromData = function (data) {
  20116. var meshes = [];
  20117. var particleSystems = [];
  20118. var skeletons = [];
  20119. try {
  20120. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20121. if (onerror) {
  20122. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20123. }
  20124. scene._removePendingData(loadingToken);
  20125. return;
  20126. }
  20127. }
  20128. catch (e) {
  20129. if (onerror) {
  20130. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20131. }
  20132. scene._removePendingData(loadingToken);
  20133. return;
  20134. }
  20135. if (onsuccess) {
  20136. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20137. onsuccess(meshes, particleSystems, skeletons);
  20138. scene._removePendingData(loadingToken);
  20139. }
  20140. };
  20141. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20142. // Direct load
  20143. importMeshFromData(sceneFilename.substr(5));
  20144. return;
  20145. }
  20146. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20147. importMeshFromData(data);
  20148. }, progressCallBack, database);
  20149. };
  20150. if (scene.getEngine().enableOfflineSupport) {
  20151. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20152. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20153. }
  20154. else {
  20155. manifestChecked(true);
  20156. }
  20157. };
  20158. /**
  20159. * Load a scene
  20160. * @param rootUrl a string that defines the root url for scene and resources
  20161. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20162. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20163. */
  20164. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20165. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20166. };
  20167. /**
  20168. * Append a scene
  20169. * @param rootUrl a string that defines the root url for scene and resources
  20170. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20171. * @param scene is the instance of BABYLON.Scene to append to
  20172. */
  20173. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20174. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20175. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20176. return;
  20177. }
  20178. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20179. var database;
  20180. var loadingToken = {};
  20181. scene._addPendingData(loadingToken);
  20182. if (SceneLoader.ShowLoadingScreen) {
  20183. scene.getEngine().displayLoadingUI();
  20184. }
  20185. var loadSceneFromData = function (data) {
  20186. scene.database = database;
  20187. if (!plugin.load(scene, data, rootUrl)) {
  20188. if (onerror) {
  20189. onerror(scene);
  20190. }
  20191. scene._removePendingData(loadingToken);
  20192. scene.getEngine().hideLoadingUI();
  20193. return;
  20194. }
  20195. if (onsuccess) {
  20196. onsuccess(scene);
  20197. }
  20198. scene._removePendingData(loadingToken);
  20199. if (SceneLoader.ShowLoadingScreen) {
  20200. scene.executeWhenReady(function () {
  20201. scene.getEngine().hideLoadingUI();
  20202. });
  20203. }
  20204. };
  20205. var manifestChecked = function (success) {
  20206. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20207. };
  20208. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20209. // Direct load
  20210. loadSceneFromData(sceneFilename.substr(5));
  20211. return;
  20212. }
  20213. if (rootUrl.indexOf("file:") === -1) {
  20214. if (scene.getEngine().enableOfflineSupport) {
  20215. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20216. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20217. }
  20218. else {
  20219. manifestChecked(true);
  20220. }
  20221. }
  20222. else {
  20223. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20224. }
  20225. };
  20226. // Flags
  20227. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20228. SceneLoader._ShowLoadingScreen = true;
  20229. // Members
  20230. SceneLoader._registeredPlugins = new Array();
  20231. return SceneLoader;
  20232. })();
  20233. BABYLON.SceneLoader = SceneLoader;
  20234. ;
  20235. })(BABYLON || (BABYLON = {}));
  20236. var BABYLON;
  20237. (function (BABYLON) {
  20238. var Internals;
  20239. (function (Internals) {
  20240. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20241. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20242. var parsedMaterial = parsedData.materials[index];
  20243. if (parsedMaterial.id === id) {
  20244. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20245. }
  20246. }
  20247. return null;
  20248. };
  20249. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20250. names = (names instanceof Array) ? names : [names];
  20251. for (var i in names) {
  20252. if (mesh.name === names[i]) {
  20253. hierarchyIds.push(mesh.id);
  20254. return true;
  20255. }
  20256. }
  20257. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20258. hierarchyIds.push(mesh.id);
  20259. return true;
  20260. }
  20261. return false;
  20262. };
  20263. BABYLON.SceneLoader.RegisterPlugin({
  20264. extensions: ".babylon",
  20265. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20266. var parsedData = JSON.parse(data);
  20267. var loadedSkeletonsIds = [];
  20268. var loadedMaterialsIds = [];
  20269. var hierarchyIds = [];
  20270. var index;
  20271. var cache;
  20272. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20273. var parsedMesh = parsedData.meshes[index];
  20274. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20275. if (meshesNames instanceof Array) {
  20276. // Remove found mesh name from list.
  20277. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20278. }
  20279. //Geometry?
  20280. if (parsedMesh.geometryId) {
  20281. //does the file contain geometries?
  20282. if (parsedData.geometries) {
  20283. //find the correct geometry and add it to the scene
  20284. var found = false;
  20285. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20286. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20287. return;
  20288. }
  20289. else {
  20290. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20291. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20292. switch (geometryType) {
  20293. case "boxes":
  20294. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20295. break;
  20296. case "spheres":
  20297. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20298. break;
  20299. case "cylinders":
  20300. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20301. break;
  20302. case "toruses":
  20303. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20304. break;
  20305. case "grounds":
  20306. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20307. break;
  20308. case "planes":
  20309. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20310. break;
  20311. case "torusKnots":
  20312. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20313. break;
  20314. case "vertexData":
  20315. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20316. break;
  20317. }
  20318. found = true;
  20319. }
  20320. });
  20321. }
  20322. });
  20323. if (!found) {
  20324. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20325. }
  20326. }
  20327. }
  20328. // Material ?
  20329. if (parsedMesh.materialId) {
  20330. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20331. if (!materialFound && parsedData.multiMaterials) {
  20332. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20333. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20334. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20335. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20336. var subMatId = parsedMultiMaterial.materials[matIndex];
  20337. loadedMaterialsIds.push(subMatId);
  20338. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20339. }
  20340. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20341. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20342. materialFound = true;
  20343. break;
  20344. }
  20345. }
  20346. }
  20347. if (!materialFound) {
  20348. loadedMaterialsIds.push(parsedMesh.materialId);
  20349. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20350. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20351. }
  20352. }
  20353. }
  20354. // Skeleton ?
  20355. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20356. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20357. if (!skeletonAlreadyLoaded) {
  20358. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20359. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20360. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20361. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20362. loadedSkeletonsIds.push(parsedSkeleton.id);
  20363. }
  20364. }
  20365. }
  20366. }
  20367. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20368. meshes.push(mesh);
  20369. }
  20370. }
  20371. // Connecting parents
  20372. var currentMesh;
  20373. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20374. currentMesh = scene.meshes[index];
  20375. if (currentMesh._waitingParentId) {
  20376. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20377. currentMesh._waitingParentId = undefined;
  20378. }
  20379. }
  20380. // freeze world matrix application
  20381. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20382. currentMesh = scene.meshes[index];
  20383. if (currentMesh._waitingFreezeWorldMatrix) {
  20384. currentMesh.freezeWorldMatrix();
  20385. currentMesh._waitingFreezeWorldMatrix = undefined;
  20386. }
  20387. }
  20388. // Particles
  20389. if (parsedData.particleSystems) {
  20390. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20391. var parsedParticleSystem = parsedData.particleSystems[index];
  20392. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20393. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20394. }
  20395. }
  20396. }
  20397. return true;
  20398. },
  20399. load: function (scene, data, rootUrl) {
  20400. var parsedData = JSON.parse(data);
  20401. // Scene
  20402. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20403. scene.autoClear = parsedData.autoClear;
  20404. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20405. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20406. if (parsedData.gravity) {
  20407. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20408. }
  20409. // Fog
  20410. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20411. scene.fogMode = parsedData.fogMode;
  20412. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20413. scene.fogStart = parsedData.fogStart;
  20414. scene.fogEnd = parsedData.fogEnd;
  20415. scene.fogDensity = parsedData.fogDensity;
  20416. }
  20417. //Physics
  20418. if (parsedData.physicsEnabled) {
  20419. var physicsPlugin;
  20420. if (parsedData.physicsEngine === "cannon") {
  20421. physicsPlugin = new BABYLON.CannonJSPlugin();
  20422. }
  20423. else if (parsedData.physicsEngine === "oimo") {
  20424. physicsPlugin = new BABYLON.OimoJSPlugin();
  20425. }
  20426. //else - default engine, which is currently oimo
  20427. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20428. scene.enablePhysics(physicsGravity, physicsPlugin);
  20429. }
  20430. //collisions, if defined. otherwise, default is true
  20431. if (parsedData.collisionsEnabled != undefined) {
  20432. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20433. }
  20434. scene.workerCollisions = !!parsedData.workerCollisions;
  20435. var index;
  20436. var cache;
  20437. // Lights
  20438. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20439. var parsedLight = parsedData.lights[index];
  20440. BABYLON.Light.Parse(parsedLight, scene);
  20441. }
  20442. // Materials
  20443. if (parsedData.materials) {
  20444. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20445. var parsedMaterial = parsedData.materials[index];
  20446. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20447. }
  20448. }
  20449. if (parsedData.multiMaterials) {
  20450. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20451. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20452. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20453. }
  20454. }
  20455. // Skeletons
  20456. if (parsedData.skeletons) {
  20457. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20458. var parsedSkeleton = parsedData.skeletons[index];
  20459. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20460. }
  20461. }
  20462. // Geometries
  20463. var geometries = parsedData.geometries;
  20464. if (geometries) {
  20465. // Boxes
  20466. var boxes = geometries.boxes;
  20467. if (boxes) {
  20468. for (index = 0, cache = boxes.length; index < cache; index++) {
  20469. var parsedBox = boxes[index];
  20470. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20471. }
  20472. }
  20473. // Spheres
  20474. var spheres = geometries.spheres;
  20475. if (spheres) {
  20476. for (index = 0, cache = spheres.length; index < cache; index++) {
  20477. var parsedSphere = spheres[index];
  20478. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20479. }
  20480. }
  20481. // Cylinders
  20482. var cylinders = geometries.cylinders;
  20483. if (cylinders) {
  20484. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20485. var parsedCylinder = cylinders[index];
  20486. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20487. }
  20488. }
  20489. // Toruses
  20490. var toruses = geometries.toruses;
  20491. if (toruses) {
  20492. for (index = 0, cache = toruses.length; index < cache; index++) {
  20493. var parsedTorus = toruses[index];
  20494. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20495. }
  20496. }
  20497. // Grounds
  20498. var grounds = geometries.grounds;
  20499. if (grounds) {
  20500. for (index = 0, cache = grounds.length; index < cache; index++) {
  20501. var parsedGround = grounds[index];
  20502. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20503. }
  20504. }
  20505. // Planes
  20506. var planes = geometries.planes;
  20507. if (planes) {
  20508. for (index = 0, cache = planes.length; index < cache; index++) {
  20509. var parsedPlane = planes[index];
  20510. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20511. }
  20512. }
  20513. // TorusKnots
  20514. var torusKnots = geometries.torusKnots;
  20515. if (torusKnots) {
  20516. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20517. var parsedTorusKnot = torusKnots[index];
  20518. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20519. }
  20520. }
  20521. // VertexData
  20522. var vertexData = geometries.vertexData;
  20523. if (vertexData) {
  20524. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20525. var parsedVertexData = vertexData[index];
  20526. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20527. }
  20528. }
  20529. }
  20530. // Meshes
  20531. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20532. var parsedMesh = parsedData.meshes[index];
  20533. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20534. }
  20535. // Cameras
  20536. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20537. var parsedCamera = parsedData.cameras[index];
  20538. BABYLON.Camera.Parse(parsedCamera, scene);
  20539. }
  20540. if (parsedData.activeCameraID) {
  20541. scene.setActiveCameraByID(parsedData.activeCameraID);
  20542. }
  20543. // Browsing all the graph to connect the dots
  20544. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20545. var camera = scene.cameras[index];
  20546. if (camera._waitingParentId) {
  20547. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20548. camera._waitingParentId = undefined;
  20549. }
  20550. }
  20551. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20552. var light = scene.lights[index];
  20553. if (light._waitingParentId) {
  20554. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20555. light._waitingParentId = undefined;
  20556. }
  20557. }
  20558. // Sounds
  20559. var loadedSounds = [];
  20560. var loadedSound;
  20561. if (BABYLON.AudioEngine && parsedData.sounds) {
  20562. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20563. var parsedSound = parsedData.sounds[index];
  20564. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20565. if (!parsedSound.url)
  20566. parsedSound.url = parsedSound.name;
  20567. if (!loadedSounds[parsedSound.url]) {
  20568. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20569. loadedSounds[parsedSound.url] = loadedSound;
  20570. }
  20571. else {
  20572. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20573. }
  20574. }
  20575. else {
  20576. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20577. }
  20578. }
  20579. }
  20580. loadedSounds = [];
  20581. // Connect parents & children and parse actions
  20582. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20583. var mesh = scene.meshes[index];
  20584. if (mesh._waitingParentId) {
  20585. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20586. mesh._waitingParentId = undefined;
  20587. }
  20588. if (mesh._waitingActions) {
  20589. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20590. mesh._waitingActions = undefined;
  20591. }
  20592. }
  20593. // freeze world matrix application
  20594. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20595. var currentMesh = scene.meshes[index];
  20596. if (currentMesh._waitingFreezeWorldMatrix) {
  20597. currentMesh.freezeWorldMatrix();
  20598. currentMesh._waitingFreezeWorldMatrix = undefined;
  20599. }
  20600. }
  20601. // Particles Systems
  20602. if (parsedData.particleSystems) {
  20603. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20604. var parsedParticleSystem = parsedData.particleSystems[index];
  20605. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20606. }
  20607. }
  20608. // Lens flares
  20609. if (parsedData.lensFlareSystems) {
  20610. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20611. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20612. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20613. }
  20614. }
  20615. // Shadows
  20616. if (parsedData.shadowGenerators) {
  20617. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20618. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20619. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20620. }
  20621. }
  20622. // Actions (scene)
  20623. if (parsedData.actions) {
  20624. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20625. }
  20626. // Finish
  20627. return true;
  20628. }
  20629. });
  20630. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20631. })(BABYLON || (BABYLON = {}));
  20632. var BABYLON;
  20633. (function (BABYLON) {
  20634. var SpriteManager = (function () {
  20635. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20637. this.name = name;
  20638. this.cellSize = cellSize;
  20639. this.sprites = new Array();
  20640. this.renderingGroupId = 0;
  20641. this.layerMask = 0x0FFFFFFF;
  20642. this.fogEnabled = true;
  20643. this.isPickable = false;
  20644. this._vertexDeclaration = [4, 4, 4, 4];
  20645. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20646. this._capacity = capacity;
  20647. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20648. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20649. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20650. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20651. this._scene = scene;
  20652. this._scene.spriteManagers.push(this);
  20653. // VBO
  20654. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20655. var indices = [];
  20656. var index = 0;
  20657. for (var count = 0; count < capacity; count++) {
  20658. indices.push(index);
  20659. indices.push(index + 1);
  20660. indices.push(index + 2);
  20661. indices.push(index);
  20662. indices.push(index + 2);
  20663. indices.push(index + 3);
  20664. index += 4;
  20665. }
  20666. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20667. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20668. // Effects
  20669. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20670. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20671. }
  20672. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20673. var arrayOffset = index * 16;
  20674. if (offsetX === 0)
  20675. offsetX = this._epsilon;
  20676. else if (offsetX === 1)
  20677. offsetX = 1 - this._epsilon;
  20678. if (offsetY === 0)
  20679. offsetY = this._epsilon;
  20680. else if (offsetY === 1)
  20681. offsetY = 1 - this._epsilon;
  20682. this._vertices[arrayOffset] = sprite.position.x;
  20683. this._vertices[arrayOffset + 1] = sprite.position.y;
  20684. this._vertices[arrayOffset + 2] = sprite.position.z;
  20685. this._vertices[arrayOffset + 3] = sprite.angle;
  20686. this._vertices[arrayOffset + 4] = sprite.width;
  20687. this._vertices[arrayOffset + 5] = sprite.height;
  20688. this._vertices[arrayOffset + 6] = offsetX;
  20689. this._vertices[arrayOffset + 7] = offsetY;
  20690. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20691. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20692. var offset = (sprite.cellIndex / rowSize) >> 0;
  20693. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20694. this._vertices[arrayOffset + 11] = offset;
  20695. // Color
  20696. this._vertices[arrayOffset + 12] = sprite.color.r;
  20697. this._vertices[arrayOffset + 13] = sprite.color.g;
  20698. this._vertices[arrayOffset + 14] = sprite.color.b;
  20699. this._vertices[arrayOffset + 15] = sprite.color.a;
  20700. };
  20701. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20702. var count = Math.min(this._capacity, this.sprites.length);
  20703. var min = BABYLON.Vector3.Zero();
  20704. var max = BABYLON.Vector3.Zero();
  20705. var distance = Number.MAX_VALUE;
  20706. var currentSprite;
  20707. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20708. var cameraView = camera.getViewMatrix();
  20709. for (var index = 0; index < count; index++) {
  20710. var sprite = this.sprites[index];
  20711. if (!sprite) {
  20712. continue;
  20713. }
  20714. if (predicate) {
  20715. if (!predicate(sprite)) {
  20716. continue;
  20717. }
  20718. }
  20719. else if (!sprite.isPickable) {
  20720. continue;
  20721. }
  20722. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20723. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20724. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20725. if (ray.intersectsBoxMinMax(min, max)) {
  20726. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20727. if (distance > currentDistance) {
  20728. distance = currentDistance;
  20729. currentSprite = sprite;
  20730. if (fastCheck) {
  20731. break;
  20732. }
  20733. }
  20734. }
  20735. }
  20736. if (currentSprite) {
  20737. var result = new BABYLON.PickingInfo();
  20738. result.hit = true;
  20739. result.pickedSprite = currentSprite;
  20740. result.distance = distance;
  20741. return result;
  20742. }
  20743. return null;
  20744. };
  20745. SpriteManager.prototype.render = function () {
  20746. // Check
  20747. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20748. return;
  20749. var engine = this._scene.getEngine();
  20750. var baseSize = this._spriteTexture.getBaseSize();
  20751. // Sprites
  20752. var deltaTime = engine.getDeltaTime();
  20753. var max = Math.min(this._capacity, this.sprites.length);
  20754. var rowSize = baseSize.width / this.cellSize;
  20755. var offset = 0;
  20756. for (var index = 0; index < max; index++) {
  20757. var sprite = this.sprites[index];
  20758. if (!sprite) {
  20759. continue;
  20760. }
  20761. sprite._animate(deltaTime);
  20762. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20763. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20764. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20765. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20766. }
  20767. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20768. // Render
  20769. var effect = this._effectBase;
  20770. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20771. effect = this._effectFog;
  20772. }
  20773. engine.enableEffect(effect);
  20774. var viewMatrix = this._scene.getViewMatrix();
  20775. effect.setTexture("diffuseSampler", this._spriteTexture);
  20776. effect.setMatrix("view", viewMatrix);
  20777. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20778. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20779. // Fog
  20780. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20781. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20782. effect.setColor3("vFogColor", this._scene.fogColor);
  20783. }
  20784. // VBOs
  20785. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20786. // Draw order
  20787. engine.setDepthFunctionToLessOrEqual();
  20788. effect.setBool("alphaTest", true);
  20789. engine.setColorWrite(false);
  20790. engine.draw(true, 0, max * 6);
  20791. engine.setColorWrite(true);
  20792. effect.setBool("alphaTest", false);
  20793. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20794. engine.draw(true, 0, max * 6);
  20795. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20796. };
  20797. SpriteManager.prototype.dispose = function () {
  20798. if (this._vertexBuffer) {
  20799. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20800. this._vertexBuffer = null;
  20801. }
  20802. if (this._indexBuffer) {
  20803. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20804. this._indexBuffer = null;
  20805. }
  20806. if (this._spriteTexture) {
  20807. this._spriteTexture.dispose();
  20808. this._spriteTexture = null;
  20809. }
  20810. // Remove from scene
  20811. var index = this._scene.spriteManagers.indexOf(this);
  20812. this._scene.spriteManagers.splice(index, 1);
  20813. // Callback
  20814. if (this.onDispose) {
  20815. this.onDispose();
  20816. }
  20817. };
  20818. return SpriteManager;
  20819. })();
  20820. BABYLON.SpriteManager = SpriteManager;
  20821. })(BABYLON || (BABYLON = {}));
  20822. var BABYLON;
  20823. (function (BABYLON) {
  20824. var Sprite = (function () {
  20825. function Sprite(name, manager) {
  20826. this.name = name;
  20827. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20828. this.width = 1.0;
  20829. this.height = 1.0;
  20830. this.angle = 0;
  20831. this.cellIndex = 0;
  20832. this.invertU = 0;
  20833. this.invertV = 0;
  20834. this.animations = new Array();
  20835. this.isPickable = false;
  20836. this._animationStarted = false;
  20837. this._loopAnimation = false;
  20838. this._fromIndex = 0;
  20839. this._toIndex = 0;
  20840. this._delay = 0;
  20841. this._direction = 1;
  20842. this._frameCount = 0;
  20843. this._time = 0;
  20844. this._manager = manager;
  20845. this._manager.sprites.push(this);
  20846. this.position = BABYLON.Vector3.Zero();
  20847. }
  20848. Object.defineProperty(Sprite.prototype, "size", {
  20849. get: function () {
  20850. return this.width;
  20851. },
  20852. set: function (value) {
  20853. this.width = value;
  20854. this.height = value;
  20855. },
  20856. enumerable: true,
  20857. configurable: true
  20858. });
  20859. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20860. this._fromIndex = from;
  20861. this._toIndex = to;
  20862. this._loopAnimation = loop;
  20863. this._delay = delay;
  20864. this._animationStarted = true;
  20865. this._direction = from < to ? 1 : -1;
  20866. this.cellIndex = from;
  20867. this._time = 0;
  20868. };
  20869. Sprite.prototype.stopAnimation = function () {
  20870. this._animationStarted = false;
  20871. };
  20872. Sprite.prototype._animate = function (deltaTime) {
  20873. if (!this._animationStarted)
  20874. return;
  20875. this._time += deltaTime;
  20876. if (this._time > this._delay) {
  20877. this._time = this._time % this._delay;
  20878. this.cellIndex += this._direction;
  20879. if (this.cellIndex == this._toIndex) {
  20880. if (this._loopAnimation) {
  20881. this.cellIndex = this._fromIndex;
  20882. }
  20883. else {
  20884. this._animationStarted = false;
  20885. if (this.disposeWhenFinishedAnimating) {
  20886. this.dispose();
  20887. }
  20888. }
  20889. }
  20890. }
  20891. };
  20892. Sprite.prototype.dispose = function () {
  20893. for (var i = 0; i < this._manager.sprites.length; i++) {
  20894. if (this._manager.sprites[i] == this) {
  20895. this._manager.sprites.splice(i, 1);
  20896. }
  20897. }
  20898. };
  20899. return Sprite;
  20900. })();
  20901. BABYLON.Sprite = Sprite;
  20902. })(BABYLON || (BABYLON = {}));
  20903. var BABYLON;
  20904. (function (BABYLON) {
  20905. var Layer = (function () {
  20906. function Layer(name, imgUrl, scene, isBackground, color) {
  20907. this.name = name;
  20908. this.scale = new BABYLON.Vector2(1, 1);
  20909. this.offset = new BABYLON.Vector2(0, 0);
  20910. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20911. this._vertexDeclaration = [2];
  20912. this._vertexStrideSize = 2 * 4;
  20913. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20914. this.isBackground = isBackground === undefined ? true : isBackground;
  20915. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20916. this._scene = scene;
  20917. this._scene.layers.push(this);
  20918. // VBO
  20919. var vertices = [];
  20920. vertices.push(1, 1);
  20921. vertices.push(-1, 1);
  20922. vertices.push(-1, -1);
  20923. vertices.push(1, -1);
  20924. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20925. // Indices
  20926. var indices = [];
  20927. indices.push(0);
  20928. indices.push(1);
  20929. indices.push(2);
  20930. indices.push(0);
  20931. indices.push(2);
  20932. indices.push(3);
  20933. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20934. // Effects
  20935. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  20936. }
  20937. Layer.prototype.render = function () {
  20938. // Check
  20939. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20940. return;
  20941. var engine = this._scene.getEngine();
  20942. // Render
  20943. engine.enableEffect(this._effect);
  20944. engine.setState(false);
  20945. // Texture
  20946. this._effect.setTexture("textureSampler", this.texture);
  20947. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20948. // Color
  20949. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20950. // Scale / offset
  20951. this._effect.setVector2("offset", this.offset);
  20952. this._effect.setVector2("scale", this.scale);
  20953. // VBOs
  20954. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20955. // Draw order
  20956. engine.setAlphaMode(this.alphaBlendingMode);
  20957. engine.draw(true, 0, 6);
  20958. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20959. };
  20960. Layer.prototype.dispose = function () {
  20961. if (this._vertexBuffer) {
  20962. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20963. this._vertexBuffer = null;
  20964. }
  20965. if (this._indexBuffer) {
  20966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20967. this._indexBuffer = null;
  20968. }
  20969. if (this.texture) {
  20970. this.texture.dispose();
  20971. this.texture = null;
  20972. }
  20973. // Remove from scene
  20974. var index = this._scene.layers.indexOf(this);
  20975. this._scene.layers.splice(index, 1);
  20976. // Callback
  20977. if (this.onDispose) {
  20978. this.onDispose();
  20979. }
  20980. };
  20981. return Layer;
  20982. })();
  20983. BABYLON.Layer = Layer;
  20984. })(BABYLON || (BABYLON = {}));
  20985. var BABYLON;
  20986. (function (BABYLON) {
  20987. var Particle = (function () {
  20988. function Particle() {
  20989. this.position = BABYLON.Vector3.Zero();
  20990. this.direction = BABYLON.Vector3.Zero();
  20991. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20992. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20993. this.lifeTime = 1.0;
  20994. this.age = 0;
  20995. this.size = 0;
  20996. this.angle = 0;
  20997. this.angularSpeed = 0;
  20998. }
  20999. Particle.prototype.copyTo = function (other) {
  21000. other.position.copyFrom(this.position);
  21001. other.direction.copyFrom(this.direction);
  21002. other.color.copyFrom(this.color);
  21003. other.colorStep.copyFrom(this.colorStep);
  21004. other.lifeTime = this.lifeTime;
  21005. other.age = this.age;
  21006. other.size = this.size;
  21007. other.angle = this.angle;
  21008. other.angularSpeed = this.angularSpeed;
  21009. };
  21010. return Particle;
  21011. })();
  21012. BABYLON.Particle = Particle;
  21013. })(BABYLON || (BABYLON = {}));
  21014. var BABYLON;
  21015. (function (BABYLON) {
  21016. var randomNumber = function (min, max) {
  21017. if (min === max) {
  21018. return (min);
  21019. }
  21020. var random = Math.random();
  21021. return ((random * (max - min)) + min);
  21022. };
  21023. var ParticleSystem = (function () {
  21024. function ParticleSystem(name, capacity, scene, customEffect) {
  21025. var _this = this;
  21026. this.name = name;
  21027. this.renderingGroupId = 0;
  21028. this.emitter = null;
  21029. this.emitRate = 10;
  21030. this.manualEmitCount = -1;
  21031. this.updateSpeed = 0.01;
  21032. this.targetStopDuration = 0;
  21033. this.disposeOnStop = false;
  21034. this.minEmitPower = 1;
  21035. this.maxEmitPower = 1;
  21036. this.minLifeTime = 1;
  21037. this.maxLifeTime = 1;
  21038. this.minSize = 1;
  21039. this.maxSize = 1;
  21040. this.minAngularSpeed = 0;
  21041. this.maxAngularSpeed = 0;
  21042. this.layerMask = 0x0FFFFFFF;
  21043. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21044. this.forceDepthWrite = false;
  21045. this.gravity = BABYLON.Vector3.Zero();
  21046. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21047. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21048. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21049. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21050. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21051. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21052. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21053. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21054. this.particles = new Array();
  21055. this._vertexDeclaration = [3, 4, 4];
  21056. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21057. this._stockParticles = new Array();
  21058. this._newPartsExcess = 0;
  21059. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21060. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21061. this._scaledDirection = BABYLON.Vector3.Zero();
  21062. this._scaledGravity = BABYLON.Vector3.Zero();
  21063. this._currentRenderId = -1;
  21064. this._started = false;
  21065. this._stopped = false;
  21066. this._actualFrame = 0;
  21067. this.id = name;
  21068. this._capacity = capacity;
  21069. this._scene = scene;
  21070. this._customEffect = customEffect;
  21071. scene.particleSystems.push(this);
  21072. // VBO
  21073. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21074. var indices = [];
  21075. var index = 0;
  21076. for (var count = 0; count < capacity; count++) {
  21077. indices.push(index);
  21078. indices.push(index + 1);
  21079. indices.push(index + 2);
  21080. indices.push(index);
  21081. indices.push(index + 2);
  21082. indices.push(index + 3);
  21083. index += 4;
  21084. }
  21085. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21086. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21087. // Default behaviors
  21088. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21089. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21090. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21091. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21092. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21093. };
  21094. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21095. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21096. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21097. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21099. };
  21100. this.updateFunction = function (particles) {
  21101. for (var index = 0; index < particles.length; index++) {
  21102. var particle = particles[index];
  21103. particle.age += _this._scaledUpdateSpeed;
  21104. if (particle.age >= particle.lifeTime) {
  21105. _this.recycleParticle(particle);
  21106. index--;
  21107. continue;
  21108. }
  21109. else {
  21110. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21111. particle.color.addInPlace(_this._scaledColorStep);
  21112. if (particle.color.a < 0)
  21113. particle.color.a = 0;
  21114. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21115. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21116. particle.position.addInPlace(_this._scaledDirection);
  21117. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21118. particle.direction.addInPlace(_this._scaledGravity);
  21119. }
  21120. }
  21121. };
  21122. }
  21123. ParticleSystem.prototype.recycleParticle = function (particle) {
  21124. var lastParticle = this.particles.pop();
  21125. if (lastParticle !== particle) {
  21126. lastParticle.copyTo(particle);
  21127. this._stockParticles.push(lastParticle);
  21128. }
  21129. };
  21130. ParticleSystem.prototype.getCapacity = function () {
  21131. return this._capacity;
  21132. };
  21133. ParticleSystem.prototype.isAlive = function () {
  21134. return this._alive;
  21135. };
  21136. ParticleSystem.prototype.isStarted = function () {
  21137. return this._started;
  21138. };
  21139. ParticleSystem.prototype.start = function () {
  21140. this._started = true;
  21141. this._stopped = false;
  21142. this._actualFrame = 0;
  21143. };
  21144. ParticleSystem.prototype.stop = function () {
  21145. this._stopped = true;
  21146. };
  21147. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21148. var offset = index * 11;
  21149. this._vertices[offset] = particle.position.x;
  21150. this._vertices[offset + 1] = particle.position.y;
  21151. this._vertices[offset + 2] = particle.position.z;
  21152. this._vertices[offset + 3] = particle.color.r;
  21153. this._vertices[offset + 4] = particle.color.g;
  21154. this._vertices[offset + 5] = particle.color.b;
  21155. this._vertices[offset + 6] = particle.color.a;
  21156. this._vertices[offset + 7] = particle.angle;
  21157. this._vertices[offset + 8] = particle.size;
  21158. this._vertices[offset + 9] = offsetX;
  21159. this._vertices[offset + 10] = offsetY;
  21160. };
  21161. ParticleSystem.prototype._update = function (newParticles) {
  21162. // Update current
  21163. this._alive = this.particles.length > 0;
  21164. this.updateFunction(this.particles);
  21165. // Add new ones
  21166. var worldMatrix;
  21167. if (this.emitter.position) {
  21168. worldMatrix = this.emitter.getWorldMatrix();
  21169. }
  21170. else {
  21171. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21172. }
  21173. var particle;
  21174. for (var index = 0; index < newParticles; index++) {
  21175. if (this.particles.length === this._capacity) {
  21176. break;
  21177. }
  21178. if (this._stockParticles.length !== 0) {
  21179. particle = this._stockParticles.pop();
  21180. particle.age = 0;
  21181. }
  21182. else {
  21183. particle = new BABYLON.Particle();
  21184. }
  21185. this.particles.push(particle);
  21186. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21187. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21188. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21189. particle.size = randomNumber(this.minSize, this.maxSize);
  21190. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21191. this.startPositionFunction(worldMatrix, particle.position, particle);
  21192. var step = randomNumber(0, 1.0);
  21193. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21194. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21195. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21196. }
  21197. };
  21198. ParticleSystem.prototype._getEffect = function () {
  21199. if (this._customEffect) {
  21200. return this._customEffect;
  21201. }
  21202. ;
  21203. var defines = [];
  21204. if (this._scene.clipPlane) {
  21205. defines.push("#define CLIPPLANE");
  21206. }
  21207. // Effect
  21208. var join = defines.join("\n");
  21209. if (this._cachedDefines !== join) {
  21210. this._cachedDefines = join;
  21211. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21212. }
  21213. return this._effect;
  21214. };
  21215. ParticleSystem.prototype.animate = function () {
  21216. if (!this._started)
  21217. return;
  21218. var effect = this._getEffect();
  21219. // Check
  21220. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21221. return;
  21222. if (this._currentRenderId === this._scene.getRenderId()) {
  21223. return;
  21224. }
  21225. this._currentRenderId = this._scene.getRenderId();
  21226. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21227. // determine the number of particles we need to create
  21228. var newParticles;
  21229. if (this.manualEmitCount > -1) {
  21230. newParticles = this.manualEmitCount;
  21231. this._newPartsExcess = 0;
  21232. this.manualEmitCount = 0;
  21233. }
  21234. else {
  21235. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21236. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21237. }
  21238. if (this._newPartsExcess > 1.0) {
  21239. newParticles += this._newPartsExcess >> 0;
  21240. this._newPartsExcess -= this._newPartsExcess >> 0;
  21241. }
  21242. this._alive = false;
  21243. if (!this._stopped) {
  21244. this._actualFrame += this._scaledUpdateSpeed;
  21245. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21246. this.stop();
  21247. }
  21248. else {
  21249. newParticles = 0;
  21250. }
  21251. this._update(newParticles);
  21252. // Stopped?
  21253. if (this._stopped) {
  21254. if (!this._alive) {
  21255. this._started = false;
  21256. if (this.disposeOnStop) {
  21257. this._scene._toBeDisposed.push(this);
  21258. }
  21259. }
  21260. }
  21261. // Update VBO
  21262. var offset = 0;
  21263. for (var index = 0; index < this.particles.length; index++) {
  21264. var particle = this.particles[index];
  21265. this._appendParticleVertex(offset++, particle, 0, 0);
  21266. this._appendParticleVertex(offset++, particle, 1, 0);
  21267. this._appendParticleVertex(offset++, particle, 1, 1);
  21268. this._appendParticleVertex(offset++, particle, 0, 1);
  21269. }
  21270. var engine = this._scene.getEngine();
  21271. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21272. };
  21273. ParticleSystem.prototype.render = function () {
  21274. var effect = this._getEffect();
  21275. // Check
  21276. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21277. return 0;
  21278. var engine = this._scene.getEngine();
  21279. // Render
  21280. engine.enableEffect(effect);
  21281. engine.setState(false);
  21282. var viewMatrix = this._scene.getViewMatrix();
  21283. effect.setTexture("diffuseSampler", this.particleTexture);
  21284. effect.setMatrix("view", viewMatrix);
  21285. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21286. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21287. if (this._scene.clipPlane) {
  21288. var clipPlane = this._scene.clipPlane;
  21289. var invView = viewMatrix.clone();
  21290. invView.invert();
  21291. effect.setMatrix("invView", invView);
  21292. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21293. }
  21294. // VBOs
  21295. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21296. // Draw order
  21297. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21298. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21299. }
  21300. else {
  21301. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21302. }
  21303. if (this.forceDepthWrite) {
  21304. engine.setDepthWrite(true);
  21305. }
  21306. engine.draw(true, 0, this.particles.length * 6);
  21307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21308. return this.particles.length;
  21309. };
  21310. ParticleSystem.prototype.dispose = function () {
  21311. if (this._vertexBuffer) {
  21312. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21313. this._vertexBuffer = null;
  21314. }
  21315. if (this._indexBuffer) {
  21316. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21317. this._indexBuffer = null;
  21318. }
  21319. if (this.particleTexture) {
  21320. this.particleTexture.dispose();
  21321. this.particleTexture = null;
  21322. }
  21323. // Remove from scene
  21324. var index = this._scene.particleSystems.indexOf(this);
  21325. this._scene.particleSystems.splice(index, 1);
  21326. // Callback
  21327. if (this.onDispose) {
  21328. this.onDispose();
  21329. }
  21330. };
  21331. // Clone
  21332. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21333. var result = new ParticleSystem(name, this._capacity, this._scene);
  21334. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21335. if (newEmitter === undefined) {
  21336. newEmitter = this.emitter;
  21337. }
  21338. result.emitter = newEmitter;
  21339. if (this.particleTexture) {
  21340. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21341. }
  21342. result.start();
  21343. return result;
  21344. };
  21345. ParticleSystem.prototype.serialize = function () {
  21346. var serializationObject = {};
  21347. serializationObject.name = this.name;
  21348. if (this.emitter.position) {
  21349. serializationObject.emitterId = this.emitter.id;
  21350. }
  21351. else {
  21352. serializationObject.emitter = this.emitter.asArray();
  21353. ;
  21354. }
  21355. serializationObject.capacity = this.getCapacity();
  21356. if (this.particleTexture) {
  21357. serializationObject.textureName = this.particleTexture.name;
  21358. }
  21359. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21360. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21361. serializationObject.minSize = this.minSize;
  21362. serializationObject.maxSize = this.maxSize;
  21363. serializationObject.minEmitPower = this.minEmitPower;
  21364. serializationObject.maxEmitPower = this.maxEmitPower;
  21365. serializationObject.minLifeTime = this.minLifeTime;
  21366. serializationObject.maxLifeTime = this.maxLifeTime;
  21367. serializationObject.emitRate = this.emitRate;
  21368. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21369. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21370. serializationObject.gravity = this.gravity.asArray();
  21371. serializationObject.direction1 = this.direction1.asArray();
  21372. serializationObject.direction2 = this.direction2.asArray();
  21373. serializationObject.color1 = this.color1.asArray();
  21374. serializationObject.color2 = this.color2.asArray();
  21375. serializationObject.colorDead = this.colorDead.asArray();
  21376. serializationObject.updateSpeed = this.updateSpeed;
  21377. serializationObject.targetStopDuration = this.targetStopDuration;
  21378. serializationObject.textureMask = this.textureMask.asArray();
  21379. serializationObject.blendMode = this.blendMode;
  21380. return serializationObject;
  21381. };
  21382. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21383. var name = parsedParticleSystem.name;
  21384. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21385. if (parsedParticleSystem.textureName) {
  21386. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21387. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21388. }
  21389. if (parsedParticleSystem.emitterId) {
  21390. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21391. }
  21392. else {
  21393. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21394. }
  21395. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21396. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21397. particleSystem.minSize = parsedParticleSystem.minSize;
  21398. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21399. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21400. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21401. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21402. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21403. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21404. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21405. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21406. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21407. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21408. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21409. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21410. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21411. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21412. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21413. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21414. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21415. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21416. particleSystem.start();
  21417. return particleSystem;
  21418. };
  21419. // Statics
  21420. ParticleSystem.BLENDMODE_ONEONE = 0;
  21421. ParticleSystem.BLENDMODE_STANDARD = 1;
  21422. return ParticleSystem;
  21423. })();
  21424. BABYLON.ParticleSystem = ParticleSystem;
  21425. })(BABYLON || (BABYLON = {}));
  21426. var BABYLON;
  21427. (function (BABYLON) {
  21428. var AnimationRange = (function () {
  21429. function AnimationRange(name, from, to) {
  21430. this.name = name;
  21431. this.from = from;
  21432. this.to = to;
  21433. }
  21434. return AnimationRange;
  21435. })();
  21436. BABYLON.AnimationRange = AnimationRange;
  21437. /**
  21438. * Composed of a frame, and an action function
  21439. */
  21440. var AnimationEvent = (function () {
  21441. function AnimationEvent(frame, action, onlyOnce) {
  21442. this.frame = frame;
  21443. this.action = action;
  21444. this.onlyOnce = onlyOnce;
  21445. this.isDone = false;
  21446. }
  21447. return AnimationEvent;
  21448. })();
  21449. BABYLON.AnimationEvent = AnimationEvent;
  21450. var Animation = (function () {
  21451. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21452. this.name = name;
  21453. this.targetProperty = targetProperty;
  21454. this.framePerSecond = framePerSecond;
  21455. this.dataType = dataType;
  21456. this.loopMode = loopMode;
  21457. this._offsetsCache = {};
  21458. this._highLimitsCache = {};
  21459. this._stopped = false;
  21460. // The set of event that will be linked to this animation
  21461. this._events = new Array();
  21462. this.allowMatricesInterpolation = false;
  21463. this._ranges = {};
  21464. this.targetPropertyPath = targetProperty.split(".");
  21465. this.dataType = dataType;
  21466. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21467. }
  21468. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21469. var dataType = undefined;
  21470. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21471. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21472. }
  21473. else if (from instanceof BABYLON.Quaternion) {
  21474. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21475. }
  21476. else if (from instanceof BABYLON.Vector3) {
  21477. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21478. }
  21479. else if (from instanceof BABYLON.Vector2) {
  21480. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21481. }
  21482. else if (from instanceof BABYLON.Color3) {
  21483. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21484. }
  21485. if (dataType == undefined) {
  21486. return null;
  21487. }
  21488. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21489. var keys = [];
  21490. keys.push({ frame: 0, value: from });
  21491. keys.push({ frame: totalFrame, value: to });
  21492. animation.setKeys(keys);
  21493. if (easingFunction !== undefined) {
  21494. animation.setEasingFunction(easingFunction);
  21495. }
  21496. return animation;
  21497. };
  21498. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21499. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21500. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21501. };
  21502. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21503. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21504. node.animations.push(animation);
  21505. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21506. };
  21507. // Methods
  21508. /**
  21509. * Add an event to this animation.
  21510. */
  21511. Animation.prototype.addEvent = function (event) {
  21512. this._events.push(event);
  21513. };
  21514. /**
  21515. * Remove all events found at the given frame
  21516. * @param frame
  21517. */
  21518. Animation.prototype.removeEvents = function (frame) {
  21519. for (var index = 0; index < this._events.length; index++) {
  21520. if (this._events[index].frame === frame) {
  21521. this._events.splice(index, 1);
  21522. index--;
  21523. }
  21524. }
  21525. };
  21526. Animation.prototype.createRange = function (name, from, to) {
  21527. // check name not already in use; could happen for bones after serialized
  21528. if (!this._ranges[name]) {
  21529. this._ranges[name] = new AnimationRange(name, from, to);
  21530. }
  21531. };
  21532. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21533. if (deleteFrames === void 0) { deleteFrames = true; }
  21534. if (this._ranges[name]) {
  21535. if (deleteFrames) {
  21536. var from = this._ranges[name].from;
  21537. var to = this._ranges[name].to;
  21538. // this loop MUST go high to low for multiple splices to work
  21539. for (var key = this._keys.length - 1; key >= 0; key--) {
  21540. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21541. this._keys.splice(key, 1);
  21542. }
  21543. }
  21544. }
  21545. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21546. }
  21547. };
  21548. Animation.prototype.getRange = function (name) {
  21549. return this._ranges[name];
  21550. };
  21551. Animation.prototype.reset = function () {
  21552. this._offsetsCache = {};
  21553. this._highLimitsCache = {};
  21554. this.currentFrame = 0;
  21555. };
  21556. Animation.prototype.isStopped = function () {
  21557. return this._stopped;
  21558. };
  21559. Animation.prototype.getKeys = function () {
  21560. return this._keys;
  21561. };
  21562. Animation.prototype.getHighestFrame = function () {
  21563. var ret = 0;
  21564. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21565. if (ret < this._keys[key].frame) {
  21566. ret = this._keys[key].frame;
  21567. }
  21568. }
  21569. return ret;
  21570. };
  21571. Animation.prototype.getEasingFunction = function () {
  21572. return this._easingFunction;
  21573. };
  21574. Animation.prototype.setEasingFunction = function (easingFunction) {
  21575. this._easingFunction = easingFunction;
  21576. };
  21577. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21578. return startValue + (endValue - startValue) * gradient;
  21579. };
  21580. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21581. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21582. };
  21583. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21584. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21585. };
  21586. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21587. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21588. };
  21589. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21590. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21591. };
  21592. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21593. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21594. };
  21595. Animation.prototype.clone = function () {
  21596. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21597. if (this._keys) {
  21598. clone.setKeys(this._keys);
  21599. }
  21600. return clone;
  21601. };
  21602. Animation.prototype.setKeys = function (values) {
  21603. this._keys = values.slice(0);
  21604. this._offsetsCache = {};
  21605. this._highLimitsCache = {};
  21606. };
  21607. Animation.prototype._getKeyValue = function (value) {
  21608. if (typeof value === "function") {
  21609. return value();
  21610. }
  21611. return value;
  21612. };
  21613. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21614. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21615. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21616. }
  21617. this.currentFrame = currentFrame;
  21618. // Try to get a hash to find the right key
  21619. 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));
  21620. if (this._keys[startKey].frame >= currentFrame) {
  21621. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21622. startKey--;
  21623. }
  21624. }
  21625. for (var key = startKey; key < this._keys.length; key++) {
  21626. if (this._keys[key + 1].frame >= currentFrame) {
  21627. var startValue = this._getKeyValue(this._keys[key].value);
  21628. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21629. // gradient : percent of currentFrame between the frame inf and the frame sup
  21630. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21631. // check for easingFunction and correction of gradient
  21632. if (this._easingFunction != null) {
  21633. gradient = this._easingFunction.ease(gradient);
  21634. }
  21635. switch (this.dataType) {
  21636. // Float
  21637. case Animation.ANIMATIONTYPE_FLOAT:
  21638. switch (loopMode) {
  21639. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21640. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21641. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21642. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21643. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21644. }
  21645. break;
  21646. // Quaternion
  21647. case Animation.ANIMATIONTYPE_QUATERNION:
  21648. var quaternion = null;
  21649. switch (loopMode) {
  21650. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21651. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21652. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21653. break;
  21654. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21655. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21656. break;
  21657. }
  21658. return quaternion;
  21659. // Vector3
  21660. case Animation.ANIMATIONTYPE_VECTOR3:
  21661. switch (loopMode) {
  21662. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21663. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21664. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21665. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21666. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21667. }
  21668. // Vector2
  21669. case Animation.ANIMATIONTYPE_VECTOR2:
  21670. switch (loopMode) {
  21671. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21672. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21673. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21674. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21675. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21676. }
  21677. // Color3
  21678. case Animation.ANIMATIONTYPE_COLOR3:
  21679. switch (loopMode) {
  21680. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21681. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21682. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21683. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21684. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21685. }
  21686. // Matrix
  21687. case Animation.ANIMATIONTYPE_MATRIX:
  21688. switch (loopMode) {
  21689. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21690. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21691. if (this.allowMatricesInterpolation) {
  21692. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21693. }
  21694. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21695. return startValue;
  21696. }
  21697. default:
  21698. break;
  21699. }
  21700. break;
  21701. }
  21702. }
  21703. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21704. };
  21705. Animation.prototype.setValue = function (currentValue) {
  21706. // Set value
  21707. if (this.targetPropertyPath.length > 1) {
  21708. var property = this._target[this.targetPropertyPath[0]];
  21709. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21710. property = property[this.targetPropertyPath[index]];
  21711. }
  21712. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21713. }
  21714. else {
  21715. this._target[this.targetPropertyPath[0]] = currentValue;
  21716. }
  21717. if (this._target.markAsDirty) {
  21718. this._target.markAsDirty(this.targetProperty);
  21719. }
  21720. };
  21721. Animation.prototype.goToFrame = function (frame) {
  21722. if (frame < this._keys[0].frame) {
  21723. frame = this._keys[0].frame;
  21724. }
  21725. else if (frame > this._keys[this._keys.length - 1].frame) {
  21726. frame = this._keys[this._keys.length - 1].frame;
  21727. }
  21728. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21729. this.setValue(currentValue);
  21730. };
  21731. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21732. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21733. this._stopped = true;
  21734. return false;
  21735. }
  21736. var returnValue = true;
  21737. // Adding a start key at frame 0 if missing
  21738. if (this._keys[0].frame !== 0) {
  21739. var newKey = { frame: 0, value: this._keys[0].value };
  21740. this._keys.splice(0, 0, newKey);
  21741. }
  21742. // Check limits
  21743. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21744. from = this._keys[0].frame;
  21745. }
  21746. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21747. to = this._keys[this._keys.length - 1].frame;
  21748. }
  21749. // Compute ratio
  21750. var range = to - from;
  21751. var offsetValue;
  21752. // ratio represents the frame delta between from and to
  21753. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21754. var highLimitValue = 0;
  21755. if (ratio > range && !loop) {
  21756. returnValue = false;
  21757. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21758. }
  21759. else {
  21760. // Get max value if required
  21761. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21762. var keyOffset = to.toString() + from.toString();
  21763. if (!this._offsetsCache[keyOffset]) {
  21764. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21765. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21766. switch (this.dataType) {
  21767. // Float
  21768. case Animation.ANIMATIONTYPE_FLOAT:
  21769. this._offsetsCache[keyOffset] = toValue - fromValue;
  21770. break;
  21771. // Quaternion
  21772. case Animation.ANIMATIONTYPE_QUATERNION:
  21773. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21774. break;
  21775. // Vector3
  21776. case Animation.ANIMATIONTYPE_VECTOR3:
  21777. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21778. // Vector2
  21779. case Animation.ANIMATIONTYPE_VECTOR2:
  21780. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21781. // Color3
  21782. case Animation.ANIMATIONTYPE_COLOR3:
  21783. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21784. default:
  21785. break;
  21786. }
  21787. this._highLimitsCache[keyOffset] = toValue;
  21788. }
  21789. highLimitValue = this._highLimitsCache[keyOffset];
  21790. offsetValue = this._offsetsCache[keyOffset];
  21791. }
  21792. }
  21793. if (offsetValue === undefined) {
  21794. switch (this.dataType) {
  21795. // Float
  21796. case Animation.ANIMATIONTYPE_FLOAT:
  21797. offsetValue = 0;
  21798. break;
  21799. // Quaternion
  21800. case Animation.ANIMATIONTYPE_QUATERNION:
  21801. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21802. break;
  21803. // Vector3
  21804. case Animation.ANIMATIONTYPE_VECTOR3:
  21805. offsetValue = BABYLON.Vector3.Zero();
  21806. break;
  21807. // Vector2
  21808. case Animation.ANIMATIONTYPE_VECTOR2:
  21809. offsetValue = BABYLON.Vector2.Zero();
  21810. break;
  21811. // Color3
  21812. case Animation.ANIMATIONTYPE_COLOR3:
  21813. offsetValue = BABYLON.Color3.Black();
  21814. }
  21815. }
  21816. // Compute value
  21817. var repeatCount = (ratio / range) >> 0;
  21818. var currentFrame = returnValue ? from + ratio % range : to;
  21819. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21820. // Set value
  21821. this.setValue(currentValue);
  21822. // Check events
  21823. for (var index = 0; index < this._events.length; index++) {
  21824. if (currentFrame >= this._events[index].frame) {
  21825. var event = this._events[index];
  21826. if (!event.isDone) {
  21827. // If event should be done only once, remove it.
  21828. if (event.onlyOnce) {
  21829. this._events.splice(index, 1);
  21830. index--;
  21831. }
  21832. event.isDone = true;
  21833. event.action();
  21834. } // Don't do anything if the event has already be done.
  21835. }
  21836. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21837. // reset event, the animation is looping
  21838. this._events[index].isDone = false;
  21839. }
  21840. }
  21841. if (!returnValue) {
  21842. this._stopped = true;
  21843. }
  21844. return returnValue;
  21845. };
  21846. Animation.prototype.serialize = function () {
  21847. var serializationObject = {};
  21848. serializationObject.name = this.name;
  21849. serializationObject.property = this.targetProperty;
  21850. serializationObject.framePerSecond = this.framePerSecond;
  21851. serializationObject.dataType = this.dataType;
  21852. serializationObject.loopBehavior = this.loopMode;
  21853. var dataType = this.dataType;
  21854. serializationObject.keys = [];
  21855. var keys = this.getKeys();
  21856. for (var index = 0; index < keys.length; index++) {
  21857. var animationKey = keys[index];
  21858. var key = {};
  21859. key.frame = animationKey.frame;
  21860. switch (dataType) {
  21861. case Animation.ANIMATIONTYPE_FLOAT:
  21862. key.values = [animationKey.value];
  21863. break;
  21864. case Animation.ANIMATIONTYPE_QUATERNION:
  21865. case Animation.ANIMATIONTYPE_MATRIX:
  21866. case Animation.ANIMATIONTYPE_VECTOR3:
  21867. case Animation.ANIMATIONTYPE_COLOR3:
  21868. key.values = animationKey.value.asArray();
  21869. break;
  21870. }
  21871. serializationObject.keys.push(key);
  21872. }
  21873. serializationObject.ranges = [];
  21874. for (var name in this._ranges) {
  21875. var range = {};
  21876. range.name = name;
  21877. range.from = this._ranges[name].from;
  21878. range.to = this._ranges[name].to;
  21879. serializationObject.ranges.push(range);
  21880. }
  21881. return serializationObject;
  21882. };
  21883. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21884. get: function () {
  21885. return Animation._ANIMATIONTYPE_FLOAT;
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21891. get: function () {
  21892. return Animation._ANIMATIONTYPE_VECTOR3;
  21893. },
  21894. enumerable: true,
  21895. configurable: true
  21896. });
  21897. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21898. get: function () {
  21899. return Animation._ANIMATIONTYPE_VECTOR2;
  21900. },
  21901. enumerable: true,
  21902. configurable: true
  21903. });
  21904. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21905. get: function () {
  21906. return Animation._ANIMATIONTYPE_QUATERNION;
  21907. },
  21908. enumerable: true,
  21909. configurable: true
  21910. });
  21911. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21912. get: function () {
  21913. return Animation._ANIMATIONTYPE_MATRIX;
  21914. },
  21915. enumerable: true,
  21916. configurable: true
  21917. });
  21918. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21919. get: function () {
  21920. return Animation._ANIMATIONTYPE_COLOR3;
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21926. get: function () {
  21927. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21928. },
  21929. enumerable: true,
  21930. configurable: true
  21931. });
  21932. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21933. get: function () {
  21934. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21940. get: function () {
  21941. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Animation.Parse = function (parsedAnimation) {
  21947. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21948. var dataType = parsedAnimation.dataType;
  21949. var keys = [];
  21950. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21951. var key = parsedAnimation.keys[index];
  21952. var data;
  21953. switch (dataType) {
  21954. case Animation.ANIMATIONTYPE_FLOAT:
  21955. data = key.values[0];
  21956. break;
  21957. case Animation.ANIMATIONTYPE_QUATERNION:
  21958. data = BABYLON.Quaternion.FromArray(key.values);
  21959. break;
  21960. case Animation.ANIMATIONTYPE_MATRIX:
  21961. data = BABYLON.Matrix.FromArray(key.values);
  21962. break;
  21963. case Animation.ANIMATIONTYPE_COLOR3:
  21964. data = BABYLON.Color3.FromArray(key.values);
  21965. break;
  21966. case Animation.ANIMATIONTYPE_VECTOR3:
  21967. default:
  21968. data = BABYLON.Vector3.FromArray(key.values);
  21969. break;
  21970. }
  21971. keys.push({
  21972. frame: key.frame,
  21973. value: data
  21974. });
  21975. }
  21976. animation.setKeys(keys);
  21977. if (parsedAnimation.ranges) {
  21978. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  21979. data = parsedAnimation.ranges[index];
  21980. animation.createRange(data.name, data.from, data.to);
  21981. }
  21982. }
  21983. return animation;
  21984. };
  21985. Animation.AppendSerializedAnimations = function (source, destination) {
  21986. if (source.animations) {
  21987. destination.animations = [];
  21988. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21989. var animation = source.animations[animationIndex];
  21990. destination.animations.push(animation.serialize());
  21991. }
  21992. }
  21993. };
  21994. // Statics
  21995. Animation._ANIMATIONTYPE_FLOAT = 0;
  21996. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21997. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21998. Animation._ANIMATIONTYPE_MATRIX = 3;
  21999. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22000. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22001. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22002. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22003. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22004. return Animation;
  22005. })();
  22006. BABYLON.Animation = Animation;
  22007. })(BABYLON || (BABYLON = {}));
  22008. var BABYLON;
  22009. (function (BABYLON) {
  22010. var Animatable = (function () {
  22011. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22012. if (fromFrame === void 0) { fromFrame = 0; }
  22013. if (toFrame === void 0) { toFrame = 100; }
  22014. if (loopAnimation === void 0) { loopAnimation = false; }
  22015. if (speedRatio === void 0) { speedRatio = 1.0; }
  22016. this.target = target;
  22017. this.fromFrame = fromFrame;
  22018. this.toFrame = toFrame;
  22019. this.loopAnimation = loopAnimation;
  22020. this.speedRatio = speedRatio;
  22021. this.onAnimationEnd = onAnimationEnd;
  22022. this._animations = new Array();
  22023. this._paused = false;
  22024. this.animationStarted = false;
  22025. if (animations) {
  22026. this.appendAnimations(target, animations);
  22027. }
  22028. this._scene = scene;
  22029. scene._activeAnimatables.push(this);
  22030. }
  22031. // Methods
  22032. Animatable.prototype.getAnimations = function () {
  22033. return this._animations;
  22034. };
  22035. Animatable.prototype.appendAnimations = function (target, animations) {
  22036. for (var index = 0; index < animations.length; index++) {
  22037. var animation = animations[index];
  22038. animation._target = target;
  22039. this._animations.push(animation);
  22040. }
  22041. };
  22042. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22043. var animations = this._animations;
  22044. for (var index = 0; index < animations.length; index++) {
  22045. if (animations[index].targetProperty === property) {
  22046. return animations[index];
  22047. }
  22048. }
  22049. return null;
  22050. };
  22051. Animatable.prototype.reset = function () {
  22052. var animations = this._animations;
  22053. for (var index = 0; index < animations.length; index++) {
  22054. animations[index].reset();
  22055. }
  22056. this._localDelayOffset = null;
  22057. this._pausedDelay = null;
  22058. };
  22059. Animatable.prototype.goToFrame = function (frame) {
  22060. var animations = this._animations;
  22061. for (var index = 0; index < animations.length; index++) {
  22062. animations[index].goToFrame(frame);
  22063. }
  22064. };
  22065. Animatable.prototype.pause = function () {
  22066. if (this._paused) {
  22067. return;
  22068. }
  22069. this._paused = true;
  22070. };
  22071. Animatable.prototype.restart = function () {
  22072. this._paused = false;
  22073. };
  22074. Animatable.prototype.stop = function () {
  22075. var index = this._scene._activeAnimatables.indexOf(this);
  22076. if (index > -1) {
  22077. this._scene._activeAnimatables.splice(index, 1);
  22078. }
  22079. if (this.onAnimationEnd) {
  22080. this.onAnimationEnd();
  22081. }
  22082. };
  22083. Animatable.prototype._animate = function (delay) {
  22084. if (this._paused) {
  22085. this.animationStarted = false;
  22086. if (!this._pausedDelay) {
  22087. this._pausedDelay = delay;
  22088. }
  22089. return true;
  22090. }
  22091. if (!this._localDelayOffset) {
  22092. this._localDelayOffset = delay;
  22093. }
  22094. else if (this._pausedDelay) {
  22095. this._localDelayOffset += delay - this._pausedDelay;
  22096. this._pausedDelay = null;
  22097. }
  22098. // Animating
  22099. var running = false;
  22100. var animations = this._animations;
  22101. var index;
  22102. for (index = 0; index < animations.length; index++) {
  22103. var animation = animations[index];
  22104. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22105. running = running || isRunning;
  22106. }
  22107. this.animationStarted = running;
  22108. if (!running) {
  22109. // Remove from active animatables
  22110. index = this._scene._activeAnimatables.indexOf(this);
  22111. this._scene._activeAnimatables.splice(index, 1);
  22112. }
  22113. if (!running && this.onAnimationEnd) {
  22114. this.onAnimationEnd();
  22115. }
  22116. return running;
  22117. };
  22118. return Animatable;
  22119. })();
  22120. BABYLON.Animatable = Animatable;
  22121. })(BABYLON || (BABYLON = {}));
  22122. var BABYLON;
  22123. (function (BABYLON) {
  22124. var EasingFunction = (function () {
  22125. function EasingFunction() {
  22126. // Properties
  22127. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22128. }
  22129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22130. get: function () {
  22131. return EasingFunction._EASINGMODE_EASEIN;
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22137. get: function () {
  22138. return EasingFunction._EASINGMODE_EASEOUT;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22144. get: function () {
  22145. return EasingFunction._EASINGMODE_EASEINOUT;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22151. var n = Math.min(Math.max(easingMode, 0), 2);
  22152. this._easingMode = n;
  22153. };
  22154. EasingFunction.prototype.getEasingMode = function () {
  22155. return this._easingMode;
  22156. };
  22157. EasingFunction.prototype.easeInCore = function (gradient) {
  22158. throw new Error('You must implement this method');
  22159. };
  22160. EasingFunction.prototype.ease = function (gradient) {
  22161. switch (this._easingMode) {
  22162. case EasingFunction.EASINGMODE_EASEIN:
  22163. return this.easeInCore(gradient);
  22164. case EasingFunction.EASINGMODE_EASEOUT:
  22165. return (1 - this.easeInCore(1 - gradient));
  22166. }
  22167. if (gradient >= 0.5) {
  22168. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22169. }
  22170. return (this.easeInCore(gradient * 2) * 0.5);
  22171. };
  22172. //Statics
  22173. EasingFunction._EASINGMODE_EASEIN = 0;
  22174. EasingFunction._EASINGMODE_EASEOUT = 1;
  22175. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22176. return EasingFunction;
  22177. })();
  22178. BABYLON.EasingFunction = EasingFunction;
  22179. var CircleEase = (function (_super) {
  22180. __extends(CircleEase, _super);
  22181. function CircleEase() {
  22182. _super.apply(this, arguments);
  22183. }
  22184. CircleEase.prototype.easeInCore = function (gradient) {
  22185. gradient = Math.max(0, Math.min(1, gradient));
  22186. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22187. };
  22188. return CircleEase;
  22189. })(EasingFunction);
  22190. BABYLON.CircleEase = CircleEase;
  22191. var BackEase = (function (_super) {
  22192. __extends(BackEase, _super);
  22193. function BackEase(amplitude) {
  22194. if (amplitude === void 0) { amplitude = 1; }
  22195. _super.call(this);
  22196. this.amplitude = amplitude;
  22197. }
  22198. BackEase.prototype.easeInCore = function (gradient) {
  22199. var num = Math.max(0, this.amplitude);
  22200. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22201. };
  22202. return BackEase;
  22203. })(EasingFunction);
  22204. BABYLON.BackEase = BackEase;
  22205. var BounceEase = (function (_super) {
  22206. __extends(BounceEase, _super);
  22207. function BounceEase(bounces, bounciness) {
  22208. if (bounces === void 0) { bounces = 3; }
  22209. if (bounciness === void 0) { bounciness = 2; }
  22210. _super.call(this);
  22211. this.bounces = bounces;
  22212. this.bounciness = bounciness;
  22213. }
  22214. BounceEase.prototype.easeInCore = function (gradient) {
  22215. var y = Math.max(0.0, this.bounces);
  22216. var bounciness = this.bounciness;
  22217. if (bounciness <= 1.0) {
  22218. bounciness = 1.001;
  22219. }
  22220. var num9 = Math.pow(bounciness, y);
  22221. var num5 = 1.0 - bounciness;
  22222. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22223. var num15 = gradient * num4;
  22224. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22225. var num3 = Math.floor(num65);
  22226. var num13 = num3 + 1.0;
  22227. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22228. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22229. var num7 = (num8 + num12) * 0.5;
  22230. var num6 = gradient - num7;
  22231. var num2 = num7 - num8;
  22232. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22233. };
  22234. return BounceEase;
  22235. })(EasingFunction);
  22236. BABYLON.BounceEase = BounceEase;
  22237. var CubicEase = (function (_super) {
  22238. __extends(CubicEase, _super);
  22239. function CubicEase() {
  22240. _super.apply(this, arguments);
  22241. }
  22242. CubicEase.prototype.easeInCore = function (gradient) {
  22243. return (gradient * gradient * gradient);
  22244. };
  22245. return CubicEase;
  22246. })(EasingFunction);
  22247. BABYLON.CubicEase = CubicEase;
  22248. var ElasticEase = (function (_super) {
  22249. __extends(ElasticEase, _super);
  22250. function ElasticEase(oscillations, springiness) {
  22251. if (oscillations === void 0) { oscillations = 3; }
  22252. if (springiness === void 0) { springiness = 3; }
  22253. _super.call(this);
  22254. this.oscillations = oscillations;
  22255. this.springiness = springiness;
  22256. }
  22257. ElasticEase.prototype.easeInCore = function (gradient) {
  22258. var num2;
  22259. var num3 = Math.max(0.0, this.oscillations);
  22260. var num = Math.max(0.0, this.springiness);
  22261. if (num == 0) {
  22262. num2 = gradient;
  22263. }
  22264. else {
  22265. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22266. }
  22267. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22268. };
  22269. return ElasticEase;
  22270. })(EasingFunction);
  22271. BABYLON.ElasticEase = ElasticEase;
  22272. var ExponentialEase = (function (_super) {
  22273. __extends(ExponentialEase, _super);
  22274. function ExponentialEase(exponent) {
  22275. if (exponent === void 0) { exponent = 2; }
  22276. _super.call(this);
  22277. this.exponent = exponent;
  22278. }
  22279. ExponentialEase.prototype.easeInCore = function (gradient) {
  22280. if (this.exponent <= 0) {
  22281. return gradient;
  22282. }
  22283. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22284. };
  22285. return ExponentialEase;
  22286. })(EasingFunction);
  22287. BABYLON.ExponentialEase = ExponentialEase;
  22288. var PowerEase = (function (_super) {
  22289. __extends(PowerEase, _super);
  22290. function PowerEase(power) {
  22291. if (power === void 0) { power = 2; }
  22292. _super.call(this);
  22293. this.power = power;
  22294. }
  22295. PowerEase.prototype.easeInCore = function (gradient) {
  22296. var y = Math.max(0.0, this.power);
  22297. return Math.pow(gradient, y);
  22298. };
  22299. return PowerEase;
  22300. })(EasingFunction);
  22301. BABYLON.PowerEase = PowerEase;
  22302. var QuadraticEase = (function (_super) {
  22303. __extends(QuadraticEase, _super);
  22304. function QuadraticEase() {
  22305. _super.apply(this, arguments);
  22306. }
  22307. QuadraticEase.prototype.easeInCore = function (gradient) {
  22308. return (gradient * gradient);
  22309. };
  22310. return QuadraticEase;
  22311. })(EasingFunction);
  22312. BABYLON.QuadraticEase = QuadraticEase;
  22313. var QuarticEase = (function (_super) {
  22314. __extends(QuarticEase, _super);
  22315. function QuarticEase() {
  22316. _super.apply(this, arguments);
  22317. }
  22318. QuarticEase.prototype.easeInCore = function (gradient) {
  22319. return (gradient * gradient * gradient * gradient);
  22320. };
  22321. return QuarticEase;
  22322. })(EasingFunction);
  22323. BABYLON.QuarticEase = QuarticEase;
  22324. var QuinticEase = (function (_super) {
  22325. __extends(QuinticEase, _super);
  22326. function QuinticEase() {
  22327. _super.apply(this, arguments);
  22328. }
  22329. QuinticEase.prototype.easeInCore = function (gradient) {
  22330. return (gradient * gradient * gradient * gradient * gradient);
  22331. };
  22332. return QuinticEase;
  22333. })(EasingFunction);
  22334. BABYLON.QuinticEase = QuinticEase;
  22335. var SineEase = (function (_super) {
  22336. __extends(SineEase, _super);
  22337. function SineEase() {
  22338. _super.apply(this, arguments);
  22339. }
  22340. SineEase.prototype.easeInCore = function (gradient) {
  22341. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22342. };
  22343. return SineEase;
  22344. })(EasingFunction);
  22345. BABYLON.SineEase = SineEase;
  22346. var BezierCurveEase = (function (_super) {
  22347. __extends(BezierCurveEase, _super);
  22348. function BezierCurveEase(x1, y1, x2, y2) {
  22349. if (x1 === void 0) { x1 = 0; }
  22350. if (y1 === void 0) { y1 = 0; }
  22351. if (x2 === void 0) { x2 = 1; }
  22352. if (y2 === void 0) { y2 = 1; }
  22353. _super.call(this);
  22354. this.x1 = x1;
  22355. this.y1 = y1;
  22356. this.x2 = x2;
  22357. this.y2 = y2;
  22358. }
  22359. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22360. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22361. };
  22362. return BezierCurveEase;
  22363. })(EasingFunction);
  22364. BABYLON.BezierCurveEase = BezierCurveEase;
  22365. })(BABYLON || (BABYLON = {}));
  22366. var BABYLON;
  22367. (function (BABYLON) {
  22368. var Bone = (function (_super) {
  22369. __extends(Bone, _super);
  22370. function Bone(name, skeleton, parentBone, matrix) {
  22371. _super.call(this, name, skeleton.getScene());
  22372. this.name = name;
  22373. this.children = new Array();
  22374. this.animations = new Array();
  22375. this._worldTransform = new BABYLON.Matrix();
  22376. this._absoluteTransform = new BABYLON.Matrix();
  22377. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22378. this._skeleton = skeleton;
  22379. this._matrix = matrix;
  22380. this._baseMatrix = matrix;
  22381. skeleton.bones.push(this);
  22382. if (parentBone) {
  22383. this._parent = parentBone;
  22384. parentBone.children.push(this);
  22385. }
  22386. else {
  22387. this._parent = null;
  22388. }
  22389. this._updateDifferenceMatrix();
  22390. }
  22391. // Members
  22392. Bone.prototype.getParent = function () {
  22393. return this._parent;
  22394. };
  22395. Bone.prototype.getLocalMatrix = function () {
  22396. return this._matrix;
  22397. };
  22398. Bone.prototype.getBaseMatrix = function () {
  22399. return this._baseMatrix;
  22400. };
  22401. Bone.prototype.getWorldMatrix = function () {
  22402. return this._worldTransform;
  22403. };
  22404. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22405. return this._invertedAbsoluteTransform;
  22406. };
  22407. Bone.prototype.getAbsoluteMatrix = function () {
  22408. var matrix = this._matrix.clone();
  22409. var parent = this._parent;
  22410. while (parent) {
  22411. matrix = matrix.multiply(parent.getLocalMatrix());
  22412. parent = parent.getParent();
  22413. }
  22414. return matrix;
  22415. };
  22416. // Methods
  22417. Bone.prototype.updateMatrix = function (matrix) {
  22418. this._matrix = matrix;
  22419. this._skeleton._markAsDirty();
  22420. this._updateDifferenceMatrix();
  22421. };
  22422. Bone.prototype._updateDifferenceMatrix = function () {
  22423. if (this._parent) {
  22424. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22425. }
  22426. else {
  22427. this._absoluteTransform.copyFrom(this._matrix);
  22428. }
  22429. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22430. for (var index = 0; index < this.children.length; index++) {
  22431. this.children[index]._updateDifferenceMatrix();
  22432. }
  22433. };
  22434. Bone.prototype.markAsDirty = function () {
  22435. this._currentRenderId++;
  22436. this._skeleton._markAsDirty();
  22437. };
  22438. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22439. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22440. // all animation may be coming from a library skeleton, so may need to create animation
  22441. if (this.animations.length === 0) {
  22442. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22443. }
  22444. // get animation info / verify there is such a range from the source bone
  22445. var sourceRange = source.animations[0].getRange(rangeName);
  22446. if (!sourceRange) {
  22447. return false;
  22448. }
  22449. var from = sourceRange.from;
  22450. var to = sourceRange.to;
  22451. var sourceKeys = source.animations[0].getKeys();
  22452. // rescaling prep
  22453. var sourceBoneLength = source.length;
  22454. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22455. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22456. var destKeys = this.animations[0].getKeys();
  22457. // loop vars declaration / initialization
  22458. var orig;
  22459. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22460. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22461. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22462. var mat;
  22463. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22464. orig = sourceKeys[key];
  22465. if (orig.frame >= from && orig.frame <= to) {
  22466. if (scalingReqd) {
  22467. orig.value.decompose(origScale, origRotation, origTranslation);
  22468. origTranslation.scaleInPlace(ratio);
  22469. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22470. }
  22471. else {
  22472. mat = orig.value;
  22473. }
  22474. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22475. }
  22476. }
  22477. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22478. return true;
  22479. };
  22480. return Bone;
  22481. })(BABYLON.Node);
  22482. BABYLON.Bone = Bone;
  22483. })(BABYLON || (BABYLON = {}));
  22484. var BABYLON;
  22485. (function (BABYLON) {
  22486. var Skeleton = (function () {
  22487. function Skeleton(name, id, scene) {
  22488. this.name = name;
  22489. this.id = id;
  22490. this.bones = new Array();
  22491. this._isDirty = true;
  22492. this._identity = BABYLON.Matrix.Identity();
  22493. this._ranges = {};
  22494. this.bones = [];
  22495. this._scene = scene;
  22496. scene.skeletons.push(this);
  22497. this.prepare();
  22498. //make sure it will recalculate the matrix next time prepare is called.
  22499. this._isDirty = true;
  22500. }
  22501. // Members
  22502. Skeleton.prototype.getTransformMatrices = function () {
  22503. return this._transformMatrices;
  22504. };
  22505. Skeleton.prototype.getScene = function () {
  22506. return this._scene;
  22507. };
  22508. // Methods
  22509. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22510. // check name not already in use
  22511. if (!this._ranges[name]) {
  22512. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22513. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22514. if (this.bones[i].animations[0]) {
  22515. this.bones[i].animations[0].createRange(name, from, to);
  22516. }
  22517. }
  22518. }
  22519. };
  22520. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22521. if (deleteFrames === void 0) { deleteFrames = true; }
  22522. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22523. if (this.bones[i].animations[0]) {
  22524. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22525. }
  22526. }
  22527. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22528. };
  22529. Skeleton.prototype.getAnimationRange = function (name) {
  22530. return this._ranges[name];
  22531. };
  22532. /**
  22533. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22534. */
  22535. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22536. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22537. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22538. return false;
  22539. }
  22540. var ret = true;
  22541. var frameOffset = this._getHighestAnimationFrame() + 1;
  22542. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22543. var boneDict = {};
  22544. var sourceBones = source.bones;
  22545. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22546. boneDict[sourceBones[i].name] = sourceBones[i];
  22547. }
  22548. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22549. var boneName = this.bones[i].name;
  22550. var sourceBone = boneDict[boneName];
  22551. if (sourceBone) {
  22552. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22553. }
  22554. else {
  22555. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22556. ret = false;
  22557. }
  22558. }
  22559. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22560. var range = source.getAnimationRange(name);
  22561. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22562. return ret;
  22563. };
  22564. Skeleton.prototype._getHighestAnimationFrame = function () {
  22565. var ret = 0;
  22566. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22567. if (this.bones[i].animations[0]) {
  22568. var highest = this.bones[i].animations[0].getHighestFrame();
  22569. if (ret < highest) {
  22570. ret = highest;
  22571. }
  22572. }
  22573. }
  22574. return ret;
  22575. };
  22576. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22577. var range = this.getAnimationRange(name);
  22578. if (!range) {
  22579. return null;
  22580. }
  22581. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22582. };
  22583. Skeleton.prototype._markAsDirty = function () {
  22584. this._isDirty = true;
  22585. };
  22586. Skeleton.prototype.prepare = function () {
  22587. if (!this._isDirty) {
  22588. return;
  22589. }
  22590. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22591. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22592. }
  22593. for (var index = 0; index < this.bones.length; index++) {
  22594. var bone = this.bones[index];
  22595. var parentBone = bone.getParent();
  22596. if (parentBone) {
  22597. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22598. }
  22599. else {
  22600. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22601. }
  22602. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22603. }
  22604. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22605. this._isDirty = false;
  22606. this._scene._activeBones += this.bones.length;
  22607. };
  22608. Skeleton.prototype.getAnimatables = function () {
  22609. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22610. this._animatables = [];
  22611. for (var index = 0; index < this.bones.length; index++) {
  22612. this._animatables.push(this.bones[index]);
  22613. }
  22614. }
  22615. return this._animatables;
  22616. };
  22617. Skeleton.prototype.clone = function (name, id) {
  22618. var result = new Skeleton(name, id || name, this._scene);
  22619. for (var index = 0; index < this.bones.length; index++) {
  22620. var source = this.bones[index];
  22621. var parentBone = null;
  22622. if (source.getParent()) {
  22623. var parentIndex = this.bones.indexOf(source.getParent());
  22624. parentBone = result.bones[parentIndex];
  22625. }
  22626. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone());
  22627. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22628. }
  22629. return result;
  22630. };
  22631. Skeleton.prototype.dispose = function () {
  22632. // Animations
  22633. this.getScene().stopAnimation(this);
  22634. // Remove from scene
  22635. this.getScene().removeSkeleton(this);
  22636. };
  22637. Skeleton.prototype.serialize = function () {
  22638. var serializationObject = {};
  22639. serializationObject.name = this.name;
  22640. serializationObject.id = this.id;
  22641. serializationObject.bones = [];
  22642. for (var index = 0; index < this.bones.length; index++) {
  22643. var bone = this.bones[index];
  22644. var serializedBone = {
  22645. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22646. name: bone.name,
  22647. matrix: bone.getLocalMatrix().toArray()
  22648. };
  22649. serializationObject.bones.push(serializedBone);
  22650. if (bone.length) {
  22651. serializedBone.length = bone.length;
  22652. }
  22653. if (bone.animations && bone.animations.length > 0) {
  22654. serializedBone.animation = bone.animations[0].serialize();
  22655. }
  22656. serializationObject.ranges = [];
  22657. for (var name in this._ranges) {
  22658. var range = {};
  22659. range.name = name;
  22660. range.from = this._ranges[name].from;
  22661. range.to = this._ranges[name].to;
  22662. serializationObject.ranges.push(range);
  22663. }
  22664. }
  22665. return serializationObject;
  22666. };
  22667. Skeleton.Parse = function (parsedSkeleton, scene) {
  22668. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22669. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22670. var parsedBone = parsedSkeleton.bones[index];
  22671. var parentBone = null;
  22672. if (parsedBone.parentBoneIndex > -1) {
  22673. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22674. }
  22675. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22676. if (parsedBone.length) {
  22677. bone.length = parsedBone.length;
  22678. }
  22679. if (parsedBone.animation) {
  22680. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22681. }
  22682. }
  22683. // placed after bones, so createAnimationRange can cascade down
  22684. if (parsedSkeleton.ranges) {
  22685. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  22686. var data = parsedSkeleton.ranges[index];
  22687. skeleton.createAnimationRange(data.name, data.from, data.to);
  22688. }
  22689. }
  22690. return skeleton;
  22691. };
  22692. return Skeleton;
  22693. })();
  22694. BABYLON.Skeleton = Skeleton;
  22695. })(BABYLON || (BABYLON = {}));
  22696. var BABYLON;
  22697. (function (BABYLON) {
  22698. var PostProcess = (function () {
  22699. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22701. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22702. this.name = name;
  22703. this.width = -1;
  22704. this.height = -1;
  22705. this._reusable = false;
  22706. this._textures = new BABYLON.SmartArray(2);
  22707. this._currentRenderTextureInd = 0;
  22708. if (camera != null) {
  22709. this._camera = camera;
  22710. this._scene = camera.getScene();
  22711. camera.attachPostProcess(this);
  22712. this._engine = this._scene.getEngine();
  22713. }
  22714. else {
  22715. this._engine = engine;
  22716. }
  22717. this._renderRatio = ratio;
  22718. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22719. this._reusable = reusable || false;
  22720. this._textureType = textureType;
  22721. this._samplers = samplers || [];
  22722. this._samplers.push("textureSampler");
  22723. this._fragmentUrl = fragmentUrl;
  22724. this._parameters = parameters || [];
  22725. this.updateEffect(defines);
  22726. }
  22727. PostProcess.prototype.updateEffect = function (defines) {
  22728. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22729. };
  22730. PostProcess.prototype.isReusable = function () {
  22731. return this._reusable;
  22732. };
  22733. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22734. camera = camera || this._camera;
  22735. var scene = camera.getScene();
  22736. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22737. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22738. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22739. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22740. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22741. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22742. if (this._textures.length > 0) {
  22743. for (var i = 0; i < this._textures.length; i++) {
  22744. this._engine._releaseTexture(this._textures.data[i]);
  22745. }
  22746. this._textures.reset();
  22747. }
  22748. this.width = desiredWidth;
  22749. this.height = desiredHeight;
  22750. 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 }));
  22751. if (this._reusable) {
  22752. 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 }));
  22753. }
  22754. if (this.onSizeChanged) {
  22755. this.onSizeChanged();
  22756. }
  22757. }
  22758. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22759. if (this.onActivate) {
  22760. this.onActivate(camera);
  22761. }
  22762. // Clear
  22763. if (this.clearColor) {
  22764. this._engine.clear(this.clearColor, true, true);
  22765. }
  22766. else {
  22767. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22768. }
  22769. if (this._reusable) {
  22770. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22771. }
  22772. };
  22773. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22774. get: function () {
  22775. return this._effect.isSupported;
  22776. },
  22777. enumerable: true,
  22778. configurable: true
  22779. });
  22780. PostProcess.prototype.apply = function () {
  22781. // Check
  22782. if (!this._effect.isReady())
  22783. return null;
  22784. // States
  22785. this._engine.enableEffect(this._effect);
  22786. this._engine.setState(false);
  22787. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22788. this._engine.setDepthBuffer(false);
  22789. this._engine.setDepthWrite(false);
  22790. // Texture
  22791. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22792. // Parameters
  22793. if (this.onApply) {
  22794. this.onApply(this._effect);
  22795. }
  22796. return this._effect;
  22797. };
  22798. PostProcess.prototype.dispose = function (camera) {
  22799. camera = camera || this._camera;
  22800. if (this._textures.length > 0) {
  22801. for (var i = 0; i < this._textures.length; i++) {
  22802. this._engine._releaseTexture(this._textures.data[i]);
  22803. }
  22804. this._textures.reset();
  22805. }
  22806. if (!camera) {
  22807. return;
  22808. }
  22809. camera.detachPostProcess(this);
  22810. var index = camera._postProcesses.indexOf(this);
  22811. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22812. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22813. }
  22814. };
  22815. return PostProcess;
  22816. })();
  22817. BABYLON.PostProcess = PostProcess;
  22818. })(BABYLON || (BABYLON = {}));
  22819. var BABYLON;
  22820. (function (BABYLON) {
  22821. var PostProcessManager = (function () {
  22822. function PostProcessManager(scene) {
  22823. this._vertexDeclaration = [2];
  22824. this._vertexStrideSize = 2 * 4;
  22825. this._scene = scene;
  22826. }
  22827. PostProcessManager.prototype._prepareBuffers = function () {
  22828. if (this._vertexBuffer) {
  22829. return;
  22830. }
  22831. // VBO
  22832. var vertices = [];
  22833. vertices.push(1, 1);
  22834. vertices.push(-1, 1);
  22835. vertices.push(-1, -1);
  22836. vertices.push(1, -1);
  22837. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22838. // Indices
  22839. var indices = [];
  22840. indices.push(0);
  22841. indices.push(1);
  22842. indices.push(2);
  22843. indices.push(0);
  22844. indices.push(2);
  22845. indices.push(3);
  22846. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22847. };
  22848. // Methods
  22849. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22850. var postProcesses = this._scene.activeCamera._postProcesses;
  22851. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22852. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22853. return false;
  22854. }
  22855. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22856. return true;
  22857. };
  22858. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22859. var engine = this._scene.getEngine();
  22860. for (var index = 0; index < postProcesses.length; index++) {
  22861. if (index < postProcesses.length - 1) {
  22862. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22863. }
  22864. else {
  22865. if (targetTexture) {
  22866. engine.bindFramebuffer(targetTexture);
  22867. }
  22868. else {
  22869. engine.restoreDefaultFramebuffer();
  22870. }
  22871. }
  22872. var pp = postProcesses[index];
  22873. var effect = pp.apply();
  22874. if (effect) {
  22875. if (pp.onBeforeRender) {
  22876. pp.onBeforeRender(effect);
  22877. }
  22878. // VBOs
  22879. this._prepareBuffers();
  22880. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22881. // Draw order
  22882. engine.draw(true, 0, 6);
  22883. if (pp.onAfterRender) {
  22884. pp.onAfterRender(effect);
  22885. }
  22886. }
  22887. }
  22888. // Restore depth buffer
  22889. engine.setDepthBuffer(true);
  22890. engine.setDepthWrite(true);
  22891. };
  22892. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22893. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22894. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22895. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22896. return;
  22897. }
  22898. var engine = this._scene.getEngine();
  22899. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22900. if (index < postProcessesTakenIndices.length - 1) {
  22901. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  22902. }
  22903. else {
  22904. if (targetTexture) {
  22905. engine.bindFramebuffer(targetTexture, faceIndex);
  22906. }
  22907. else {
  22908. engine.restoreDefaultFramebuffer();
  22909. }
  22910. }
  22911. if (doNotPresent) {
  22912. break;
  22913. }
  22914. var pp = postProcesses[postProcessesTakenIndices[index]];
  22915. var effect = pp.apply();
  22916. if (effect) {
  22917. if (pp.onBeforeRender) {
  22918. pp.onBeforeRender(effect);
  22919. }
  22920. // VBOs
  22921. this._prepareBuffers();
  22922. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22923. // Draw order
  22924. engine.draw(true, 0, 6);
  22925. if (pp.onAfterRender) {
  22926. pp.onAfterRender(effect);
  22927. }
  22928. }
  22929. }
  22930. // Restore depth buffer
  22931. engine.setDepthBuffer(true);
  22932. engine.setDepthWrite(true);
  22933. };
  22934. PostProcessManager.prototype.dispose = function () {
  22935. if (this._vertexBuffer) {
  22936. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22937. this._vertexBuffer = null;
  22938. }
  22939. if (this._indexBuffer) {
  22940. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22941. this._indexBuffer = null;
  22942. }
  22943. };
  22944. return PostProcessManager;
  22945. })();
  22946. BABYLON.PostProcessManager = PostProcessManager;
  22947. })(BABYLON || (BABYLON = {}));
  22948. var BABYLON;
  22949. (function (BABYLON) {
  22950. var PassPostProcess = (function (_super) {
  22951. __extends(PassPostProcess, _super);
  22952. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22953. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22954. }
  22955. return PassPostProcess;
  22956. })(BABYLON.PostProcess);
  22957. BABYLON.PassPostProcess = PassPostProcess;
  22958. })(BABYLON || (BABYLON = {}));
  22959. var BABYLON;
  22960. (function (BABYLON) {
  22961. var PhysicsEngine = (function () {
  22962. function PhysicsEngine(plugin) {
  22963. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22964. }
  22965. PhysicsEngine.prototype._initialize = function (gravity) {
  22966. this._currentPlugin.initialize();
  22967. this._setGravity(gravity);
  22968. };
  22969. PhysicsEngine.prototype._runOneStep = function (delta) {
  22970. if (delta > 0.1) {
  22971. delta = 0.1;
  22972. }
  22973. else if (delta <= 0) {
  22974. delta = 1.0 / 60.0;
  22975. }
  22976. this._currentPlugin.runOneStep(delta);
  22977. };
  22978. PhysicsEngine.prototype._setGravity = function (gravity) {
  22979. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22980. this._currentPlugin.setGravity(this.gravity);
  22981. };
  22982. PhysicsEngine.prototype._getGravity = function () {
  22983. return this._currentPlugin.getGravity();
  22984. };
  22985. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22986. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22987. };
  22988. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22989. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22990. };
  22991. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22992. this._currentPlugin.unregisterMesh(mesh);
  22993. };
  22994. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22995. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22996. };
  22997. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22998. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22999. };
  23000. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23001. this._currentPlugin.updateBodyPosition(mesh);
  23002. };
  23003. PhysicsEngine.prototype.dispose = function () {
  23004. this._currentPlugin.dispose();
  23005. };
  23006. PhysicsEngine.prototype.isSupported = function () {
  23007. return this._currentPlugin.isSupported();
  23008. };
  23009. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23010. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23011. };
  23012. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23013. return this._currentPlugin.name;
  23014. };
  23015. // Statics
  23016. PhysicsEngine.NoImpostor = 0;
  23017. PhysicsEngine.SphereImpostor = 1;
  23018. PhysicsEngine.BoxImpostor = 2;
  23019. PhysicsEngine.PlaneImpostor = 3;
  23020. PhysicsEngine.MeshImpostor = 4;
  23021. PhysicsEngine.CapsuleImpostor = 5;
  23022. PhysicsEngine.ConeImpostor = 6;
  23023. PhysicsEngine.CylinderImpostor = 7;
  23024. PhysicsEngine.ConvexHullImpostor = 8;
  23025. PhysicsEngine.HeightmapImpostor = 9;
  23026. PhysicsEngine.Epsilon = 0.001;
  23027. return PhysicsEngine;
  23028. })();
  23029. BABYLON.PhysicsEngine = PhysicsEngine;
  23030. })(BABYLON || (BABYLON = {}));
  23031. var BABYLON;
  23032. (function (BABYLON) {
  23033. var VertexData = (function () {
  23034. function VertexData() {
  23035. }
  23036. VertexData.prototype.set = function (data, kind) {
  23037. switch (kind) {
  23038. case BABYLON.VertexBuffer.PositionKind:
  23039. this.positions = data;
  23040. break;
  23041. case BABYLON.VertexBuffer.NormalKind:
  23042. this.normals = data;
  23043. break;
  23044. case BABYLON.VertexBuffer.UVKind:
  23045. this.uvs = data;
  23046. break;
  23047. case BABYLON.VertexBuffer.UV2Kind:
  23048. this.uvs2 = data;
  23049. break;
  23050. case BABYLON.VertexBuffer.UV3Kind:
  23051. this.uvs3 = data;
  23052. break;
  23053. case BABYLON.VertexBuffer.UV4Kind:
  23054. this.uvs4 = data;
  23055. break;
  23056. case BABYLON.VertexBuffer.UV5Kind:
  23057. this.uvs5 = data;
  23058. break;
  23059. case BABYLON.VertexBuffer.UV6Kind:
  23060. this.uvs6 = data;
  23061. break;
  23062. case BABYLON.VertexBuffer.ColorKind:
  23063. this.colors = data;
  23064. break;
  23065. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23066. this.matricesIndices = data;
  23067. break;
  23068. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23069. this.matricesWeights = data;
  23070. break;
  23071. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23072. this.matricesIndicesExtra = data;
  23073. break;
  23074. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23075. this.matricesWeightsExtra = data;
  23076. break;
  23077. }
  23078. };
  23079. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23080. this._applyTo(mesh, updatable);
  23081. };
  23082. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23083. this._applyTo(geometry, updatable);
  23084. };
  23085. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23086. this._update(mesh);
  23087. };
  23088. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23089. this._update(geometry);
  23090. };
  23091. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23092. if (this.positions) {
  23093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23094. }
  23095. if (this.normals) {
  23096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23097. }
  23098. if (this.uvs) {
  23099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23100. }
  23101. if (this.uvs2) {
  23102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23103. }
  23104. if (this.uvs3) {
  23105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23106. }
  23107. if (this.uvs4) {
  23108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23109. }
  23110. if (this.uvs5) {
  23111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23112. }
  23113. if (this.uvs6) {
  23114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23115. }
  23116. if (this.colors) {
  23117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23118. }
  23119. if (this.matricesIndices) {
  23120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23121. }
  23122. if (this.matricesWeights) {
  23123. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23124. }
  23125. if (this.matricesIndicesExtra) {
  23126. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23127. }
  23128. if (this.matricesWeightsExtra) {
  23129. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23130. }
  23131. if (this.indices) {
  23132. meshOrGeometry.setIndices(this.indices);
  23133. }
  23134. };
  23135. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23136. if (this.positions) {
  23137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23138. }
  23139. if (this.normals) {
  23140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23141. }
  23142. if (this.uvs) {
  23143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23144. }
  23145. if (this.uvs2) {
  23146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23147. }
  23148. if (this.uvs3) {
  23149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23150. }
  23151. if (this.uvs4) {
  23152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23153. }
  23154. if (this.uvs5) {
  23155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23156. }
  23157. if (this.uvs6) {
  23158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23159. }
  23160. if (this.colors) {
  23161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23162. }
  23163. if (this.matricesIndices) {
  23164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23165. }
  23166. if (this.matricesWeights) {
  23167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23168. }
  23169. if (this.matricesIndicesExtra) {
  23170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23171. }
  23172. if (this.matricesWeightsExtra) {
  23173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23174. }
  23175. if (this.indices) {
  23176. meshOrGeometry.setIndices(this.indices);
  23177. }
  23178. };
  23179. VertexData.prototype.transform = function (matrix) {
  23180. var transformed = BABYLON.Vector3.Zero();
  23181. var index;
  23182. if (this.positions) {
  23183. var position = BABYLON.Vector3.Zero();
  23184. for (index = 0; index < this.positions.length; index += 3) {
  23185. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23186. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23187. this.positions[index] = transformed.x;
  23188. this.positions[index + 1] = transformed.y;
  23189. this.positions[index + 2] = transformed.z;
  23190. }
  23191. }
  23192. if (this.normals) {
  23193. var normal = BABYLON.Vector3.Zero();
  23194. for (index = 0; index < this.normals.length; index += 3) {
  23195. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23196. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23197. this.normals[index] = transformed.x;
  23198. this.normals[index + 1] = transformed.y;
  23199. this.normals[index + 2] = transformed.z;
  23200. }
  23201. }
  23202. };
  23203. VertexData.prototype.merge = function (other) {
  23204. if (other.indices) {
  23205. if (!this.indices) {
  23206. this.indices = [];
  23207. }
  23208. var offset = this.positions ? this.positions.length / 3 : 0;
  23209. for (var index = 0; index < other.indices.length; index++) {
  23210. //TODO check type - if Int32Array!
  23211. this.indices.push(other.indices[index] + offset);
  23212. }
  23213. }
  23214. this.positions = this._mergeElement(this.positions, other.positions);
  23215. this.normals = this._mergeElement(this.normals, other.normals);
  23216. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23217. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23218. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23219. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23220. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23221. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23222. this.colors = this._mergeElement(this.colors, other.colors);
  23223. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23224. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23225. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23226. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23227. };
  23228. VertexData.prototype._mergeElement = function (source, other) {
  23229. if (!other)
  23230. return source;
  23231. if (!source)
  23232. return other;
  23233. var len = other.length + source.length;
  23234. var isSrcTypedArray = source instanceof Float32Array;
  23235. var isOthTypedArray = other instanceof Float32Array;
  23236. // use non-loop method when the source is Float32Array
  23237. if (isSrcTypedArray) {
  23238. var ret32 = new Float32Array(len);
  23239. ret32.set(source);
  23240. ret32.set(other, source.length);
  23241. return ret32;
  23242. }
  23243. else if (!isOthTypedArray) {
  23244. return source.concat(other);
  23245. }
  23246. else {
  23247. var ret = source.slice(0); // copy source to a separate array
  23248. for (var i = 0, len = other.length; i < len; i++) {
  23249. ret.push(other[i]);
  23250. }
  23251. return ret;
  23252. }
  23253. };
  23254. VertexData.prototype.serialize = function () {
  23255. var serializationObject = this.serialize();
  23256. if (this.positions) {
  23257. serializationObject.positions = this.positions;
  23258. }
  23259. if (this.normals) {
  23260. serializationObject.normals = this.normals;
  23261. }
  23262. if (this.uvs) {
  23263. serializationObject.uvs = this.uvs;
  23264. }
  23265. if (this.uvs2) {
  23266. serializationObject.uvs2 = this.uvs2;
  23267. }
  23268. if (this.uvs3) {
  23269. serializationObject.uvs3 = this.uvs3;
  23270. }
  23271. if (this.uvs4) {
  23272. serializationObject.uvs4 = this.uvs4;
  23273. }
  23274. if (this.uvs5) {
  23275. serializationObject.uvs5 = this.uvs5;
  23276. }
  23277. if (this.uvs6) {
  23278. serializationObject.uvs6 = this.uvs6;
  23279. }
  23280. if (this.colors) {
  23281. serializationObject.colors = this.colors;
  23282. }
  23283. if (this.matricesIndices) {
  23284. serializationObject.matricesIndices = this.matricesIndices;
  23285. serializationObject.matricesIndices._isExpanded = true;
  23286. }
  23287. if (this.matricesWeights) {
  23288. serializationObject.matricesWeights = this.matricesWeights;
  23289. }
  23290. if (this.matricesIndicesExtra) {
  23291. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23292. serializationObject.matricesIndicesExtra._isExpanded = true;
  23293. }
  23294. if (this.matricesWeightsExtra) {
  23295. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23296. }
  23297. serializationObject.indices = this.indices;
  23298. return serializationObject;
  23299. };
  23300. // Statics
  23301. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23302. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23303. };
  23304. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23305. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23306. };
  23307. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23308. var result = new VertexData();
  23309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23310. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23311. }
  23312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23313. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23314. }
  23315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23316. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23317. }
  23318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23319. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23320. }
  23321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23322. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23323. }
  23324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23325. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23326. }
  23327. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23328. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23329. }
  23330. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23331. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23332. }
  23333. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23334. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23335. }
  23336. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23337. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23338. }
  23339. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23340. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23341. }
  23342. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23343. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23344. }
  23345. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23346. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23347. }
  23348. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23349. return result;
  23350. };
  23351. VertexData.CreateRibbon = function (options) {
  23352. var pathArray = options.pathArray;
  23353. var closeArray = options.closeArray || false;
  23354. var closePath = options.closePath || false;
  23355. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23356. var offset = options.offset || defaultOffset;
  23357. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23358. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23359. var positions = [];
  23360. var indices = [];
  23361. var normals = [];
  23362. var uvs = [];
  23363. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23364. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23365. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23366. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23367. var minlg; // minimal length among all paths from pathArray
  23368. var lg = []; // array of path lengths : nb of vertex per path
  23369. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23370. var p; // path iterator
  23371. var i; // point iterator
  23372. var j; // point iterator
  23373. // if single path in pathArray
  23374. if (pathArray.length < 2) {
  23375. var ar1 = [];
  23376. var ar2 = [];
  23377. for (i = 0; i < pathArray[0].length - offset; i++) {
  23378. ar1.push(pathArray[0][i]);
  23379. ar2.push(pathArray[0][i + offset]);
  23380. }
  23381. pathArray = [ar1, ar2];
  23382. }
  23383. // positions and horizontal distances (u)
  23384. var idc = 0;
  23385. var closePathCorr = (closePath) ? 1 : 0;
  23386. var path;
  23387. var l;
  23388. minlg = pathArray[0].length;
  23389. var vectlg;
  23390. var dist;
  23391. for (p = 0; p < pathArray.length; p++) {
  23392. uTotalDistance[p] = 0;
  23393. us[p] = [0];
  23394. path = pathArray[p];
  23395. l = path.length;
  23396. minlg = (minlg < l) ? minlg : l;
  23397. j = 0;
  23398. while (j < l) {
  23399. positions.push(path[j].x, path[j].y, path[j].z);
  23400. if (j > 0) {
  23401. vectlg = path[j].subtract(path[j - 1]).length();
  23402. dist = vectlg + uTotalDistance[p];
  23403. us[p].push(dist);
  23404. uTotalDistance[p] = dist;
  23405. }
  23406. j++;
  23407. }
  23408. if (closePath) {
  23409. j--;
  23410. positions.push(path[0].x, path[0].y, path[0].z);
  23411. vectlg = path[j].subtract(path[0]).length();
  23412. dist = vectlg + uTotalDistance[p];
  23413. us[p].push(dist);
  23414. uTotalDistance[p] = dist;
  23415. }
  23416. lg[p] = l + closePathCorr;
  23417. idx[p] = idc;
  23418. idc += (l + closePathCorr);
  23419. }
  23420. // vertical distances (v)
  23421. var path1;
  23422. var path2;
  23423. var vertex1;
  23424. var vertex2;
  23425. for (i = 0; i < minlg + closePathCorr; i++) {
  23426. vTotalDistance[i] = 0;
  23427. vs[i] = [0];
  23428. for (p = 0; p < pathArray.length - 1; p++) {
  23429. path1 = pathArray[p];
  23430. path2 = pathArray[p + 1];
  23431. if (i === minlg) {
  23432. vertex1 = path1[0];
  23433. vertex2 = path2[0];
  23434. }
  23435. else {
  23436. vertex1 = path1[i];
  23437. vertex2 = path2[i];
  23438. }
  23439. vectlg = vertex2.subtract(vertex1).length();
  23440. dist = vectlg + vTotalDistance[i];
  23441. vs[i].push(dist);
  23442. vTotalDistance[i] = dist;
  23443. }
  23444. if (closeArray) {
  23445. path1 = pathArray[p];
  23446. path2 = pathArray[0];
  23447. if (i === minlg) {
  23448. vertex2 = path2[0];
  23449. }
  23450. vectlg = vertex2.subtract(vertex1).length();
  23451. dist = vectlg + vTotalDistance[i];
  23452. vTotalDistance[i] = dist;
  23453. }
  23454. }
  23455. // uvs
  23456. var u;
  23457. var v;
  23458. for (p = 0; p < pathArray.length; p++) {
  23459. for (i = 0; i < minlg + closePathCorr; i++) {
  23460. u = us[p][i] / uTotalDistance[p];
  23461. v = vs[i][p] / vTotalDistance[i];
  23462. uvs.push(u, v);
  23463. }
  23464. }
  23465. // indices
  23466. p = 0; // path index
  23467. var pi = 0; // positions array index
  23468. var l1 = lg[p] - 1; // path1 length
  23469. var l2 = lg[p + 1] - 1; // path2 length
  23470. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23471. var shft = idx[1] - idx[0]; // shift
  23472. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23473. while (pi <= min && p < path1nb) {
  23474. // 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
  23475. indices.push(pi, pi + shft, pi + 1);
  23476. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23477. pi += 1;
  23478. if (pi === min) {
  23479. p++;
  23480. if (p === lg.length - 1) {
  23481. shft = idx[0] - idx[p];
  23482. l1 = lg[p] - 1;
  23483. l2 = lg[0] - 1;
  23484. }
  23485. else {
  23486. shft = idx[p + 1] - idx[p];
  23487. l1 = lg[p] - 1;
  23488. l2 = lg[p + 1] - 1;
  23489. }
  23490. pi = idx[p];
  23491. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23492. }
  23493. }
  23494. // normals
  23495. VertexData.ComputeNormals(positions, indices, normals);
  23496. if (closePath) {
  23497. var indexFirst = 0;
  23498. var indexLast = 0;
  23499. for (p = 0; p < pathArray.length; p++) {
  23500. indexFirst = idx[p] * 3;
  23501. if (p + 1 < pathArray.length) {
  23502. indexLast = (idx[p + 1] - 1) * 3;
  23503. }
  23504. else {
  23505. indexLast = normals.length - 3;
  23506. }
  23507. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23508. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23509. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23510. normals[indexLast] = normals[indexFirst];
  23511. normals[indexLast + 1] = normals[indexFirst + 1];
  23512. normals[indexLast + 2] = normals[indexFirst + 2];
  23513. }
  23514. }
  23515. // sides
  23516. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23517. // Result
  23518. var vertexData = new VertexData();
  23519. vertexData.indices = indices;
  23520. vertexData.positions = positions;
  23521. vertexData.normals = normals;
  23522. vertexData.uvs = uvs;
  23523. if (closePath) {
  23524. vertexData._idx = idx;
  23525. }
  23526. return vertexData;
  23527. };
  23528. VertexData.CreateBox = function (options) {
  23529. var normalsSource = [
  23530. new BABYLON.Vector3(0, 0, 1),
  23531. new BABYLON.Vector3(0, 0, -1),
  23532. new BABYLON.Vector3(1, 0, 0),
  23533. new BABYLON.Vector3(-1, 0, 0),
  23534. new BABYLON.Vector3(0, 1, 0),
  23535. new BABYLON.Vector3(0, -1, 0)
  23536. ];
  23537. var indices = [];
  23538. var positions = [];
  23539. var normals = [];
  23540. var uvs = [];
  23541. var width = options.width || options.size || 1;
  23542. var height = options.height || options.size || 1;
  23543. var depth = options.depth || options.size || 1;
  23544. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23545. var faceUV = options.faceUV || new Array(6);
  23546. var faceColors = options.faceColors;
  23547. var colors = [];
  23548. // default face colors and UV if undefined
  23549. for (var f = 0; f < 6; f++) {
  23550. if (faceUV[f] === undefined) {
  23551. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23552. }
  23553. if (faceColors && faceColors[f] === undefined) {
  23554. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23555. }
  23556. }
  23557. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23558. // Create each face in turn.
  23559. for (var index = 0; index < normalsSource.length; index++) {
  23560. var normal = normalsSource[index];
  23561. // Get two vectors perpendicular to the face normal and to each other.
  23562. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23563. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23564. // Six indices (two triangles) per face.
  23565. var verticesLength = positions.length / 3;
  23566. indices.push(verticesLength);
  23567. indices.push(verticesLength + 1);
  23568. indices.push(verticesLength + 2);
  23569. indices.push(verticesLength);
  23570. indices.push(verticesLength + 2);
  23571. indices.push(verticesLength + 3);
  23572. // Four vertices per face.
  23573. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23574. positions.push(vertex.x, vertex.y, vertex.z);
  23575. normals.push(normal.x, normal.y, normal.z);
  23576. uvs.push(faceUV[index].z, faceUV[index].w);
  23577. if (faceColors) {
  23578. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23579. }
  23580. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23581. positions.push(vertex.x, vertex.y, vertex.z);
  23582. normals.push(normal.x, normal.y, normal.z);
  23583. uvs.push(faceUV[index].x, faceUV[index].w);
  23584. if (faceColors) {
  23585. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23586. }
  23587. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23588. positions.push(vertex.x, vertex.y, vertex.z);
  23589. normals.push(normal.x, normal.y, normal.z);
  23590. uvs.push(faceUV[index].x, faceUV[index].y);
  23591. if (faceColors) {
  23592. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23593. }
  23594. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23595. positions.push(vertex.x, vertex.y, vertex.z);
  23596. normals.push(normal.x, normal.y, normal.z);
  23597. uvs.push(faceUV[index].z, faceUV[index].y);
  23598. if (faceColors) {
  23599. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23600. }
  23601. }
  23602. // sides
  23603. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23604. // Result
  23605. var vertexData = new VertexData();
  23606. vertexData.indices = indices;
  23607. vertexData.positions = positions;
  23608. vertexData.normals = normals;
  23609. vertexData.uvs = uvs;
  23610. if (faceColors) {
  23611. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23612. vertexData.colors = totalColors;
  23613. }
  23614. return vertexData;
  23615. };
  23616. VertexData.CreateSphere = function (options) {
  23617. var segments = options.segments || 32;
  23618. var diameterX = options.diameterX || options.diameter || 1;
  23619. var diameterY = options.diameterY || options.diameter || 1;
  23620. var diameterZ = options.diameterZ || options.diameter || 1;
  23621. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23622. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23623. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23624. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23625. var totalZRotationSteps = 2 + segments;
  23626. var totalYRotationSteps = 2 * totalZRotationSteps;
  23627. var indices = [];
  23628. var positions = [];
  23629. var normals = [];
  23630. var uvs = [];
  23631. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23632. var normalizedZ = zRotationStep / totalZRotationSteps;
  23633. var angleZ = normalizedZ * Math.PI * slice;
  23634. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23635. var normalizedY = yRotationStep / totalYRotationSteps;
  23636. var angleY = normalizedY * Math.PI * 2 * arc;
  23637. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23638. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23639. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23640. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23641. var vertex = complete.multiply(radius);
  23642. var normal = complete.divide(radius).normalize();
  23643. positions.push(vertex.x, vertex.y, vertex.z);
  23644. normals.push(normal.x, normal.y, normal.z);
  23645. uvs.push(normalizedY, normalizedZ);
  23646. }
  23647. if (zRotationStep > 0) {
  23648. var verticesCount = positions.length / 3;
  23649. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23650. indices.push((firstIndex));
  23651. indices.push((firstIndex + 1));
  23652. indices.push(firstIndex + totalYRotationSteps + 1);
  23653. indices.push((firstIndex + totalYRotationSteps + 1));
  23654. indices.push((firstIndex + 1));
  23655. indices.push((firstIndex + totalYRotationSteps + 2));
  23656. }
  23657. }
  23658. }
  23659. // Sides
  23660. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23661. // Result
  23662. var vertexData = new VertexData();
  23663. vertexData.indices = indices;
  23664. vertexData.positions = positions;
  23665. vertexData.normals = normals;
  23666. vertexData.uvs = uvs;
  23667. return vertexData;
  23668. };
  23669. // Cylinder and cone
  23670. VertexData.CreateCylinder = function (options) {
  23671. var height = options.height || 2;
  23672. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23673. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23674. var tessellation = options.tessellation || 24;
  23675. var subdivisions = options.subdivisions || 1;
  23676. var hasRings = options.hasRings;
  23677. var enclose = options.enclose;
  23678. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23679. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23680. var faceUV = options.faceUV || new Array(3);
  23681. var faceColors = options.faceColors;
  23682. // default face colors and UV if undefined
  23683. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23684. var ringNb = (hasRings) ? subdivisions : 1;
  23685. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23686. var f;
  23687. for (f = 0; f < surfaceNb; f++) {
  23688. if (faceColors && faceColors[f] === undefined) {
  23689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23690. }
  23691. }
  23692. for (f = 0; f < surfaceNb; f++) {
  23693. if (faceUV && faceUV[f] === undefined) {
  23694. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23695. }
  23696. }
  23697. var indices = [];
  23698. var positions = [];
  23699. var normals = [];
  23700. var uvs = [];
  23701. var colors = [];
  23702. var angle_step = Math.PI * 2 * arc / tessellation;
  23703. var angle;
  23704. var h;
  23705. var radius;
  23706. var tan = (diameterBottom - diameterTop) / 2 / height;
  23707. var ringVertex = BABYLON.Vector3.Zero();
  23708. var ringNormal = BABYLON.Vector3.Zero();
  23709. var ringFirstVertex = BABYLON.Vector3.Zero();
  23710. var ringFirstNormal = BABYLON.Vector3.Zero();
  23711. var quadNormal = BABYLON.Vector3.Zero();
  23712. var Y = BABYLON.Axis.Y;
  23713. // positions, normals, uvs
  23714. var i;
  23715. var j;
  23716. var r;
  23717. var ringIdx = 1;
  23718. var s = 1; // surface index
  23719. var cs = 0;
  23720. var v = 0;
  23721. for (i = 0; i <= subdivisions; i++) {
  23722. h = i / subdivisions;
  23723. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23724. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23725. for (r = 0; r < ringIdx; r++) {
  23726. if (hasRings) {
  23727. s += r;
  23728. }
  23729. if (enclose) {
  23730. s += 2 * r;
  23731. }
  23732. for (j = 0; j <= tessellation; j++) {
  23733. angle = j * angle_step;
  23734. // position
  23735. ringVertex.x = Math.cos(-angle) * radius;
  23736. ringVertex.y = -height / 2 + h * height;
  23737. ringVertex.z = Math.sin(-angle) * radius;
  23738. // normal
  23739. if (diameterTop === 0 && i === subdivisions) {
  23740. // if no top cap, reuse former normals
  23741. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23742. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23743. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23744. }
  23745. else {
  23746. ringNormal.x = ringVertex.x;
  23747. ringNormal.z = ringVertex.z;
  23748. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23749. ringNormal.normalize();
  23750. }
  23751. // keep first ring vertex values for enclose
  23752. if (j === 0) {
  23753. ringFirstVertex.copyFrom(ringVertex);
  23754. ringFirstNormal.copyFrom(ringNormal);
  23755. }
  23756. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23757. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23758. if (hasRings) {
  23759. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23760. }
  23761. else {
  23762. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23763. }
  23764. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23765. if (faceColors) {
  23766. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23767. }
  23768. }
  23769. // if enclose, add four vertices and their dedicated normals
  23770. if (arc !== 1 && enclose) {
  23771. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23772. positions.push(0, ringVertex.y, 0);
  23773. positions.push(0, ringVertex.y, 0);
  23774. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23775. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23776. quadNormal.normalize();
  23777. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23778. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23779. quadNormal.normalize();
  23780. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23781. if (hasRings) {
  23782. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23783. }
  23784. else {
  23785. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23786. }
  23787. uvs.push(faceUV[s + 1].x, v);
  23788. uvs.push(faceUV[s + 1].z, v);
  23789. if (hasRings) {
  23790. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23791. }
  23792. else {
  23793. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23794. }
  23795. uvs.push(faceUV[s + 2].x, v);
  23796. uvs.push(faceUV[s + 2].z, v);
  23797. if (faceColors) {
  23798. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23799. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23800. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23801. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23802. }
  23803. }
  23804. if (cs !== s) {
  23805. cs = s;
  23806. }
  23807. }
  23808. }
  23809. // indices
  23810. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23811. var s;
  23812. i = 0;
  23813. for (s = 0; s < subdivisions; s++) {
  23814. for (j = 0; j < tessellation; j++) {
  23815. var i0 = i * (e + 1) + j;
  23816. var i1 = (i + 1) * (e + 1) + j;
  23817. var i2 = i * (e + 1) + (j + 1);
  23818. var i3 = (i + 1) * (e + 1) + (j + 1);
  23819. indices.push(i0, i1, i2);
  23820. indices.push(i3, i2, i1);
  23821. }
  23822. if (arc !== 1 && enclose) {
  23823. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23824. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23825. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23826. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23827. }
  23828. i = (hasRings) ? (i + 2) : (i + 1);
  23829. }
  23830. // Caps
  23831. var createCylinderCap = function (isTop) {
  23832. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23833. if (radius === 0) {
  23834. return;
  23835. }
  23836. // Cap positions, normals & uvs
  23837. var angle;
  23838. var circleVector;
  23839. var i;
  23840. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23841. var c;
  23842. if (faceColors) {
  23843. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23844. }
  23845. // cap center
  23846. var vbase = positions.length / 3;
  23847. var offset = isTop ? height / 2 : -height / 2;
  23848. var center = new BABYLON.Vector3(0, offset, 0);
  23849. positions.push(center.x, center.y, center.z);
  23850. normals.push(0, isTop ? 1 : -1, 0);
  23851. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23852. if (faceColors) {
  23853. colors.push(c.r, c.g, c.b, c.a);
  23854. }
  23855. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23856. for (i = 0; i <= tessellation; i++) {
  23857. angle = Math.PI * 2 * i * arc / tessellation;
  23858. var cos = Math.cos(-angle);
  23859. var sin = Math.sin(-angle);
  23860. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23861. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23862. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23863. normals.push(0, isTop ? 1 : -1, 0);
  23864. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23865. if (faceColors) {
  23866. colors.push(c.r, c.g, c.b, c.a);
  23867. }
  23868. }
  23869. // Cap indices
  23870. for (i = 0; i < tessellation; i++) {
  23871. if (!isTop) {
  23872. indices.push(vbase);
  23873. indices.push(vbase + (i + 1));
  23874. indices.push(vbase + (i + 2));
  23875. }
  23876. else {
  23877. indices.push(vbase);
  23878. indices.push(vbase + (i + 2));
  23879. indices.push(vbase + (i + 1));
  23880. }
  23881. }
  23882. };
  23883. // add caps to geometry
  23884. createCylinderCap(false);
  23885. createCylinderCap(true);
  23886. // Sides
  23887. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23888. var vertexData = new VertexData();
  23889. vertexData.indices = indices;
  23890. vertexData.positions = positions;
  23891. vertexData.normals = normals;
  23892. vertexData.uvs = uvs;
  23893. if (faceColors) {
  23894. vertexData.colors = colors;
  23895. }
  23896. return vertexData;
  23897. };
  23898. VertexData.CreateTorus = function (options) {
  23899. var indices = [];
  23900. var positions = [];
  23901. var normals = [];
  23902. var uvs = [];
  23903. var diameter = options.diameter || 1;
  23904. var thickness = options.thickness || 0.5;
  23905. var tessellation = options.tessellation || 16;
  23906. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23907. var stride = tessellation + 1;
  23908. for (var i = 0; i <= tessellation; i++) {
  23909. var u = i / tessellation;
  23910. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23911. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23912. for (var j = 0; j <= tessellation; j++) {
  23913. var v = 1 - j / tessellation;
  23914. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23915. var dx = Math.cos(innerAngle);
  23916. var dy = Math.sin(innerAngle);
  23917. // Create a vertex.
  23918. var normal = new BABYLON.Vector3(dx, dy, 0);
  23919. var position = normal.scale(thickness / 2);
  23920. var textureCoordinate = new BABYLON.Vector2(u, v);
  23921. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23922. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23923. positions.push(position.x, position.y, position.z);
  23924. normals.push(normal.x, normal.y, normal.z);
  23925. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23926. // And create indices for two triangles.
  23927. var nextI = (i + 1) % stride;
  23928. var nextJ = (j + 1) % stride;
  23929. indices.push(i * stride + j);
  23930. indices.push(i * stride + nextJ);
  23931. indices.push(nextI * stride + j);
  23932. indices.push(i * stride + nextJ);
  23933. indices.push(nextI * stride + nextJ);
  23934. indices.push(nextI * stride + j);
  23935. }
  23936. }
  23937. // Sides
  23938. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23939. // Result
  23940. var vertexData = new VertexData();
  23941. vertexData.indices = indices;
  23942. vertexData.positions = positions;
  23943. vertexData.normals = normals;
  23944. vertexData.uvs = uvs;
  23945. return vertexData;
  23946. };
  23947. VertexData.CreateLines = function (options) {
  23948. var indices = [];
  23949. var positions = [];
  23950. var points = options.points;
  23951. for (var index = 0; index < points.length; index++) {
  23952. positions.push(points[index].x, points[index].y, points[index].z);
  23953. if (index > 0) {
  23954. indices.push(index - 1);
  23955. indices.push(index);
  23956. }
  23957. }
  23958. // Result
  23959. var vertexData = new VertexData();
  23960. vertexData.indices = indices;
  23961. vertexData.positions = positions;
  23962. return vertexData;
  23963. };
  23964. VertexData.CreateDashedLines = function (options) {
  23965. var dashSize = options.dashSize || 3;
  23966. var gapSize = options.gapSize || 1;
  23967. var dashNb = options.dashNb || 200;
  23968. var points = options.points;
  23969. var positions = new Array();
  23970. var indices = new Array();
  23971. var curvect = BABYLON.Vector3.Zero();
  23972. var lg = 0;
  23973. var nb = 0;
  23974. var shft = 0;
  23975. var dashshft = 0;
  23976. var curshft = 0;
  23977. var idx = 0;
  23978. var i = 0;
  23979. for (i = 0; i < points.length - 1; i++) {
  23980. points[i + 1].subtractToRef(points[i], curvect);
  23981. lg += curvect.length();
  23982. }
  23983. shft = lg / dashNb;
  23984. dashshft = dashSize * shft / (dashSize + gapSize);
  23985. for (i = 0; i < points.length - 1; i++) {
  23986. points[i + 1].subtractToRef(points[i], curvect);
  23987. nb = Math.floor(curvect.length() / shft);
  23988. curvect.normalize();
  23989. for (var j = 0; j < nb; j++) {
  23990. curshft = shft * j;
  23991. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23992. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23993. indices.push(idx, idx + 1);
  23994. idx += 2;
  23995. }
  23996. }
  23997. // Result
  23998. var vertexData = new VertexData();
  23999. vertexData.positions = positions;
  24000. vertexData.indices = indices;
  24001. return vertexData;
  24002. };
  24003. VertexData.CreateGround = function (options) {
  24004. var indices = [];
  24005. var positions = [];
  24006. var normals = [];
  24007. var uvs = [];
  24008. var row, col;
  24009. var width = options.width || 1;
  24010. var height = options.height || 1;
  24011. var subdivisions = options.subdivisions || 1;
  24012. for (row = 0; row <= subdivisions; row++) {
  24013. for (col = 0; col <= subdivisions; col++) {
  24014. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24015. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24016. positions.push(position.x, position.y, position.z);
  24017. normals.push(normal.x, normal.y, normal.z);
  24018. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24019. }
  24020. }
  24021. for (row = 0; row < subdivisions; row++) {
  24022. for (col = 0; col < subdivisions; col++) {
  24023. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24024. indices.push(col + 1 + row * (subdivisions + 1));
  24025. indices.push(col + row * (subdivisions + 1));
  24026. indices.push(col + (row + 1) * (subdivisions + 1));
  24027. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24028. indices.push(col + row * (subdivisions + 1));
  24029. }
  24030. }
  24031. // Result
  24032. var vertexData = new VertexData();
  24033. vertexData.indices = indices;
  24034. vertexData.positions = positions;
  24035. vertexData.normals = normals;
  24036. vertexData.uvs = uvs;
  24037. return vertexData;
  24038. };
  24039. VertexData.CreateTiledGround = function (options) {
  24040. var xmin = options.xmin;
  24041. var zmin = options.zmin;
  24042. var xmax = options.xmax;
  24043. var zmax = options.zmax;
  24044. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24045. var precision = options.precision || { w: 1, h: 1 };
  24046. var indices = [];
  24047. var positions = [];
  24048. var normals = [];
  24049. var uvs = [];
  24050. var row, col, tileRow, tileCol;
  24051. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24052. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24053. precision.w = (precision.w < 1) ? 1 : precision.w;
  24054. precision.h = (precision.h < 1) ? 1 : precision.h;
  24055. var tileSize = {
  24056. 'w': (xmax - xmin) / subdivisions.w,
  24057. 'h': (zmax - zmin) / subdivisions.h
  24058. };
  24059. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24060. // Indices
  24061. var base = positions.length / 3;
  24062. var rowLength = precision.w + 1;
  24063. for (row = 0; row < precision.h; row++) {
  24064. for (col = 0; col < precision.w; col++) {
  24065. var square = [
  24066. base + col + row * rowLength,
  24067. base + (col + 1) + row * rowLength,
  24068. base + (col + 1) + (row + 1) * rowLength,
  24069. base + col + (row + 1) * rowLength
  24070. ];
  24071. indices.push(square[1]);
  24072. indices.push(square[2]);
  24073. indices.push(square[3]);
  24074. indices.push(square[0]);
  24075. indices.push(square[1]);
  24076. indices.push(square[3]);
  24077. }
  24078. }
  24079. // Position, normals and uvs
  24080. var position = BABYLON.Vector3.Zero();
  24081. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24082. for (row = 0; row <= precision.h; row++) {
  24083. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24084. for (col = 0; col <= precision.w; col++) {
  24085. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24086. position.y = 0;
  24087. positions.push(position.x, position.y, position.z);
  24088. normals.push(normal.x, normal.y, normal.z);
  24089. uvs.push(col / precision.w, row / precision.h);
  24090. }
  24091. }
  24092. }
  24093. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24094. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24095. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24096. }
  24097. }
  24098. // Result
  24099. var vertexData = new VertexData();
  24100. vertexData.indices = indices;
  24101. vertexData.positions = positions;
  24102. vertexData.normals = normals;
  24103. vertexData.uvs = uvs;
  24104. return vertexData;
  24105. };
  24106. VertexData.CreateGroundFromHeightMap = function (options) {
  24107. var indices = [];
  24108. var positions = [];
  24109. var normals = [];
  24110. var uvs = [];
  24111. var row, col;
  24112. // Vertices
  24113. for (row = 0; row <= options.subdivisions; row++) {
  24114. for (col = 0; col <= options.subdivisions; col++) {
  24115. 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));
  24116. // Compute height
  24117. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24118. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24119. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24120. var r = options.buffer[pos] / 255.0;
  24121. var g = options.buffer[pos + 1] / 255.0;
  24122. var b = options.buffer[pos + 2] / 255.0;
  24123. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24124. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24125. // Add vertex
  24126. positions.push(position.x, position.y, position.z);
  24127. normals.push(0, 0, 0);
  24128. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24129. }
  24130. }
  24131. // Indices
  24132. for (row = 0; row < options.subdivisions; row++) {
  24133. for (col = 0; col < options.subdivisions; col++) {
  24134. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24135. indices.push(col + 1 + row * (options.subdivisions + 1));
  24136. indices.push(col + row * (options.subdivisions + 1));
  24137. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24138. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24139. indices.push(col + row * (options.subdivisions + 1));
  24140. }
  24141. }
  24142. // Normals
  24143. VertexData.ComputeNormals(positions, indices, normals);
  24144. // Result
  24145. var vertexData = new VertexData();
  24146. vertexData.indices = indices;
  24147. vertexData.positions = positions;
  24148. vertexData.normals = normals;
  24149. vertexData.uvs = uvs;
  24150. return vertexData;
  24151. };
  24152. VertexData.CreatePlane = function (options) {
  24153. var indices = [];
  24154. var positions = [];
  24155. var normals = [];
  24156. var uvs = [];
  24157. var width = options.width || options.size || 1;
  24158. var height = options.height || options.size || 1;
  24159. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24160. // Vertices
  24161. var halfWidth = width / 2.0;
  24162. var halfHeight = height / 2.0;
  24163. positions.push(-halfWidth, -halfHeight, 0);
  24164. normals.push(0, 0, -1.0);
  24165. uvs.push(0.0, 0.0);
  24166. positions.push(halfWidth, -halfHeight, 0);
  24167. normals.push(0, 0, -1.0);
  24168. uvs.push(1.0, 0.0);
  24169. positions.push(halfWidth, halfHeight, 0);
  24170. normals.push(0, 0, -1.0);
  24171. uvs.push(1.0, 1.0);
  24172. positions.push(-halfWidth, halfHeight, 0);
  24173. normals.push(0, 0, -1.0);
  24174. uvs.push(0.0, 1.0);
  24175. // Indices
  24176. indices.push(0);
  24177. indices.push(1);
  24178. indices.push(2);
  24179. indices.push(0);
  24180. indices.push(2);
  24181. indices.push(3);
  24182. // Sides
  24183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24184. // Result
  24185. var vertexData = new VertexData();
  24186. vertexData.indices = indices;
  24187. vertexData.positions = positions;
  24188. vertexData.normals = normals;
  24189. vertexData.uvs = uvs;
  24190. return vertexData;
  24191. };
  24192. VertexData.CreateDisc = function (options) {
  24193. var positions = [];
  24194. var indices = [];
  24195. var normals = [];
  24196. var uvs = [];
  24197. var radius = options.radius || 0.5;
  24198. var tessellation = options.tessellation || 64;
  24199. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24201. // positions and uvs
  24202. positions.push(0, 0, 0); // disc center first
  24203. uvs.push(0.5, 0.5);
  24204. var theta = Math.PI * 2 * arc;
  24205. var step = theta / tessellation;
  24206. for (var a = 0; a < theta; a += step) {
  24207. var x = Math.cos(a);
  24208. var y = Math.sin(a);
  24209. var u = (x + 1) / 2;
  24210. var v = (1 - y) / 2;
  24211. positions.push(radius * x, radius * y, 0);
  24212. uvs.push(u, v);
  24213. }
  24214. if (arc === 1) {
  24215. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24216. uvs.push(uvs[2], uvs[3]);
  24217. }
  24218. //indices
  24219. var vertexNb = positions.length / 3;
  24220. for (var i = 1; i < vertexNb - 1; i++) {
  24221. indices.push(i + 1, 0, i);
  24222. }
  24223. // result
  24224. VertexData.ComputeNormals(positions, indices, normals);
  24225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24226. var vertexData = new VertexData();
  24227. vertexData.indices = indices;
  24228. vertexData.positions = positions;
  24229. vertexData.normals = normals;
  24230. vertexData.uvs = uvs;
  24231. return vertexData;
  24232. };
  24233. VertexData.CreateIcoSphere = function (options) {
  24234. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24235. var radius = options.radius || 1;
  24236. var flat = (options.flat === undefined) ? true : options.flat;
  24237. var subdivisions = options.subdivisions || 4;
  24238. var radiusX = options.radiusX || radius;
  24239. var radiusY = options.radiusY || radius;
  24240. var radiusZ = options.radiusZ || radius;
  24241. var t = (1 + Math.sqrt(5)) / 2;
  24242. // 12 vertex x,y,z
  24243. var ico_vertices = [
  24244. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24245. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24246. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24247. ];
  24248. // index of 3 vertex makes a face of icopshere
  24249. var ico_indices = [
  24250. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24251. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24252. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24253. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24254. ];
  24255. // vertex for uv have aliased position, not for UV
  24256. var vertices_unalias_id = [
  24257. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24258. // vertex alias
  24259. 0,
  24260. 2,
  24261. 3,
  24262. 3,
  24263. 3,
  24264. 4,
  24265. 7,
  24266. 8,
  24267. 9,
  24268. 9,
  24269. 10,
  24270. 11 // 23: B + 12
  24271. ];
  24272. // uv as integer step (not pixels !)
  24273. var ico_vertexuv = [
  24274. 5, 1, 3, 1, 6, 4, 0, 0,
  24275. 5, 3, 4, 2, 2, 2, 4, 0,
  24276. 2, 0, 1, 1, 6, 0, 6, 2,
  24277. // vertex alias (for same vertex on different faces)
  24278. 0, 4,
  24279. 3, 3,
  24280. 4, 4,
  24281. 3, 1,
  24282. 4, 2,
  24283. 4, 4,
  24284. 0, 2,
  24285. 1, 1,
  24286. 2, 2,
  24287. 3, 3,
  24288. 1, 3,
  24289. 2, 4 // 23: B + 12
  24290. ];
  24291. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24292. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24293. // First island of uv mapping
  24294. // v = 4h 3+ 2
  24295. // v = 3h 9+ 4
  24296. // v = 2h 9+ 5 B
  24297. // v = 1h 9 1 0
  24298. // v = 0h 3 8 7 A
  24299. // u = 0 1 2 3 4 5 6 *a
  24300. // Second island of uv mapping
  24301. // v = 4h 0+ B+ 4+
  24302. // v = 3h A+ 2+
  24303. // v = 2h 7+ 6 3+
  24304. // v = 1h 8+ 3+
  24305. // v = 0h
  24306. // u = 0 1 2 3 4 5 6 *a
  24307. // Face layout on texture UV mapping
  24308. // ============
  24309. // \ 4 /\ 16 / ======
  24310. // \ / \ / /\ 11 /
  24311. // \/ 7 \/ / \ /
  24312. // ======= / 10 \/
  24313. // /\ 17 /\ =======
  24314. // / \ / \ \ 15 /\
  24315. // / 8 \/ 12 \ \ / \
  24316. // ============ \/ 6 \
  24317. // \ 18 /\ ============
  24318. // \ / \ \ 5 /\ 0 /
  24319. // \/ 13 \ \ / \ /
  24320. // ======= \/ 1 \/
  24321. // =============
  24322. // /\ 19 /\ 2 /\
  24323. // / \ / \ / \
  24324. // / 14 \/ 9 \/ 3 \
  24325. // ===================
  24326. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24327. var ustep = 138 / 1024;
  24328. var vstep = 239 / 1024;
  24329. var uoffset = 60 / 1024;
  24330. var voffset = 26 / 1024;
  24331. // Second island should have margin, not to touch the first island
  24332. // avoid any borderline artefact in pixel rounding
  24333. var island_u_offset = -40 / 1024;
  24334. var island_v_offset = +20 / 1024;
  24335. // face is either island 0 or 1 :
  24336. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24337. var island = [
  24338. 0, 0, 0, 0, 1,
  24339. 0, 0, 1, 1, 0,
  24340. 0, 0, 1, 1, 0,
  24341. 0, 1, 1, 1, 0 // 15 - 19
  24342. ];
  24343. var indices = [];
  24344. var positions = [];
  24345. var normals = [];
  24346. var uvs = [];
  24347. var current_indice = 0;
  24348. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24349. var face_vertex_pos = new Array(3);
  24350. var face_vertex_uv = new Array(3);
  24351. var v012;
  24352. for (v012 = 0; v012 < 3; v012++) {
  24353. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24354. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24355. }
  24356. // create all with normals
  24357. for (var face = 0; face < 20; face++) {
  24358. // 3 vertex per face
  24359. for (v012 = 0; v012 < 3; v012++) {
  24360. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24361. var v_id = ico_indices[3 * face + v012];
  24362. // vertex have 3D position (x,y,z)
  24363. 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]);
  24364. // Normalize to get normal, then scale to radius
  24365. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24366. // uv Coordinates from vertex ID
  24367. 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);
  24368. }
  24369. // Subdivide the face (interpolate pos, norm, uv)
  24370. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24371. // - norm is linear interpolation of vertex corner normal
  24372. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24373. // - uv is linear interpolation
  24374. //
  24375. // Topology is as below for sub-divide by 2
  24376. // vertex shown as v0,v1,v2
  24377. // interp index is i1 to progress in range [v0,v1[
  24378. // interp index is i2 to progress in range [v0,v2[
  24379. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24380. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24381. //
  24382. //
  24383. // i2 v2
  24384. // ^ ^
  24385. // / / \
  24386. // / / \
  24387. // / / \
  24388. // / / (0,1) \
  24389. // / #---------\
  24390. // / / \ (0,0)'/ \
  24391. // / / \ / \
  24392. // / / \ / \
  24393. // / / (0,0) \ / (1,0) \
  24394. // / #---------#---------\
  24395. // v0 v1
  24396. //
  24397. // --------------------> i1
  24398. //
  24399. // interp of (i1,i2):
  24400. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24401. // along i1 : lerp(x0,x1, i1/(S-i2))
  24402. //
  24403. // centroid of triangle is needed to get help normal computation
  24404. // (c1,c2) are used for centroid location
  24405. var interp_vertex = function (i1, i2, c1, c2) {
  24406. // vertex is interpolated from
  24407. // - face_vertex_pos[0..2]
  24408. // - face_vertex_uv[0..2]
  24409. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24410. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24411. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24412. pos_interp.normalize();
  24413. var vertex_normal;
  24414. if (flat) {
  24415. // in flat mode, recalculate normal as face centroid normal
  24416. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24417. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24418. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24419. }
  24420. else {
  24421. // in smooth mode, recalculate normal from each single vertex position
  24422. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24423. }
  24424. // Vertex normal need correction due to X,Y,Z radius scaling
  24425. vertex_normal.x /= radiusX;
  24426. vertex_normal.y /= radiusY;
  24427. vertex_normal.z /= radiusZ;
  24428. vertex_normal.normalize();
  24429. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24430. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24431. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24432. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24433. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24434. uvs.push(uv_interp.x, uv_interp.y);
  24435. // push each vertex has member of a face
  24436. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24437. indices.push(current_indice);
  24438. current_indice++;
  24439. };
  24440. for (var i2 = 0; i2 < subdivisions; i2++) {
  24441. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24442. // face : (i1,i2) for /\ :
  24443. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24444. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24445. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24446. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24447. if (i1 + i2 + 1 < subdivisions) {
  24448. // face : (i1,i2)' for \/ :
  24449. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24450. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24451. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24452. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24453. }
  24454. }
  24455. }
  24456. }
  24457. // Sides
  24458. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24459. // Result
  24460. var vertexData = new VertexData();
  24461. vertexData.indices = indices;
  24462. vertexData.positions = positions;
  24463. vertexData.normals = normals;
  24464. vertexData.uvs = uvs;
  24465. return vertexData;
  24466. };
  24467. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24468. VertexData.CreatePolyhedron = function (options) {
  24469. // provided polyhedron types :
  24470. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24471. // 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)
  24472. var polyhedra = [];
  24473. 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]] };
  24474. 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]] };
  24475. polyhedra[2] = {
  24476. 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]],
  24477. 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]]
  24478. };
  24479. polyhedra[3] = {
  24480. 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]],
  24481. 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]]
  24482. };
  24483. polyhedra[4] = {
  24484. 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]],
  24485. 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]]
  24486. };
  24487. 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]] };
  24488. 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]] };
  24489. 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]] };
  24490. 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]] };
  24491. 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]] };
  24492. 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]] };
  24493. 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]] };
  24494. 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]] };
  24495. 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]] };
  24496. polyhedra[14] = {
  24497. 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]],
  24498. 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]]
  24499. };
  24500. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24501. var size = options.size;
  24502. var sizeX = options.sizeX || size || 1;
  24503. var sizeY = options.sizeY || size || 1;
  24504. var sizeZ = options.sizeZ || size || 1;
  24505. var data = options.custom || polyhedra[type];
  24506. var nbfaces = data.face.length;
  24507. var faceUV = options.faceUV || new Array(nbfaces);
  24508. var faceColors = options.faceColors;
  24509. var flat = (options.flat === undefined) ? true : options.flat;
  24510. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24511. var positions = [];
  24512. var indices = [];
  24513. var normals = [];
  24514. var uvs = [];
  24515. var colors = [];
  24516. var index = 0;
  24517. var faceIdx = 0; // face cursor in the array "indexes"
  24518. var indexes = [];
  24519. var i = 0;
  24520. var f = 0;
  24521. var u, v, ang, x, y, tmp;
  24522. // default face colors and UV if undefined
  24523. if (flat) {
  24524. for (f = 0; f < nbfaces; f++) {
  24525. if (faceColors && faceColors[f] === undefined) {
  24526. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24527. }
  24528. if (faceUV && faceUV[f] === undefined) {
  24529. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24530. }
  24531. }
  24532. }
  24533. if (!flat) {
  24534. for (i = 0; i < data.vertex.length; i++) {
  24535. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24536. uvs.push(0, 0);
  24537. }
  24538. for (f = 0; f < nbfaces; f++) {
  24539. for (i = 0; i < data.face[f].length - 2; i++) {
  24540. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24541. }
  24542. }
  24543. }
  24544. else {
  24545. for (f = 0; f < nbfaces; f++) {
  24546. var fl = data.face[f].length; // number of vertices of the current face
  24547. ang = 2 * Math.PI / fl;
  24548. x = 0.5 * Math.tan(ang / 2);
  24549. y = 0.5;
  24550. // positions, uvs, colors
  24551. for (i = 0; i < fl; i++) {
  24552. // positions
  24553. 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);
  24554. indexes.push(index);
  24555. index++;
  24556. // uvs
  24557. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24558. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24559. uvs.push(u, v);
  24560. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24561. y = x * Math.sin(ang) + y * Math.cos(ang);
  24562. x = tmp;
  24563. // colors
  24564. if (faceColors) {
  24565. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24566. }
  24567. }
  24568. // indices from indexes
  24569. for (i = 0; i < fl - 2; i++) {
  24570. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24571. }
  24572. faceIdx += fl;
  24573. }
  24574. }
  24575. VertexData.ComputeNormals(positions, indices, normals);
  24576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24577. var vertexData = new VertexData();
  24578. vertexData.positions = positions;
  24579. vertexData.indices = indices;
  24580. vertexData.normals = normals;
  24581. vertexData.uvs = uvs;
  24582. if (faceColors && flat) {
  24583. vertexData.colors = colors;
  24584. }
  24585. return vertexData;
  24586. };
  24587. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24588. VertexData.CreateTorusKnot = function (options) {
  24589. var indices = [];
  24590. var positions = [];
  24591. var normals = [];
  24592. var uvs = [];
  24593. var radius = options.radius || 2;
  24594. var tube = options.tube || 0.5;
  24595. var radialSegments = options.radialSegments || 32;
  24596. var tubularSegments = options.tubularSegments || 32;
  24597. var p = options.p || 2;
  24598. var q = options.q || 3;
  24599. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24600. // Helper
  24601. var getPos = function (angle) {
  24602. var cu = Math.cos(angle);
  24603. var su = Math.sin(angle);
  24604. var quOverP = q / p * angle;
  24605. var cs = Math.cos(quOverP);
  24606. var tx = radius * (2 + cs) * 0.5 * cu;
  24607. var ty = radius * (2 + cs) * su * 0.5;
  24608. var tz = radius * Math.sin(quOverP) * 0.5;
  24609. return new BABYLON.Vector3(tx, ty, tz);
  24610. };
  24611. // Vertices
  24612. var i;
  24613. var j;
  24614. for (i = 0; i <= radialSegments; i++) {
  24615. var modI = i % radialSegments;
  24616. var u = modI / radialSegments * 2 * p * Math.PI;
  24617. var p1 = getPos(u);
  24618. var p2 = getPos(u + 0.01);
  24619. var tang = p2.subtract(p1);
  24620. var n = p2.add(p1);
  24621. var bitan = BABYLON.Vector3.Cross(tang, n);
  24622. n = BABYLON.Vector3.Cross(bitan, tang);
  24623. bitan.normalize();
  24624. n.normalize();
  24625. for (j = 0; j < tubularSegments; j++) {
  24626. var modJ = j % tubularSegments;
  24627. var v = modJ / tubularSegments * 2 * Math.PI;
  24628. var cx = -tube * Math.cos(v);
  24629. var cy = tube * Math.sin(v);
  24630. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24631. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24632. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24633. uvs.push(i / radialSegments);
  24634. uvs.push(j / tubularSegments);
  24635. }
  24636. }
  24637. for (i = 0; i < radialSegments; i++) {
  24638. for (j = 0; j < tubularSegments; j++) {
  24639. var jNext = (j + 1) % tubularSegments;
  24640. var a = i * tubularSegments + j;
  24641. var b = (i + 1) * tubularSegments + j;
  24642. var c = (i + 1) * tubularSegments + jNext;
  24643. var d = i * tubularSegments + jNext;
  24644. indices.push(d);
  24645. indices.push(b);
  24646. indices.push(a);
  24647. indices.push(d);
  24648. indices.push(c);
  24649. indices.push(b);
  24650. }
  24651. }
  24652. // Normals
  24653. VertexData.ComputeNormals(positions, indices, normals);
  24654. // Sides
  24655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24656. // Result
  24657. var vertexData = new VertexData();
  24658. vertexData.indices = indices;
  24659. vertexData.positions = positions;
  24660. vertexData.normals = normals;
  24661. vertexData.uvs = uvs;
  24662. return vertexData;
  24663. };
  24664. // Tools
  24665. /**
  24666. * @param {any} - positions (number[] or Float32Array)
  24667. * @param {any} - indices (number[] or Uint16Array)
  24668. * @param {any} - normals (number[] or Float32Array)
  24669. */
  24670. VertexData.ComputeNormals = function (positions, indices, normals) {
  24671. var index = 0;
  24672. var p1p2x = 0.0;
  24673. var p1p2y = 0.0;
  24674. var p1p2z = 0.0;
  24675. var p3p2x = 0.0;
  24676. var p3p2y = 0.0;
  24677. var p3p2z = 0.0;
  24678. var faceNormalx = 0.0;
  24679. var faceNormaly = 0.0;
  24680. var faceNormalz = 0.0;
  24681. var length = 0.0;
  24682. var i1 = 0;
  24683. var i2 = 0;
  24684. var i3 = 0;
  24685. for (index = 0; index < positions.length; index++) {
  24686. normals[index] = 0.0;
  24687. }
  24688. // indice triplet = 1 face
  24689. var nbFaces = indices.length / 3;
  24690. for (index = 0; index < nbFaces; index++) {
  24691. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24692. i2 = indices[index * 3 + 1];
  24693. i3 = indices[index * 3 + 2];
  24694. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24695. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24696. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24697. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24698. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24699. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24700. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24701. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24702. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24703. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24704. length = (length === 0) ? 1.0 : length;
  24705. faceNormalx /= length; // normalize this normal
  24706. faceNormaly /= length;
  24707. faceNormalz /= length;
  24708. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24709. normals[i1 * 3 + 1] += faceNormaly;
  24710. normals[i1 * 3 + 2] += faceNormalz;
  24711. normals[i2 * 3] += faceNormalx;
  24712. normals[i2 * 3 + 1] += faceNormaly;
  24713. normals[i2 * 3 + 2] += faceNormalz;
  24714. normals[i3 * 3] += faceNormalx;
  24715. normals[i3 * 3 + 1] += faceNormaly;
  24716. normals[i3 * 3 + 2] += faceNormalz;
  24717. }
  24718. // last normalization of each normal
  24719. for (index = 0; index < normals.length / 3; index++) {
  24720. faceNormalx = normals[index * 3];
  24721. faceNormaly = normals[index * 3 + 1];
  24722. faceNormalz = normals[index * 3 + 2];
  24723. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24724. length = (length === 0) ? 1.0 : length;
  24725. faceNormalx /= length;
  24726. faceNormaly /= length;
  24727. faceNormalz /= length;
  24728. normals[index * 3] = faceNormalx;
  24729. normals[index * 3 + 1] = faceNormaly;
  24730. normals[index * 3 + 2] = faceNormalz;
  24731. }
  24732. };
  24733. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24734. var li = indices.length;
  24735. var ln = normals.length;
  24736. var i;
  24737. var n;
  24738. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24739. switch (sideOrientation) {
  24740. case BABYLON.Mesh.FRONTSIDE:
  24741. // nothing changed
  24742. break;
  24743. case BABYLON.Mesh.BACKSIDE:
  24744. var tmp;
  24745. // indices
  24746. for (i = 0; i < li; i += 3) {
  24747. tmp = indices[i];
  24748. indices[i] = indices[i + 2];
  24749. indices[i + 2] = tmp;
  24750. }
  24751. // normals
  24752. for (n = 0; n < ln; n++) {
  24753. normals[n] = -normals[n];
  24754. }
  24755. break;
  24756. case BABYLON.Mesh.DOUBLESIDE:
  24757. // positions
  24758. var lp = positions.length;
  24759. var l = lp / 3;
  24760. for (var p = 0; p < lp; p++) {
  24761. positions[lp + p] = positions[p];
  24762. }
  24763. // indices
  24764. for (i = 0; i < li; i += 3) {
  24765. indices[i + li] = indices[i + 2] + l;
  24766. indices[i + 1 + li] = indices[i + 1] + l;
  24767. indices[i + 2 + li] = indices[i] + l;
  24768. }
  24769. // normals
  24770. for (n = 0; n < ln; n++) {
  24771. normals[ln + n] = -normals[n];
  24772. }
  24773. // uvs
  24774. var lu = uvs.length;
  24775. for (var u = 0; u < lu; u++) {
  24776. uvs[u + lu] = uvs[u];
  24777. }
  24778. break;
  24779. }
  24780. };
  24781. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24782. var vertexData = new VertexData();
  24783. // positions
  24784. var positions = parsedVertexData.positions;
  24785. if (positions) {
  24786. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24787. }
  24788. // normals
  24789. var normals = parsedVertexData.normals;
  24790. if (normals) {
  24791. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24792. }
  24793. // uvs
  24794. var uvs = parsedVertexData.uvs;
  24795. if (uvs) {
  24796. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24797. }
  24798. // uv2s
  24799. var uv2s = parsedVertexData.uv2s;
  24800. if (uv2s) {
  24801. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24802. }
  24803. // uv3s
  24804. var uv3s = parsedVertexData.uv3s;
  24805. if (uv3s) {
  24806. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24807. }
  24808. // uv4s
  24809. var uv4s = parsedVertexData.uv4s;
  24810. if (uv4s) {
  24811. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24812. }
  24813. // uv5s
  24814. var uv5s = parsedVertexData.uv5s;
  24815. if (uv5s) {
  24816. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24817. }
  24818. // uv6s
  24819. var uv6s = parsedVertexData.uv6s;
  24820. if (uv6s) {
  24821. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24822. }
  24823. // colors
  24824. var colors = parsedVertexData.colors;
  24825. if (colors) {
  24826. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24827. }
  24828. // matricesIndices
  24829. var matricesIndices = parsedVertexData.matricesIndices;
  24830. if (matricesIndices) {
  24831. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24832. }
  24833. // matricesWeights
  24834. var matricesWeights = parsedVertexData.matricesWeights;
  24835. if (matricesWeights) {
  24836. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24837. }
  24838. // indices
  24839. var indices = parsedVertexData.indices;
  24840. if (indices) {
  24841. vertexData.indices = indices;
  24842. }
  24843. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24844. };
  24845. return VertexData;
  24846. })();
  24847. BABYLON.VertexData = VertexData;
  24848. })(BABYLON || (BABYLON = {}));
  24849. var BABYLON;
  24850. (function (BABYLON) {
  24851. var Tags = (function () {
  24852. function Tags() {
  24853. }
  24854. Tags.EnableFor = function (obj) {
  24855. obj._tags = obj._tags || {};
  24856. obj.hasTags = function () {
  24857. return Tags.HasTags(obj);
  24858. };
  24859. obj.addTags = function (tagsString) {
  24860. return Tags.AddTagsTo(obj, tagsString);
  24861. };
  24862. obj.removeTags = function (tagsString) {
  24863. return Tags.RemoveTagsFrom(obj, tagsString);
  24864. };
  24865. obj.matchesTagsQuery = function (tagsQuery) {
  24866. return Tags.MatchesQuery(obj, tagsQuery);
  24867. };
  24868. };
  24869. Tags.DisableFor = function (obj) {
  24870. delete obj._tags;
  24871. delete obj.hasTags;
  24872. delete obj.addTags;
  24873. delete obj.removeTags;
  24874. delete obj.matchesTagsQuery;
  24875. };
  24876. Tags.HasTags = function (obj) {
  24877. if (!obj._tags) {
  24878. return false;
  24879. }
  24880. return !BABYLON.Tools.IsEmpty(obj._tags);
  24881. };
  24882. Tags.GetTags = function (obj) {
  24883. if (!obj._tags) {
  24884. return null;
  24885. }
  24886. return obj._tags;
  24887. };
  24888. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24889. // a tag cannot start with '||', '&&', and '!'
  24890. // it cannot contain whitespaces
  24891. Tags.AddTagsTo = function (obj, tagsString) {
  24892. if (!tagsString) {
  24893. return;
  24894. }
  24895. if (typeof tagsString !== "string") {
  24896. return;
  24897. }
  24898. var tags = tagsString.split(" ");
  24899. for (var t in tags) {
  24900. Tags._AddTagTo(obj, tags[t]);
  24901. }
  24902. };
  24903. Tags._AddTagTo = function (obj, tag) {
  24904. tag = tag.trim();
  24905. if (tag === "" || tag === "true" || tag === "false") {
  24906. return;
  24907. }
  24908. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24909. return;
  24910. }
  24911. Tags.EnableFor(obj);
  24912. obj._tags[tag] = true;
  24913. };
  24914. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24915. if (!Tags.HasTags(obj)) {
  24916. return;
  24917. }
  24918. var tags = tagsString.split(" ");
  24919. for (var t in tags) {
  24920. Tags._RemoveTagFrom(obj, tags[t]);
  24921. }
  24922. };
  24923. Tags._RemoveTagFrom = function (obj, tag) {
  24924. delete obj._tags[tag];
  24925. };
  24926. Tags.MatchesQuery = function (obj, tagsQuery) {
  24927. if (tagsQuery === undefined) {
  24928. return true;
  24929. }
  24930. if (tagsQuery === "") {
  24931. return Tags.HasTags(obj);
  24932. }
  24933. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24934. };
  24935. return Tags;
  24936. })();
  24937. BABYLON.Tags = Tags;
  24938. })(BABYLON || (BABYLON = {}));
  24939. var BABYLON;
  24940. (function (BABYLON) {
  24941. var Internals;
  24942. (function (Internals) {
  24943. var AndOrNotEvaluator = (function () {
  24944. function AndOrNotEvaluator() {
  24945. }
  24946. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24947. if (!query.match(/\([^\(\)]*\)/g)) {
  24948. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24949. }
  24950. else {
  24951. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24952. // remove parenthesis
  24953. r = r.slice(1, r.length - 1);
  24954. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24955. });
  24956. }
  24957. if (query === "true") {
  24958. return true;
  24959. }
  24960. if (query === "false") {
  24961. return false;
  24962. }
  24963. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24964. };
  24965. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24966. evaluateCallback = evaluateCallback || (function (r) {
  24967. return r === "true" ? true : false;
  24968. });
  24969. var result;
  24970. var or = parenthesisContent.split("||");
  24971. for (var i in or) {
  24972. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24973. var and = ori.split("&&");
  24974. if (and.length > 1) {
  24975. for (var j = 0; j < and.length; ++j) {
  24976. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24977. if (andj !== "true" && andj !== "false") {
  24978. if (andj[0] === "!") {
  24979. result = !evaluateCallback(andj.substring(1));
  24980. }
  24981. else {
  24982. result = evaluateCallback(andj);
  24983. }
  24984. }
  24985. else {
  24986. result = andj === "true" ? true : false;
  24987. }
  24988. if (!result) {
  24989. ori = "false";
  24990. break;
  24991. }
  24992. }
  24993. }
  24994. if (result || ori === "true") {
  24995. result = true;
  24996. break;
  24997. }
  24998. // result equals false (or undefined)
  24999. if (ori !== "true" && ori !== "false") {
  25000. if (ori[0] === "!") {
  25001. result = !evaluateCallback(ori.substring(1));
  25002. }
  25003. else {
  25004. result = evaluateCallback(ori);
  25005. }
  25006. }
  25007. else {
  25008. result = ori === "true" ? true : false;
  25009. }
  25010. }
  25011. // the whole parenthesis scope is replaced by 'true' or 'false'
  25012. return result ? "true" : "false";
  25013. };
  25014. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25015. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25016. // remove whitespaces
  25017. r = r.replace(/[\s]/g, function () { return ""; });
  25018. return r.length % 2 ? "!" : "";
  25019. });
  25020. booleanString = booleanString.trim();
  25021. if (booleanString === "!true") {
  25022. booleanString = "false";
  25023. }
  25024. else if (booleanString === "!false") {
  25025. booleanString = "true";
  25026. }
  25027. return booleanString;
  25028. };
  25029. return AndOrNotEvaluator;
  25030. })();
  25031. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25032. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25033. })(BABYLON || (BABYLON = {}));
  25034. var BABYLON;
  25035. (function (BABYLON) {
  25036. var PostProcessRenderPass = (function () {
  25037. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25038. this._enabled = true;
  25039. this._refCount = 0;
  25040. this._name = name;
  25041. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25042. this.setRenderList(renderList);
  25043. this._renderTexture.onBeforeRender = beforeRender;
  25044. this._renderTexture.onAfterRender = afterRender;
  25045. this._scene = scene;
  25046. this._renderList = renderList;
  25047. }
  25048. // private
  25049. PostProcessRenderPass.prototype._incRefCount = function () {
  25050. if (this._refCount === 0) {
  25051. this._scene.customRenderTargets.push(this._renderTexture);
  25052. }
  25053. return ++this._refCount;
  25054. };
  25055. PostProcessRenderPass.prototype._decRefCount = function () {
  25056. this._refCount--;
  25057. if (this._refCount <= 0) {
  25058. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25059. }
  25060. return this._refCount;
  25061. };
  25062. PostProcessRenderPass.prototype._update = function () {
  25063. this.setRenderList(this._renderList);
  25064. };
  25065. // public
  25066. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25067. this._renderTexture.renderList = renderList;
  25068. };
  25069. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25070. return this._renderTexture;
  25071. };
  25072. return PostProcessRenderPass;
  25073. })();
  25074. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25075. })(BABYLON || (BABYLON = {}));
  25076. var BABYLON;
  25077. (function (BABYLON) {
  25078. var PostProcessRenderEffect = (function () {
  25079. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25080. this._engine = engine;
  25081. this._name = name;
  25082. this._singleInstance = singleInstance || true;
  25083. this._getPostProcess = getPostProcess;
  25084. this._cameras = [];
  25085. this._indicesForCamera = [];
  25086. this._postProcesses = {};
  25087. this._renderPasses = {};
  25088. this._renderEffectAsPasses = {};
  25089. }
  25090. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25091. get: function () {
  25092. for (var index in this._postProcesses) {
  25093. if (!this._postProcesses[index].isSupported) {
  25094. return false;
  25095. }
  25096. }
  25097. return true;
  25098. },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. PostProcessRenderEffect.prototype._update = function () {
  25103. for (var renderPassName in this._renderPasses) {
  25104. this._renderPasses[renderPassName]._update();
  25105. }
  25106. };
  25107. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25108. this._renderPasses[renderPass._name] = renderPass;
  25109. this._linkParameters();
  25110. };
  25111. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25112. delete this._renderPasses[renderPass._name];
  25113. this._linkParameters();
  25114. };
  25115. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25116. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25117. this._linkParameters();
  25118. };
  25119. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25120. for (var renderPassName in this._renderPasses) {
  25121. if (renderPassName === passName) {
  25122. return this._renderPasses[passName];
  25123. }
  25124. }
  25125. };
  25126. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25127. this._renderPasses = {};
  25128. this._linkParameters();
  25129. };
  25130. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25131. var cameraKey;
  25132. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25133. for (var i = 0; i < _cam.length; i++) {
  25134. var camera = _cam[i];
  25135. var cameraName = camera.name;
  25136. if (this._singleInstance) {
  25137. cameraKey = 0;
  25138. }
  25139. else {
  25140. cameraKey = cameraName;
  25141. }
  25142. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25143. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25144. if (!this._indicesForCamera[cameraName]) {
  25145. this._indicesForCamera[cameraName] = [];
  25146. }
  25147. this._indicesForCamera[cameraName].push(index);
  25148. if (this._cameras.indexOf(camera) === -1) {
  25149. this._cameras[cameraName] = camera;
  25150. }
  25151. for (var passName in this._renderPasses) {
  25152. this._renderPasses[passName]._incRefCount();
  25153. }
  25154. }
  25155. this._linkParameters();
  25156. };
  25157. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25158. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25159. for (var i = 0; i < _cam.length; i++) {
  25160. var camera = _cam[i];
  25161. var cameraName = camera.name;
  25162. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25163. var index = this._cameras.indexOf(cameraName);
  25164. this._indicesForCamera.splice(index, 1);
  25165. this._cameras.splice(index, 1);
  25166. for (var passName in this._renderPasses) {
  25167. this._renderPasses[passName]._decRefCount();
  25168. }
  25169. }
  25170. };
  25171. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25172. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25173. for (var i = 0; i < _cam.length; i++) {
  25174. var camera = _cam[i];
  25175. var cameraName = camera.name;
  25176. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25177. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25178. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25179. }
  25180. }
  25181. for (var passName in this._renderPasses) {
  25182. this._renderPasses[passName]._incRefCount();
  25183. }
  25184. }
  25185. };
  25186. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25187. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25188. for (var i = 0; i < _cam.length; i++) {
  25189. var camera = _cam[i];
  25190. var cameraName = camera.Name;
  25191. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25192. for (var passName in this._renderPasses) {
  25193. this._renderPasses[passName]._decRefCount();
  25194. }
  25195. }
  25196. };
  25197. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25198. if (this._singleInstance) {
  25199. return this._postProcesses[0];
  25200. }
  25201. else {
  25202. return this._postProcesses[camera.name];
  25203. }
  25204. };
  25205. PostProcessRenderEffect.prototype._linkParameters = function () {
  25206. var _this = this;
  25207. for (var index in this._postProcesses) {
  25208. if (this.applyParameters) {
  25209. this.applyParameters(this._postProcesses[index]);
  25210. }
  25211. this._postProcesses[index].onBeforeRender = function (effect) {
  25212. _this._linkTextures(effect);
  25213. };
  25214. }
  25215. };
  25216. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25217. for (var renderPassName in this._renderPasses) {
  25218. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25219. }
  25220. for (var renderEffectName in this._renderEffectAsPasses) {
  25221. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25222. }
  25223. };
  25224. return PostProcessRenderEffect;
  25225. })();
  25226. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25227. })(BABYLON || (BABYLON = {}));
  25228. var BABYLON;
  25229. (function (BABYLON) {
  25230. var PostProcessRenderPipeline = (function () {
  25231. function PostProcessRenderPipeline(engine, name) {
  25232. this._engine = engine;
  25233. this._name = name;
  25234. this._renderEffects = {};
  25235. this._renderEffectsForIsolatedPass = {};
  25236. this._cameras = [];
  25237. }
  25238. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25239. get: function () {
  25240. for (var renderEffectName in this._renderEffects) {
  25241. if (!this._renderEffects[renderEffectName].isSupported) {
  25242. return false;
  25243. }
  25244. }
  25245. return true;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25251. this._renderEffects[renderEffect._name] = renderEffect;
  25252. };
  25253. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25254. var renderEffects = this._renderEffects[renderEffectName];
  25255. if (!renderEffects) {
  25256. return;
  25257. }
  25258. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25259. };
  25260. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25261. var renderEffects = this._renderEffects[renderEffectName];
  25262. if (!renderEffects) {
  25263. return;
  25264. }
  25265. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25266. };
  25267. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25268. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25269. var indicesToDelete = [];
  25270. var i;
  25271. for (i = 0; i < _cam.length; i++) {
  25272. var camera = _cam[i];
  25273. var cameraName = camera.name;
  25274. if (this._cameras.indexOf(camera) === -1) {
  25275. this._cameras[cameraName] = camera;
  25276. }
  25277. else if (unique) {
  25278. indicesToDelete.push(i);
  25279. }
  25280. }
  25281. for (i = 0; i < indicesToDelete.length; i++) {
  25282. cameras.splice(indicesToDelete[i], 1);
  25283. }
  25284. for (var renderEffectName in this._renderEffects) {
  25285. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25286. }
  25287. };
  25288. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25289. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25290. for (var renderEffectName in this._renderEffects) {
  25291. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25292. }
  25293. for (var i = 0; i < _cam.length; i++) {
  25294. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25295. }
  25296. };
  25297. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25298. var _this = this;
  25299. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25300. var pass = null;
  25301. var renderEffectName;
  25302. for (renderEffectName in this._renderEffects) {
  25303. pass = this._renderEffects[renderEffectName].getPass(passName);
  25304. if (pass != null) {
  25305. break;
  25306. }
  25307. }
  25308. if (pass === null) {
  25309. return;
  25310. }
  25311. for (renderEffectName in this._renderEffects) {
  25312. this._renderEffects[renderEffectName]._disable(_cam);
  25313. }
  25314. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25315. for (var i = 0; i < _cam.length; i++) {
  25316. var camera = _cam[i];
  25317. var cameraName = camera.name;
  25318. 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); });
  25319. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25320. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25321. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25322. }
  25323. };
  25324. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25325. var _this = this;
  25326. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25327. for (var i = 0; i < _cam.length; i++) {
  25328. var camera = _cam[i];
  25329. var cameraName = camera.name;
  25330. 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); });
  25331. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25332. }
  25333. for (var renderEffectName in this._renderEffects) {
  25334. this._renderEffects[renderEffectName]._enable(_cam);
  25335. }
  25336. };
  25337. PostProcessRenderPipeline.prototype._update = function () {
  25338. for (var renderEffectName in this._renderEffects) {
  25339. this._renderEffects[renderEffectName]._update();
  25340. }
  25341. for (var i = 0; i < this._cameras.length; i++) {
  25342. var cameraName = this._cameras[i].name;
  25343. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25344. this._renderEffectsForIsolatedPass[cameraName]._update();
  25345. }
  25346. }
  25347. };
  25348. PostProcessRenderPipeline.prototype.dispose = function () {
  25349. // Must be implemented by children
  25350. };
  25351. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25352. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25353. return PostProcessRenderPipeline;
  25354. })();
  25355. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25356. })(BABYLON || (BABYLON = {}));
  25357. var BABYLON;
  25358. (function (BABYLON) {
  25359. var PostProcessRenderPipelineManager = (function () {
  25360. function PostProcessRenderPipelineManager() {
  25361. this._renderPipelines = {};
  25362. }
  25363. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25364. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25365. };
  25366. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25367. var renderPipeline = this._renderPipelines[renderPipelineName];
  25368. if (!renderPipeline) {
  25369. return;
  25370. }
  25371. renderPipeline._attachCameras(cameras, unique);
  25372. };
  25373. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25374. var renderPipeline = this._renderPipelines[renderPipelineName];
  25375. if (!renderPipeline) {
  25376. return;
  25377. }
  25378. renderPipeline._detachCameras(cameras);
  25379. };
  25380. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25381. var renderPipeline = this._renderPipelines[renderPipelineName];
  25382. if (!renderPipeline) {
  25383. return;
  25384. }
  25385. renderPipeline._enableEffect(renderEffectName, cameras);
  25386. };
  25387. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25388. var renderPipeline = this._renderPipelines[renderPipelineName];
  25389. if (!renderPipeline) {
  25390. return;
  25391. }
  25392. renderPipeline._disableEffect(renderEffectName, cameras);
  25393. };
  25394. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25395. var renderPipeline = this._renderPipelines[renderPipelineName];
  25396. if (!renderPipeline) {
  25397. return;
  25398. }
  25399. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25400. };
  25401. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25402. var renderPipeline = this._renderPipelines[renderPipelineName];
  25403. if (!renderPipeline) {
  25404. return;
  25405. }
  25406. renderPipeline._disableDisplayOnlyPass(cameras);
  25407. };
  25408. PostProcessRenderPipelineManager.prototype.update = function () {
  25409. for (var renderPipelineName in this._renderPipelines) {
  25410. var pipeline = this._renderPipelines[renderPipelineName];
  25411. if (!pipeline.isSupported) {
  25412. pipeline.dispose();
  25413. delete this._renderPipelines[renderPipelineName];
  25414. }
  25415. else {
  25416. pipeline._update();
  25417. }
  25418. }
  25419. };
  25420. return PostProcessRenderPipelineManager;
  25421. })();
  25422. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25423. })(BABYLON || (BABYLON = {}));
  25424. var BABYLON;
  25425. (function (BABYLON) {
  25426. var BoundingBoxRenderer = (function () {
  25427. function BoundingBoxRenderer(scene) {
  25428. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25429. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25430. this.showBackLines = true;
  25431. this.renderList = new BABYLON.SmartArray(32);
  25432. this._scene = scene;
  25433. }
  25434. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25435. if (this._colorShader) {
  25436. return;
  25437. }
  25438. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25439. attributes: ["position"],
  25440. uniforms: ["worldViewProjection", "color"]
  25441. });
  25442. var engine = this._scene.getEngine();
  25443. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25444. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25445. 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]);
  25446. };
  25447. BoundingBoxRenderer.prototype.reset = function () {
  25448. this.renderList.reset();
  25449. };
  25450. BoundingBoxRenderer.prototype.render = function () {
  25451. if (this.renderList.length === 0) {
  25452. return;
  25453. }
  25454. this._prepareRessources();
  25455. if (!this._colorShader.isReady()) {
  25456. return;
  25457. }
  25458. var engine = this._scene.getEngine();
  25459. engine.setDepthWrite(false);
  25460. this._colorShader._preBind();
  25461. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25462. var boundingBox = this.renderList.data[boundingBoxIndex];
  25463. var min = boundingBox.minimum;
  25464. var max = boundingBox.maximum;
  25465. var diff = max.subtract(min);
  25466. var median = min.add(diff.scale(0.5));
  25467. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25468. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25469. .multiply(boundingBox.getWorldMatrix());
  25470. // VBOs
  25471. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25472. if (this.showBackLines) {
  25473. // Back
  25474. engine.setDepthFunctionToGreaterOrEqual();
  25475. this._scene.resetCachedMaterial();
  25476. this._colorShader.setColor4("color", this.backColor.toColor4());
  25477. this._colorShader.bind(worldMatrix);
  25478. // Draw order
  25479. engine.draw(false, 0, 24);
  25480. }
  25481. // Front
  25482. engine.setDepthFunctionToLess();
  25483. this._scene.resetCachedMaterial();
  25484. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25485. this._colorShader.bind(worldMatrix);
  25486. // Draw order
  25487. engine.draw(false, 0, 24);
  25488. }
  25489. this._colorShader.unbind();
  25490. engine.setDepthFunctionToLessOrEqual();
  25491. engine.setDepthWrite(true);
  25492. };
  25493. BoundingBoxRenderer.prototype.dispose = function () {
  25494. if (!this._colorShader) {
  25495. return;
  25496. }
  25497. this._colorShader.dispose();
  25498. this._vb.dispose();
  25499. this._scene.getEngine()._releaseBuffer(this._ib);
  25500. };
  25501. return BoundingBoxRenderer;
  25502. })();
  25503. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25504. })(BABYLON || (BABYLON = {}));
  25505. var BABYLON;
  25506. (function (BABYLON) {
  25507. var Condition = (function () {
  25508. function Condition(actionManager) {
  25509. this._actionManager = actionManager;
  25510. }
  25511. Condition.prototype.isValid = function () {
  25512. return true;
  25513. };
  25514. Condition.prototype._getProperty = function (propertyPath) {
  25515. return this._actionManager._getProperty(propertyPath);
  25516. };
  25517. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25518. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25519. };
  25520. return Condition;
  25521. })();
  25522. BABYLON.Condition = Condition;
  25523. var ValueCondition = (function (_super) {
  25524. __extends(ValueCondition, _super);
  25525. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25526. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25527. _super.call(this, actionManager);
  25528. this.propertyPath = propertyPath;
  25529. this.value = value;
  25530. this.operator = operator;
  25531. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25532. this._property = this._getProperty(this.propertyPath);
  25533. }
  25534. Object.defineProperty(ValueCondition, "IsEqual", {
  25535. get: function () {
  25536. return ValueCondition._IsEqual;
  25537. },
  25538. enumerable: true,
  25539. configurable: true
  25540. });
  25541. Object.defineProperty(ValueCondition, "IsDifferent", {
  25542. get: function () {
  25543. return ValueCondition._IsDifferent;
  25544. },
  25545. enumerable: true,
  25546. configurable: true
  25547. });
  25548. Object.defineProperty(ValueCondition, "IsGreater", {
  25549. get: function () {
  25550. return ValueCondition._IsGreater;
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. Object.defineProperty(ValueCondition, "IsLesser", {
  25556. get: function () {
  25557. return ValueCondition._IsLesser;
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. // Methods
  25563. ValueCondition.prototype.isValid = function () {
  25564. switch (this.operator) {
  25565. case ValueCondition.IsGreater:
  25566. return this._target[this._property] > this.value;
  25567. case ValueCondition.IsLesser:
  25568. return this._target[this._property] < this.value;
  25569. case ValueCondition.IsEqual:
  25570. case ValueCondition.IsDifferent:
  25571. var check;
  25572. if (this.value.equals) {
  25573. check = this.value.equals(this._target[this._property]);
  25574. }
  25575. else {
  25576. check = this.value === this._target[this._property];
  25577. }
  25578. return this.operator === ValueCondition.IsEqual ? check : !check;
  25579. }
  25580. return false;
  25581. };
  25582. // Statics
  25583. ValueCondition._IsEqual = 0;
  25584. ValueCondition._IsDifferent = 1;
  25585. ValueCondition._IsGreater = 2;
  25586. ValueCondition._IsLesser = 3;
  25587. return ValueCondition;
  25588. })(Condition);
  25589. BABYLON.ValueCondition = ValueCondition;
  25590. var PredicateCondition = (function (_super) {
  25591. __extends(PredicateCondition, _super);
  25592. function PredicateCondition(actionManager, predicate) {
  25593. _super.call(this, actionManager);
  25594. this.predicate = predicate;
  25595. }
  25596. PredicateCondition.prototype.isValid = function () {
  25597. return this.predicate();
  25598. };
  25599. return PredicateCondition;
  25600. })(Condition);
  25601. BABYLON.PredicateCondition = PredicateCondition;
  25602. var StateCondition = (function (_super) {
  25603. __extends(StateCondition, _super);
  25604. function StateCondition(actionManager, target, value) {
  25605. _super.call(this, actionManager);
  25606. this.value = value;
  25607. this._target = target;
  25608. }
  25609. // Methods
  25610. StateCondition.prototype.isValid = function () {
  25611. return this._target.state === this.value;
  25612. };
  25613. return StateCondition;
  25614. })(Condition);
  25615. BABYLON.StateCondition = StateCondition;
  25616. })(BABYLON || (BABYLON = {}));
  25617. var BABYLON;
  25618. (function (BABYLON) {
  25619. var Action = (function () {
  25620. function Action(triggerOptions, condition) {
  25621. this.triggerOptions = triggerOptions;
  25622. if (triggerOptions.parameter) {
  25623. this.trigger = triggerOptions.trigger;
  25624. this._triggerParameter = triggerOptions.parameter;
  25625. }
  25626. else {
  25627. this.trigger = triggerOptions;
  25628. }
  25629. this._nextActiveAction = this;
  25630. this._condition = condition;
  25631. }
  25632. // Methods
  25633. Action.prototype._prepare = function () {
  25634. };
  25635. Action.prototype.getTriggerParameter = function () {
  25636. return this._triggerParameter;
  25637. };
  25638. Action.prototype._executeCurrent = function (evt) {
  25639. if (this._nextActiveAction._condition) {
  25640. var condition = this._nextActiveAction._condition;
  25641. var currentRenderId = this._actionManager.getScene().getRenderId();
  25642. // We cache the current evaluation for the current frame
  25643. if (condition._evaluationId === currentRenderId) {
  25644. if (!condition._currentResult) {
  25645. return;
  25646. }
  25647. }
  25648. else {
  25649. condition._evaluationId = currentRenderId;
  25650. if (!condition.isValid()) {
  25651. condition._currentResult = false;
  25652. return;
  25653. }
  25654. condition._currentResult = true;
  25655. }
  25656. }
  25657. this._nextActiveAction.execute(evt);
  25658. this.skipToNextActiveAction();
  25659. };
  25660. Action.prototype.execute = function (evt) {
  25661. };
  25662. Action.prototype.skipToNextActiveAction = function () {
  25663. if (this._nextActiveAction._child) {
  25664. if (!this._nextActiveAction._child._actionManager) {
  25665. this._nextActiveAction._child._actionManager = this._actionManager;
  25666. }
  25667. this._nextActiveAction = this._nextActiveAction._child;
  25668. }
  25669. else {
  25670. this._nextActiveAction = this;
  25671. }
  25672. };
  25673. Action.prototype.then = function (action) {
  25674. this._child = action;
  25675. action._actionManager = this._actionManager;
  25676. action._prepare();
  25677. return action;
  25678. };
  25679. Action.prototype._getProperty = function (propertyPath) {
  25680. return this._actionManager._getProperty(propertyPath);
  25681. };
  25682. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25683. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25684. };
  25685. return Action;
  25686. })();
  25687. BABYLON.Action = Action;
  25688. })(BABYLON || (BABYLON = {}));
  25689. var BABYLON;
  25690. (function (BABYLON) {
  25691. /**
  25692. * ActionEvent is the event beint sent when an action is triggered.
  25693. */
  25694. var ActionEvent = (function () {
  25695. /**
  25696. * @constructor
  25697. * @param source The mesh or sprite that triggered the action.
  25698. * @param pointerX The X mouse cursor position at the time of the event
  25699. * @param pointerY The Y mouse cursor position at the time of the event
  25700. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25701. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25702. */
  25703. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25704. this.source = source;
  25705. this.pointerX = pointerX;
  25706. this.pointerY = pointerY;
  25707. this.meshUnderPointer = meshUnderPointer;
  25708. this.sourceEvent = sourceEvent;
  25709. this.additionalData = additionalData;
  25710. }
  25711. /**
  25712. * Helper function to auto-create an ActionEvent from a source mesh.
  25713. * @param source The source mesh that triggered the event
  25714. * @param evt {Event} The original (browser) event
  25715. */
  25716. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25717. var scene = source.getScene();
  25718. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25719. };
  25720. /**
  25721. * Helper function to auto-create an ActionEvent from a source mesh.
  25722. * @param source The source sprite that triggered the event
  25723. * @param scene Scene associated with the sprite
  25724. * @param evt {Event} The original (browser) event
  25725. */
  25726. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25727. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25728. };
  25729. /**
  25730. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25731. * @param scene the scene where the event occurred
  25732. * @param evt {Event} The original (browser) event
  25733. */
  25734. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25735. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25736. };
  25737. return ActionEvent;
  25738. })();
  25739. BABYLON.ActionEvent = ActionEvent;
  25740. /**
  25741. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25742. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25743. */
  25744. var ActionManager = (function () {
  25745. function ActionManager(scene) {
  25746. // Members
  25747. this.actions = new Array();
  25748. this._scene = scene;
  25749. scene._actionManagers.push(this);
  25750. }
  25751. Object.defineProperty(ActionManager, "NothingTrigger", {
  25752. get: function () {
  25753. return ActionManager._NothingTrigger;
  25754. },
  25755. enumerable: true,
  25756. configurable: true
  25757. });
  25758. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25759. get: function () {
  25760. return ActionManager._OnPickTrigger;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25766. get: function () {
  25767. return ActionManager._OnLeftPickTrigger;
  25768. },
  25769. enumerable: true,
  25770. configurable: true
  25771. });
  25772. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25773. get: function () {
  25774. return ActionManager._OnRightPickTrigger;
  25775. },
  25776. enumerable: true,
  25777. configurable: true
  25778. });
  25779. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25780. get: function () {
  25781. return ActionManager._OnCenterPickTrigger;
  25782. },
  25783. enumerable: true,
  25784. configurable: true
  25785. });
  25786. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  25787. get: function () {
  25788. return ActionManager._OnPickDownTrigger;
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25794. get: function () {
  25795. return ActionManager._OnPickUpTrigger;
  25796. },
  25797. enumerable: true,
  25798. configurable: true
  25799. });
  25800. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  25801. get: function () {
  25802. return ActionManager._OnLongPressTrigger;
  25803. },
  25804. enumerable: true,
  25805. configurable: true
  25806. });
  25807. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25808. get: function () {
  25809. return ActionManager._OnPointerOverTrigger;
  25810. },
  25811. enumerable: true,
  25812. configurable: true
  25813. });
  25814. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25815. get: function () {
  25816. return ActionManager._OnPointerOutTrigger;
  25817. },
  25818. enumerable: true,
  25819. configurable: true
  25820. });
  25821. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25822. get: function () {
  25823. return ActionManager._OnEveryFrameTrigger;
  25824. },
  25825. enumerable: true,
  25826. configurable: true
  25827. });
  25828. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25829. get: function () {
  25830. return ActionManager._OnIntersectionEnterTrigger;
  25831. },
  25832. enumerable: true,
  25833. configurable: true
  25834. });
  25835. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25836. get: function () {
  25837. return ActionManager._OnIntersectionExitTrigger;
  25838. },
  25839. enumerable: true,
  25840. configurable: true
  25841. });
  25842. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25843. get: function () {
  25844. return ActionManager._OnKeyDownTrigger;
  25845. },
  25846. enumerable: true,
  25847. configurable: true
  25848. });
  25849. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25850. get: function () {
  25851. return ActionManager._OnKeyUpTrigger;
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. // Methods
  25857. ActionManager.prototype.dispose = function () {
  25858. var index = this._scene._actionManagers.indexOf(this);
  25859. if (index > -1) {
  25860. this._scene._actionManagers.splice(index, 1);
  25861. }
  25862. };
  25863. ActionManager.prototype.getScene = function () {
  25864. return this._scene;
  25865. };
  25866. /**
  25867. * Does this action manager handles actions of any of the given triggers
  25868. * @param {number[]} triggers - the triggers to be tested
  25869. * @return {boolean} whether one (or more) of the triggers is handeled
  25870. */
  25871. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25872. for (var index = 0; index < this.actions.length; index++) {
  25873. var action = this.actions[index];
  25874. if (triggers.indexOf(action.trigger) > -1) {
  25875. return true;
  25876. }
  25877. }
  25878. return false;
  25879. };
  25880. /**
  25881. * Does this action manager handles actions of a given trigger
  25882. * @param {number} trigger - the trigger to be tested
  25883. * @return {boolean} whether the trigger is handeled
  25884. */
  25885. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25886. for (var index = 0; index < this.actions.length; index++) {
  25887. var action = this.actions[index];
  25888. if (action.trigger === trigger) {
  25889. return true;
  25890. }
  25891. }
  25892. return false;
  25893. };
  25894. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25895. /**
  25896. * Does this action manager has pointer triggers
  25897. * @return {boolean} whether or not it has pointer triggers
  25898. */
  25899. get: function () {
  25900. for (var index = 0; index < this.actions.length; index++) {
  25901. var action = this.actions[index];
  25902. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25903. return true;
  25904. }
  25905. }
  25906. return false;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25912. /**
  25913. * Does this action manager has pick triggers
  25914. * @return {boolean} whether or not it has pick triggers
  25915. */
  25916. get: function () {
  25917. for (var index = 0; index < this.actions.length; index++) {
  25918. var action = this.actions[index];
  25919. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  25920. return true;
  25921. }
  25922. }
  25923. return false;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. /**
  25929. * Registers an action to this action manager
  25930. * @param {BABYLON.Action} action - the action to be registered
  25931. * @return {BABYLON.Action} the action amended (prepared) after registration
  25932. */
  25933. ActionManager.prototype.registerAction = function (action) {
  25934. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25935. if (this.getScene().actionManager !== this) {
  25936. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25937. return null;
  25938. }
  25939. }
  25940. this.actions.push(action);
  25941. action._actionManager = this;
  25942. action._prepare();
  25943. return action;
  25944. };
  25945. /**
  25946. * Process a specific trigger
  25947. * @param {number} trigger - the trigger to process
  25948. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25949. */
  25950. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25951. for (var index = 0; index < this.actions.length; index++) {
  25952. var action = this.actions[index];
  25953. if (action.trigger === trigger) {
  25954. if (trigger === ActionManager.OnKeyUpTrigger
  25955. || trigger === ActionManager.OnKeyDownTrigger) {
  25956. var parameter = action.getTriggerParameter();
  25957. if (parameter) {
  25958. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25959. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25960. if (actualkey !== parameter.toLowerCase()) {
  25961. continue;
  25962. }
  25963. }
  25964. }
  25965. action._executeCurrent(evt);
  25966. }
  25967. }
  25968. };
  25969. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25970. var properties = propertyPath.split(".");
  25971. for (var index = 0; index < properties.length - 1; index++) {
  25972. target = target[properties[index]];
  25973. }
  25974. return target;
  25975. };
  25976. ActionManager.prototype._getProperty = function (propertyPath) {
  25977. var properties = propertyPath.split(".");
  25978. return properties[properties.length - 1];
  25979. };
  25980. ActionManager.Parse = function (parsedActions, object, scene) {
  25981. var actionManager = new BABYLON.ActionManager(scene);
  25982. if (object === null)
  25983. scene.actionManager = actionManager;
  25984. else
  25985. object.actionManager = actionManager;
  25986. // instanciate a new object
  25987. var instanciate = function (name, params) {
  25988. var newInstance = Object.create(BABYLON[name].prototype);
  25989. newInstance.constructor.apply(newInstance, params);
  25990. return newInstance;
  25991. };
  25992. var parseParameter = function (name, value, target, propertyPath) {
  25993. if (propertyPath === null) {
  25994. // String, boolean or float
  25995. var floatValue = parseFloat(value);
  25996. if (value === "true" || value === "false")
  25997. return value === "true";
  25998. else
  25999. return isNaN(floatValue) ? value : floatValue;
  26000. }
  26001. var effectiveTarget = propertyPath.split(".");
  26002. var values = value.split(",");
  26003. // Get effective Target
  26004. for (var i = 0; i < effectiveTarget.length; i++) {
  26005. target = target[effectiveTarget[i]];
  26006. }
  26007. // Return appropriate value with its type
  26008. if (typeof (target) === "boolean")
  26009. return values[0] === "true";
  26010. if (typeof (target) === "string")
  26011. return values[0];
  26012. // Parameters with multiple values such as Vector3 etc.
  26013. var split = new Array();
  26014. for (var i = 0; i < values.length; i++)
  26015. split.push(parseFloat(values[i]));
  26016. if (target instanceof BABYLON.Vector3)
  26017. return BABYLON.Vector3.FromArray(split);
  26018. if (target instanceof BABYLON.Vector4)
  26019. return BABYLON.Vector4.FromArray(split);
  26020. if (target instanceof BABYLON.Color3)
  26021. return BABYLON.Color3.FromArray(split);
  26022. if (target instanceof BABYLON.Color4)
  26023. return BABYLON.Color4.FromArray(split);
  26024. return parseFloat(values[0]);
  26025. };
  26026. // traverse graph per trigger
  26027. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26028. if (combineArray === void 0) { combineArray = null; }
  26029. if (parsedAction.detached)
  26030. return;
  26031. var parameters = new Array();
  26032. var target = null;
  26033. var propertyPath = null;
  26034. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26035. // Parameters
  26036. if (parsedAction.type === 2)
  26037. parameters.push(actionManager);
  26038. else
  26039. parameters.push(trigger);
  26040. if (combine) {
  26041. var actions = new Array();
  26042. for (var j = 0; j < parsedAction.combine.length; j++) {
  26043. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26044. }
  26045. parameters.push(actions);
  26046. }
  26047. else {
  26048. for (var i = 0; i < parsedAction.properties.length; i++) {
  26049. var value = parsedAction.properties[i].value;
  26050. var name = parsedAction.properties[i].name;
  26051. var targetType = parsedAction.properties[i].targetType;
  26052. if (name === "target")
  26053. if (targetType !== null && targetType === "SceneProperties")
  26054. value = target = scene;
  26055. else
  26056. value = target = scene.getNodeByName(value);
  26057. else if (name === "parent")
  26058. value = scene.getNodeByName(value);
  26059. else if (name === "sound")
  26060. value = scene.getSoundByName(value);
  26061. else if (name !== "propertyPath") {
  26062. if (parsedAction.type === 2 && name === "operator")
  26063. value = BABYLON.ValueCondition[value];
  26064. else
  26065. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26066. }
  26067. else {
  26068. propertyPath = value;
  26069. }
  26070. parameters.push(value);
  26071. }
  26072. }
  26073. if (combineArray === null) {
  26074. parameters.push(condition);
  26075. }
  26076. else {
  26077. parameters.push(null);
  26078. }
  26079. // If interpolate value action
  26080. if (parsedAction.name === "InterpolateValueAction") {
  26081. var param = parameters[parameters.length - 2];
  26082. parameters[parameters.length - 1] = param;
  26083. parameters[parameters.length - 2] = condition;
  26084. }
  26085. // Action or condition(s) and not CombineAction
  26086. var newAction = instanciate(parsedAction.name, parameters);
  26087. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26088. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26089. if (action)
  26090. action.then(nothing);
  26091. else
  26092. actionManager.registerAction(nothing);
  26093. action = nothing;
  26094. }
  26095. if (combineArray === null) {
  26096. if (newAction instanceof BABYLON.Condition) {
  26097. condition = newAction;
  26098. newAction = action;
  26099. }
  26100. else {
  26101. condition = null;
  26102. if (action)
  26103. action.then(newAction);
  26104. else
  26105. actionManager.registerAction(newAction);
  26106. }
  26107. }
  26108. else {
  26109. combineArray.push(newAction);
  26110. }
  26111. for (var i = 0; i < parsedAction.children.length; i++)
  26112. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26113. };
  26114. // triggers
  26115. for (var i = 0; i < parsedActions.children.length; i++) {
  26116. var triggerParams;
  26117. var trigger = parsedActions.children[i];
  26118. if (trigger.properties.length > 0) {
  26119. var param = trigger.properties[0].value;
  26120. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26121. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26122. }
  26123. else
  26124. triggerParams = BABYLON.ActionManager[trigger.name];
  26125. for (var j = 0; j < trigger.children.length; j++) {
  26126. if (!trigger.detached)
  26127. traverse(trigger.children[j], triggerParams, null, null);
  26128. }
  26129. }
  26130. };
  26131. // Statics
  26132. ActionManager._NothingTrigger = 0;
  26133. ActionManager._OnPickTrigger = 1;
  26134. ActionManager._OnLeftPickTrigger = 2;
  26135. ActionManager._OnRightPickTrigger = 3;
  26136. ActionManager._OnCenterPickTrigger = 4;
  26137. ActionManager._OnPickDownTrigger = 5;
  26138. ActionManager._OnPickUpTrigger = 6;
  26139. ActionManager._OnLongPressTrigger = 7;
  26140. ActionManager._OnPointerOverTrigger = 8;
  26141. ActionManager._OnPointerOutTrigger = 9;
  26142. ActionManager._OnEveryFrameTrigger = 10;
  26143. ActionManager._OnIntersectionEnterTrigger = 11;
  26144. ActionManager._OnIntersectionExitTrigger = 12;
  26145. ActionManager._OnKeyDownTrigger = 13;
  26146. ActionManager._OnKeyUpTrigger = 14;
  26147. ActionManager.DragMovementThreshold = 10; // in pixels
  26148. ActionManager.LongPressDelay = 500; // in milliseconds
  26149. return ActionManager;
  26150. })();
  26151. BABYLON.ActionManager = ActionManager;
  26152. })(BABYLON || (BABYLON = {}));
  26153. var BABYLON;
  26154. (function (BABYLON) {
  26155. var InterpolateValueAction = (function (_super) {
  26156. __extends(InterpolateValueAction, _super);
  26157. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26158. if (duration === void 0) { duration = 1000; }
  26159. _super.call(this, triggerOptions, condition);
  26160. this.propertyPath = propertyPath;
  26161. this.value = value;
  26162. this.duration = duration;
  26163. this.stopOtherAnimations = stopOtherAnimations;
  26164. this.onInterpolationDone = onInterpolationDone;
  26165. this._target = target;
  26166. }
  26167. InterpolateValueAction.prototype._prepare = function () {
  26168. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26169. this._property = this._getProperty(this.propertyPath);
  26170. };
  26171. InterpolateValueAction.prototype.execute = function () {
  26172. var scene = this._actionManager.getScene();
  26173. var keys = [
  26174. {
  26175. frame: 0,
  26176. value: this._target[this._property]
  26177. }, {
  26178. frame: 100,
  26179. value: this.value
  26180. }
  26181. ];
  26182. var dataType;
  26183. if (typeof this.value === "number") {
  26184. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26185. }
  26186. else if (this.value instanceof BABYLON.Color3) {
  26187. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26188. }
  26189. else if (this.value instanceof BABYLON.Vector3) {
  26190. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26191. }
  26192. else if (this.value instanceof BABYLON.Matrix) {
  26193. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26194. }
  26195. else if (this.value instanceof BABYLON.Quaternion) {
  26196. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26197. }
  26198. else {
  26199. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26200. return;
  26201. }
  26202. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26203. animation.setKeys(keys);
  26204. if (this.stopOtherAnimations) {
  26205. scene.stopAnimation(this._target);
  26206. }
  26207. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26208. };
  26209. return InterpolateValueAction;
  26210. })(BABYLON.Action);
  26211. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26212. })(BABYLON || (BABYLON = {}));
  26213. var BABYLON;
  26214. (function (BABYLON) {
  26215. var SwitchBooleanAction = (function (_super) {
  26216. __extends(SwitchBooleanAction, _super);
  26217. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26218. _super.call(this, triggerOptions, condition);
  26219. this.propertyPath = propertyPath;
  26220. this._target = target;
  26221. }
  26222. SwitchBooleanAction.prototype._prepare = function () {
  26223. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26224. this._property = this._getProperty(this.propertyPath);
  26225. };
  26226. SwitchBooleanAction.prototype.execute = function () {
  26227. this._target[this._property] = !this._target[this._property];
  26228. };
  26229. return SwitchBooleanAction;
  26230. })(BABYLON.Action);
  26231. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26232. var SetStateAction = (function (_super) {
  26233. __extends(SetStateAction, _super);
  26234. function SetStateAction(triggerOptions, target, value, condition) {
  26235. _super.call(this, triggerOptions, condition);
  26236. this.value = value;
  26237. this._target = target;
  26238. }
  26239. SetStateAction.prototype.execute = function () {
  26240. this._target.state = this.value;
  26241. };
  26242. return SetStateAction;
  26243. })(BABYLON.Action);
  26244. BABYLON.SetStateAction = SetStateAction;
  26245. var SetValueAction = (function (_super) {
  26246. __extends(SetValueAction, _super);
  26247. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26248. _super.call(this, triggerOptions, condition);
  26249. this.propertyPath = propertyPath;
  26250. this.value = value;
  26251. this._target = target;
  26252. }
  26253. SetValueAction.prototype._prepare = function () {
  26254. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26255. this._property = this._getProperty(this.propertyPath);
  26256. };
  26257. SetValueAction.prototype.execute = function () {
  26258. this._target[this._property] = this.value;
  26259. };
  26260. return SetValueAction;
  26261. })(BABYLON.Action);
  26262. BABYLON.SetValueAction = SetValueAction;
  26263. var IncrementValueAction = (function (_super) {
  26264. __extends(IncrementValueAction, _super);
  26265. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26266. _super.call(this, triggerOptions, condition);
  26267. this.propertyPath = propertyPath;
  26268. this.value = value;
  26269. this._target = target;
  26270. }
  26271. IncrementValueAction.prototype._prepare = function () {
  26272. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26273. this._property = this._getProperty(this.propertyPath);
  26274. if (typeof this._target[this._property] !== "number") {
  26275. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26276. }
  26277. };
  26278. IncrementValueAction.prototype.execute = function () {
  26279. this._target[this._property] += this.value;
  26280. };
  26281. return IncrementValueAction;
  26282. })(BABYLON.Action);
  26283. BABYLON.IncrementValueAction = IncrementValueAction;
  26284. var PlayAnimationAction = (function (_super) {
  26285. __extends(PlayAnimationAction, _super);
  26286. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26287. _super.call(this, triggerOptions, condition);
  26288. this.from = from;
  26289. this.to = to;
  26290. this.loop = loop;
  26291. this._target = target;
  26292. }
  26293. PlayAnimationAction.prototype._prepare = function () {
  26294. };
  26295. PlayAnimationAction.prototype.execute = function () {
  26296. var scene = this._actionManager.getScene();
  26297. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26298. };
  26299. return PlayAnimationAction;
  26300. })(BABYLON.Action);
  26301. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26302. var StopAnimationAction = (function (_super) {
  26303. __extends(StopAnimationAction, _super);
  26304. function StopAnimationAction(triggerOptions, target, condition) {
  26305. _super.call(this, triggerOptions, condition);
  26306. this._target = target;
  26307. }
  26308. StopAnimationAction.prototype._prepare = function () {
  26309. };
  26310. StopAnimationAction.prototype.execute = function () {
  26311. var scene = this._actionManager.getScene();
  26312. scene.stopAnimation(this._target);
  26313. };
  26314. return StopAnimationAction;
  26315. })(BABYLON.Action);
  26316. BABYLON.StopAnimationAction = StopAnimationAction;
  26317. var DoNothingAction = (function (_super) {
  26318. __extends(DoNothingAction, _super);
  26319. function DoNothingAction(triggerOptions, condition) {
  26320. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26321. _super.call(this, triggerOptions, condition);
  26322. }
  26323. DoNothingAction.prototype.execute = function () {
  26324. };
  26325. return DoNothingAction;
  26326. })(BABYLON.Action);
  26327. BABYLON.DoNothingAction = DoNothingAction;
  26328. var CombineAction = (function (_super) {
  26329. __extends(CombineAction, _super);
  26330. function CombineAction(triggerOptions, children, condition) {
  26331. _super.call(this, triggerOptions, condition);
  26332. this.children = children;
  26333. }
  26334. CombineAction.prototype._prepare = function () {
  26335. for (var index = 0; index < this.children.length; index++) {
  26336. this.children[index]._actionManager = this._actionManager;
  26337. this.children[index]._prepare();
  26338. }
  26339. };
  26340. CombineAction.prototype.execute = function (evt) {
  26341. for (var index = 0; index < this.children.length; index++) {
  26342. this.children[index].execute(evt);
  26343. }
  26344. };
  26345. return CombineAction;
  26346. })(BABYLON.Action);
  26347. BABYLON.CombineAction = CombineAction;
  26348. var ExecuteCodeAction = (function (_super) {
  26349. __extends(ExecuteCodeAction, _super);
  26350. function ExecuteCodeAction(triggerOptions, func, condition) {
  26351. _super.call(this, triggerOptions, condition);
  26352. this.func = func;
  26353. }
  26354. ExecuteCodeAction.prototype.execute = function (evt) {
  26355. this.func(evt);
  26356. };
  26357. return ExecuteCodeAction;
  26358. })(BABYLON.Action);
  26359. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26360. var SetParentAction = (function (_super) {
  26361. __extends(SetParentAction, _super);
  26362. function SetParentAction(triggerOptions, target, parent, condition) {
  26363. _super.call(this, triggerOptions, condition);
  26364. this._target = target;
  26365. this._parent = parent;
  26366. }
  26367. SetParentAction.prototype._prepare = function () {
  26368. };
  26369. SetParentAction.prototype.execute = function () {
  26370. if (this._target.parent === this._parent) {
  26371. return;
  26372. }
  26373. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26374. invertParentWorldMatrix.invert();
  26375. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26376. this._target.parent = this._parent;
  26377. };
  26378. return SetParentAction;
  26379. })(BABYLON.Action);
  26380. BABYLON.SetParentAction = SetParentAction;
  26381. var PlaySoundAction = (function (_super) {
  26382. __extends(PlaySoundAction, _super);
  26383. function PlaySoundAction(triggerOptions, sound, condition) {
  26384. _super.call(this, triggerOptions, condition);
  26385. this._sound = sound;
  26386. }
  26387. PlaySoundAction.prototype._prepare = function () {
  26388. };
  26389. PlaySoundAction.prototype.execute = function () {
  26390. if (this._sound !== undefined)
  26391. this._sound.play();
  26392. };
  26393. return PlaySoundAction;
  26394. })(BABYLON.Action);
  26395. BABYLON.PlaySoundAction = PlaySoundAction;
  26396. var StopSoundAction = (function (_super) {
  26397. __extends(StopSoundAction, _super);
  26398. function StopSoundAction(triggerOptions, sound, condition) {
  26399. _super.call(this, triggerOptions, condition);
  26400. this._sound = sound;
  26401. }
  26402. StopSoundAction.prototype._prepare = function () {
  26403. };
  26404. StopSoundAction.prototype.execute = function () {
  26405. if (this._sound !== undefined)
  26406. this._sound.stop();
  26407. };
  26408. return StopSoundAction;
  26409. })(BABYLON.Action);
  26410. BABYLON.StopSoundAction = StopSoundAction;
  26411. })(BABYLON || (BABYLON = {}));
  26412. var BABYLON;
  26413. (function (BABYLON) {
  26414. var Geometry = (function () {
  26415. function Geometry(id, scene, vertexData, updatable, mesh) {
  26416. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26417. this._totalVertices = 0;
  26418. this._isDisposed = false;
  26419. this.id = id;
  26420. this._engine = scene.getEngine();
  26421. this._meshes = [];
  26422. this._scene = scene;
  26423. //Init vertex buffer cache
  26424. this._vertexBuffers = {};
  26425. this._indices = [];
  26426. // vertexData
  26427. if (vertexData) {
  26428. this.setAllVerticesData(vertexData, updatable);
  26429. }
  26430. else {
  26431. this._totalVertices = 0;
  26432. this._indices = [];
  26433. }
  26434. // applyToMesh
  26435. if (mesh) {
  26436. this.applyToMesh(mesh);
  26437. mesh.computeWorldMatrix(true);
  26438. }
  26439. }
  26440. Object.defineProperty(Geometry.prototype, "extend", {
  26441. get: function () {
  26442. return this._extend;
  26443. },
  26444. enumerable: true,
  26445. configurable: true
  26446. });
  26447. Geometry.prototype.getScene = function () {
  26448. return this._scene;
  26449. };
  26450. Geometry.prototype.getEngine = function () {
  26451. return this._engine;
  26452. };
  26453. Geometry.prototype.isReady = function () {
  26454. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26455. };
  26456. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26457. vertexData.applyToGeometry(this, updatable);
  26458. this.notifyUpdate();
  26459. };
  26460. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26461. if (this._vertexBuffers[kind]) {
  26462. this._vertexBuffers[kind].dispose();
  26463. }
  26464. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26465. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26466. stride = this._vertexBuffers[kind].getStrideSize();
  26467. this._totalVertices = data.length / stride;
  26468. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26469. var meshes = this._meshes;
  26470. var numOfMeshes = meshes.length;
  26471. for (var index = 0; index < numOfMeshes; index++) {
  26472. var mesh = meshes[index];
  26473. mesh._resetPointsArrayCache();
  26474. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26475. mesh._createGlobalSubMesh();
  26476. mesh.computeWorldMatrix(true);
  26477. }
  26478. }
  26479. this.notifyUpdate(kind);
  26480. };
  26481. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26482. var vertexBuffer = this.getVertexBuffer(kind);
  26483. if (!vertexBuffer) {
  26484. return;
  26485. }
  26486. vertexBuffer.updateDirectly(data, offset);
  26487. this.notifyUpdate(kind);
  26488. };
  26489. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26490. var vertexBuffer = this.getVertexBuffer(kind);
  26491. if (!vertexBuffer) {
  26492. return;
  26493. }
  26494. vertexBuffer.update(data);
  26495. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26496. var stride = vertexBuffer.getStrideSize();
  26497. this._totalVertices = data.length / stride;
  26498. if (updateExtends) {
  26499. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26500. }
  26501. var meshes = this._meshes;
  26502. var numOfMeshes = meshes.length;
  26503. for (var index = 0; index < numOfMeshes; index++) {
  26504. var mesh = meshes[index];
  26505. mesh._resetPointsArrayCache();
  26506. if (updateExtends) {
  26507. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26508. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26509. var subMesh = mesh.subMeshes[subIndex];
  26510. subMesh.refreshBoundingInfo();
  26511. }
  26512. }
  26513. }
  26514. }
  26515. this.notifyUpdate(kind);
  26516. };
  26517. Geometry.prototype.getTotalVertices = function () {
  26518. if (!this.isReady()) {
  26519. return 0;
  26520. }
  26521. return this._totalVertices;
  26522. };
  26523. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26524. var vertexBuffer = this.getVertexBuffer(kind);
  26525. if (!vertexBuffer) {
  26526. return null;
  26527. }
  26528. var orig = vertexBuffer.getData();
  26529. if (!copyWhenShared || this._meshes.length === 1) {
  26530. return orig;
  26531. }
  26532. else {
  26533. var len = orig.length;
  26534. var copy = [];
  26535. for (var i = 0; i < len; i++) {
  26536. copy.push(orig[i]);
  26537. }
  26538. return copy;
  26539. }
  26540. };
  26541. Geometry.prototype.getVertexBuffer = function (kind) {
  26542. if (!this.isReady()) {
  26543. return null;
  26544. }
  26545. return this._vertexBuffers[kind];
  26546. };
  26547. Geometry.prototype.getVertexBuffers = function () {
  26548. if (!this.isReady()) {
  26549. return null;
  26550. }
  26551. return this._vertexBuffers;
  26552. };
  26553. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26554. if (!this._vertexBuffers) {
  26555. if (this._delayInfo) {
  26556. return this._delayInfo.indexOf(kind) !== -1;
  26557. }
  26558. return false;
  26559. }
  26560. return this._vertexBuffers[kind] !== undefined;
  26561. };
  26562. Geometry.prototype.getVerticesDataKinds = function () {
  26563. var result = [];
  26564. var kind;
  26565. if (!this._vertexBuffers && this._delayInfo) {
  26566. for (kind in this._delayInfo) {
  26567. result.push(kind);
  26568. }
  26569. }
  26570. else {
  26571. for (kind in this._vertexBuffers) {
  26572. result.push(kind);
  26573. }
  26574. }
  26575. return result;
  26576. };
  26577. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26578. if (this._indexBuffer) {
  26579. this._engine._releaseBuffer(this._indexBuffer);
  26580. }
  26581. this._indices = indices;
  26582. if (this._meshes.length !== 0 && this._indices) {
  26583. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26584. }
  26585. if (totalVertices !== undefined) {
  26586. this._totalVertices = totalVertices;
  26587. }
  26588. var meshes = this._meshes;
  26589. var numOfMeshes = meshes.length;
  26590. for (var index = 0; index < numOfMeshes; index++) {
  26591. meshes[index]._createGlobalSubMesh();
  26592. }
  26593. this.notifyUpdate();
  26594. };
  26595. Geometry.prototype.getTotalIndices = function () {
  26596. if (!this.isReady()) {
  26597. return 0;
  26598. }
  26599. return this._indices.length;
  26600. };
  26601. Geometry.prototype.getIndices = function (copyWhenShared) {
  26602. if (!this.isReady()) {
  26603. return null;
  26604. }
  26605. var orig = this._indices;
  26606. if (!copyWhenShared || this._meshes.length === 1) {
  26607. return orig;
  26608. }
  26609. else {
  26610. var len = orig.length;
  26611. var copy = [];
  26612. for (var i = 0; i < len; i++) {
  26613. copy.push(orig[i]);
  26614. }
  26615. return copy;
  26616. }
  26617. };
  26618. Geometry.prototype.getIndexBuffer = function () {
  26619. if (!this.isReady()) {
  26620. return null;
  26621. }
  26622. return this._indexBuffer;
  26623. };
  26624. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26625. var meshes = this._meshes;
  26626. var index = meshes.indexOf(mesh);
  26627. if (index === -1) {
  26628. return;
  26629. }
  26630. for (var kind in this._vertexBuffers) {
  26631. this._vertexBuffers[kind].dispose();
  26632. }
  26633. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26634. this._indexBuffer = null;
  26635. }
  26636. meshes.splice(index, 1);
  26637. mesh._geometry = null;
  26638. if (meshes.length === 0 && shouldDispose) {
  26639. this.dispose();
  26640. }
  26641. };
  26642. Geometry.prototype.applyToMesh = function (mesh) {
  26643. if (mesh._geometry === this) {
  26644. return;
  26645. }
  26646. var previousGeometry = mesh._geometry;
  26647. if (previousGeometry) {
  26648. previousGeometry.releaseForMesh(mesh);
  26649. }
  26650. var meshes = this._meshes;
  26651. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26652. mesh._geometry = this;
  26653. this._scene.pushGeometry(this);
  26654. meshes.push(mesh);
  26655. if (this.isReady()) {
  26656. this._applyToMesh(mesh);
  26657. }
  26658. else {
  26659. mesh._boundingInfo = this._boundingInfo;
  26660. }
  26661. };
  26662. Geometry.prototype._applyToMesh = function (mesh) {
  26663. var numOfMeshes = this._meshes.length;
  26664. // vertexBuffers
  26665. for (var kind in this._vertexBuffers) {
  26666. if (numOfMeshes === 1) {
  26667. this._vertexBuffers[kind].create();
  26668. }
  26669. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26670. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26671. mesh._resetPointsArrayCache();
  26672. if (!this._extend) {
  26673. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26674. }
  26675. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26676. mesh._createGlobalSubMesh();
  26677. //bounding info was just created again, world matrix should be applied again.
  26678. mesh._updateBoundingInfo();
  26679. }
  26680. }
  26681. // indexBuffer
  26682. if (numOfMeshes === 1 && this._indices) {
  26683. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26684. }
  26685. if (this._indexBuffer) {
  26686. this._indexBuffer.references = numOfMeshes;
  26687. }
  26688. };
  26689. Geometry.prototype.notifyUpdate = function (kind) {
  26690. if (this.onGeometryUpdated) {
  26691. this.onGeometryUpdated(this, kind);
  26692. }
  26693. };
  26694. Geometry.prototype.load = function (scene, onLoaded) {
  26695. var _this = this;
  26696. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26697. return;
  26698. }
  26699. if (this.isReady()) {
  26700. if (onLoaded) {
  26701. onLoaded();
  26702. }
  26703. return;
  26704. }
  26705. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26706. scene._addPendingData(this);
  26707. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26708. _this._delayLoadingFunction(JSON.parse(data), _this);
  26709. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26710. _this._delayInfo = [];
  26711. scene._removePendingData(_this);
  26712. var meshes = _this._meshes;
  26713. var numOfMeshes = meshes.length;
  26714. for (var index = 0; index < numOfMeshes; index++) {
  26715. _this._applyToMesh(meshes[index]);
  26716. }
  26717. if (onLoaded) {
  26718. onLoaded();
  26719. }
  26720. }, function () { }, scene.database);
  26721. };
  26722. Geometry.prototype.isDisposed = function () {
  26723. return this._isDisposed;
  26724. };
  26725. Geometry.prototype.dispose = function () {
  26726. var meshes = this._meshes;
  26727. var numOfMeshes = meshes.length;
  26728. var index;
  26729. for (index = 0; index < numOfMeshes; index++) {
  26730. this.releaseForMesh(meshes[index]);
  26731. }
  26732. this._meshes = [];
  26733. for (var kind in this._vertexBuffers) {
  26734. this._vertexBuffers[kind].dispose();
  26735. }
  26736. this._vertexBuffers = [];
  26737. this._totalVertices = 0;
  26738. if (this._indexBuffer) {
  26739. this._engine._releaseBuffer(this._indexBuffer);
  26740. }
  26741. this._indexBuffer = null;
  26742. this._indices = [];
  26743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26744. this.delayLoadingFile = null;
  26745. this._delayLoadingFunction = null;
  26746. this._delayInfo = [];
  26747. this._boundingInfo = null;
  26748. this._scene.removeGeometry(this);
  26749. this._isDisposed = true;
  26750. };
  26751. Geometry.prototype.copy = function (id) {
  26752. var vertexData = new BABYLON.VertexData();
  26753. vertexData.indices = [];
  26754. var indices = this.getIndices();
  26755. for (var index = 0; index < indices.length; index++) {
  26756. vertexData.indices.push(indices[index]);
  26757. }
  26758. var updatable = false;
  26759. var stopChecking = false;
  26760. var kind;
  26761. for (kind in this._vertexBuffers) {
  26762. // using slice() to make a copy of the array and not just reference it
  26763. var data = this.getVerticesData(kind);
  26764. if (data instanceof Float32Array) {
  26765. vertexData.set(new Float32Array(data), kind);
  26766. }
  26767. else {
  26768. vertexData.set(data.slice(0), kind);
  26769. }
  26770. if (!stopChecking) {
  26771. updatable = this.getVertexBuffer(kind).isUpdatable();
  26772. stopChecking = !updatable;
  26773. }
  26774. }
  26775. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26776. geometry.delayLoadState = this.delayLoadState;
  26777. geometry.delayLoadingFile = this.delayLoadingFile;
  26778. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26779. for (kind in this._delayInfo) {
  26780. geometry._delayInfo = geometry._delayInfo || [];
  26781. geometry._delayInfo.push(kind);
  26782. }
  26783. // Bounding info
  26784. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26785. return geometry;
  26786. };
  26787. Geometry.prototype.serialize = function () {
  26788. var serializationObject = {};
  26789. serializationObject.id = this.id;
  26790. if (BABYLON.Tags.HasTags(this)) {
  26791. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26792. }
  26793. return serializationObject;
  26794. };
  26795. Geometry.prototype.serializeVerticeData = function () {
  26796. var serializationObject = this.serialize();
  26797. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26798. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26799. }
  26800. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26801. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26802. }
  26803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26804. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26805. }
  26806. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26807. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26808. }
  26809. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26810. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26811. }
  26812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26813. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26814. }
  26815. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26816. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26817. }
  26818. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26819. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26820. }
  26821. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26822. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26823. }
  26824. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26825. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26826. serializationObject.matricesIndices._isExpanded = true;
  26827. }
  26828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26829. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26830. }
  26831. serializationObject.indices = this.getIndices();
  26832. return serializationObject;
  26833. };
  26834. // Statics
  26835. Geometry.ExtractFromMesh = function (mesh, id) {
  26836. var geometry = mesh._geometry;
  26837. if (!geometry) {
  26838. return null;
  26839. }
  26840. return geometry.copy(id);
  26841. };
  26842. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26843. // be aware Math.random() could cause collisions
  26844. Geometry.RandomId = function () {
  26845. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26846. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26847. return v.toString(16);
  26848. });
  26849. };
  26850. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26851. var scene = mesh.getScene();
  26852. // Geometry
  26853. var geometryId = parsedGeometry.geometryId;
  26854. if (geometryId) {
  26855. var geometry = scene.getGeometryByID(geometryId);
  26856. if (geometry) {
  26857. geometry.applyToMesh(mesh);
  26858. }
  26859. }
  26860. else if (parsedGeometry instanceof ArrayBuffer) {
  26861. var binaryInfo = mesh._binaryInfo;
  26862. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26863. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26864. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26865. }
  26866. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26867. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26868. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26869. }
  26870. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26871. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26872. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26873. }
  26874. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26875. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26876. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26877. }
  26878. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26879. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26880. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26881. }
  26882. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26883. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26884. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26885. }
  26886. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26887. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26888. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26889. }
  26890. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26891. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26892. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26893. }
  26894. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26895. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26896. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26897. }
  26898. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26899. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26900. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26901. }
  26902. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26903. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26905. }
  26906. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26907. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26908. mesh.setIndices(indicesData);
  26909. }
  26910. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26911. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26912. mesh.subMeshes = [];
  26913. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26914. var materialIndex = subMeshesData[(i * 5) + 0];
  26915. var verticesStart = subMeshesData[(i * 5) + 1];
  26916. var verticesCount = subMeshesData[(i * 5) + 2];
  26917. var indexStart = subMeshesData[(i * 5) + 3];
  26918. var indexCount = subMeshesData[(i * 5) + 4];
  26919. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26920. }
  26921. }
  26922. }
  26923. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26924. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26925. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26926. if (parsedGeometry.uvs) {
  26927. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26928. }
  26929. if (parsedGeometry.uvs2) {
  26930. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26931. }
  26932. if (parsedGeometry.uvs3) {
  26933. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26934. }
  26935. if (parsedGeometry.uvs4) {
  26936. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26937. }
  26938. if (parsedGeometry.uvs5) {
  26939. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26940. }
  26941. if (parsedGeometry.uvs6) {
  26942. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26943. }
  26944. if (parsedGeometry.colors) {
  26945. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26946. }
  26947. if (parsedGeometry.matricesIndices) {
  26948. if (!parsedGeometry.matricesIndices._isExpanded) {
  26949. var floatIndices = [];
  26950. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26951. var matricesIndex = parsedGeometry.matricesIndices[i];
  26952. floatIndices.push(matricesIndex & 0x000000FF);
  26953. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26954. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26955. floatIndices.push(matricesIndex >> 24);
  26956. }
  26957. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26958. }
  26959. else {
  26960. delete parsedGeometry.matricesIndices._isExpanded;
  26961. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26962. }
  26963. }
  26964. if (parsedGeometry.matricesIndicesExtra) {
  26965. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26966. var floatIndices = [];
  26967. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26968. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26969. floatIndices.push(matricesIndex & 0x000000FF);
  26970. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26971. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26972. floatIndices.push(matricesIndex >> 24);
  26973. }
  26974. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26975. }
  26976. else {
  26977. delete parsedGeometry.matricesIndices._isExpanded;
  26978. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26979. }
  26980. }
  26981. if (parsedGeometry.matricesWeights) {
  26982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26983. }
  26984. if (parsedGeometry.matricesWeightsExtra) {
  26985. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26986. }
  26987. mesh.setIndices(parsedGeometry.indices);
  26988. }
  26989. // SubMeshes
  26990. if (parsedGeometry.subMeshes) {
  26991. mesh.subMeshes = [];
  26992. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26993. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26994. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26995. }
  26996. }
  26997. // Flat shading
  26998. if (mesh._shouldGenerateFlatShading) {
  26999. mesh.convertToFlatShadedMesh();
  27000. delete mesh._shouldGenerateFlatShading;
  27001. }
  27002. // Update
  27003. mesh.computeWorldMatrix(true);
  27004. // Octree
  27005. if (scene['_selectionOctree']) {
  27006. scene['_selectionOctree'].addMesh(mesh);
  27007. }
  27008. };
  27009. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27010. if (scene.getGeometryByID(parsedVertexData.id)) {
  27011. return null; // null since geometry could be something else than a box...
  27012. }
  27013. var geometry = new Geometry(parsedVertexData.id, scene);
  27014. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27015. if (parsedVertexData.delayLoadingFile) {
  27016. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27017. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27018. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27019. geometry._delayInfo = [];
  27020. if (parsedVertexData.hasUVs) {
  27021. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27022. }
  27023. if (parsedVertexData.hasUVs2) {
  27024. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27025. }
  27026. if (parsedVertexData.hasUVs3) {
  27027. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27028. }
  27029. if (parsedVertexData.hasUVs4) {
  27030. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27031. }
  27032. if (parsedVertexData.hasUVs5) {
  27033. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27034. }
  27035. if (parsedVertexData.hasUVs6) {
  27036. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27037. }
  27038. if (parsedVertexData.hasColors) {
  27039. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27040. }
  27041. if (parsedVertexData.hasMatricesIndices) {
  27042. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27043. }
  27044. if (parsedVertexData.hasMatricesWeights) {
  27045. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27046. }
  27047. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27048. }
  27049. else {
  27050. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27051. }
  27052. scene.pushGeometry(geometry, true);
  27053. return geometry;
  27054. };
  27055. return Geometry;
  27056. })();
  27057. BABYLON.Geometry = Geometry;
  27058. /////// Primitives //////////////////////////////////////////////
  27059. var Geometry;
  27060. (function (Geometry) {
  27061. var Primitives;
  27062. (function (Primitives) {
  27063. /// Abstract class
  27064. var _Primitive = (function (_super) {
  27065. __extends(_Primitive, _super);
  27066. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27067. this._beingRegenerated = true;
  27068. this._canBeRegenerated = canBeRegenerated;
  27069. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27070. this._beingRegenerated = false;
  27071. }
  27072. _Primitive.prototype.canBeRegenerated = function () {
  27073. return this._canBeRegenerated;
  27074. };
  27075. _Primitive.prototype.regenerate = function () {
  27076. if (!this._canBeRegenerated) {
  27077. return;
  27078. }
  27079. this._beingRegenerated = true;
  27080. this.setAllVerticesData(this._regenerateVertexData(), false);
  27081. this._beingRegenerated = false;
  27082. };
  27083. _Primitive.prototype.asNewGeometry = function (id) {
  27084. return _super.prototype.copy.call(this, id);
  27085. };
  27086. // overrides
  27087. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27088. if (!this._beingRegenerated) {
  27089. return;
  27090. }
  27091. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27092. };
  27093. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27094. if (!this._beingRegenerated) {
  27095. return;
  27096. }
  27097. _super.prototype.setVerticesData.call(this, kind, data, false);
  27098. };
  27099. // to override
  27100. // protected
  27101. _Primitive.prototype._regenerateVertexData = function () {
  27102. throw new Error("Abstract method");
  27103. };
  27104. _Primitive.prototype.copy = function (id) {
  27105. throw new Error("Must be overriden in sub-classes.");
  27106. };
  27107. _Primitive.prototype.serialize = function () {
  27108. var serializationObject = _super.prototype.serialize.call(this);
  27109. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27110. return serializationObject;
  27111. };
  27112. return _Primitive;
  27113. })(Geometry);
  27114. Primitives._Primitive = _Primitive;
  27115. var Ribbon = (function (_super) {
  27116. __extends(Ribbon, _super);
  27117. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27118. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27119. this.pathArray = pathArray;
  27120. this.closeArray = closeArray;
  27121. this.closePath = closePath;
  27122. this.offset = offset;
  27123. this.side = side;
  27124. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27125. }
  27126. Ribbon.prototype._regenerateVertexData = function () {
  27127. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27128. };
  27129. Ribbon.prototype.copy = function (id) {
  27130. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27131. };
  27132. return Ribbon;
  27133. })(_Primitive);
  27134. Primitives.Ribbon = Ribbon;
  27135. var Box = (function (_super) {
  27136. __extends(Box, _super);
  27137. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27138. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27139. this.size = size;
  27140. this.side = side;
  27141. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27142. }
  27143. Box.prototype._regenerateVertexData = function () {
  27144. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27145. };
  27146. Box.prototype.copy = function (id) {
  27147. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27148. };
  27149. Box.prototype.serialize = function () {
  27150. var serializationObject = _super.prototype.serialize.call(this);
  27151. serializationObject.size = this.size;
  27152. return serializationObject;
  27153. };
  27154. Box.Parse = function (parsedBox, scene) {
  27155. if (scene.getGeometryByID(parsedBox.id)) {
  27156. return null; // null since geometry could be something else than a box...
  27157. }
  27158. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27159. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27160. scene.pushGeometry(box, true);
  27161. return box;
  27162. };
  27163. return Box;
  27164. })(_Primitive);
  27165. Primitives.Box = Box;
  27166. var Sphere = (function (_super) {
  27167. __extends(Sphere, _super);
  27168. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27169. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27170. this.segments = segments;
  27171. this.diameter = diameter;
  27172. this.side = side;
  27173. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27174. }
  27175. Sphere.prototype._regenerateVertexData = function () {
  27176. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27177. };
  27178. Sphere.prototype.copy = function (id) {
  27179. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27180. };
  27181. Sphere.prototype.serialize = function () {
  27182. var serializationObject = _super.prototype.serialize.call(this);
  27183. serializationObject.segments = this.segments;
  27184. serializationObject.diameter = this.diameter;
  27185. return serializationObject;
  27186. };
  27187. Sphere.Parse = function (parsedSphere, scene) {
  27188. if (scene.getGeometryByID(parsedSphere.id)) {
  27189. return null; // null since geometry could be something else than a sphere...
  27190. }
  27191. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27192. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27193. scene.pushGeometry(sphere, true);
  27194. return sphere;
  27195. };
  27196. return Sphere;
  27197. })(_Primitive);
  27198. Primitives.Sphere = Sphere;
  27199. var Disc = (function (_super) {
  27200. __extends(Disc, _super);
  27201. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27202. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27203. this.radius = radius;
  27204. this.tessellation = tessellation;
  27205. this.side = side;
  27206. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27207. }
  27208. Disc.prototype._regenerateVertexData = function () {
  27209. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27210. };
  27211. Disc.prototype.copy = function (id) {
  27212. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27213. };
  27214. return Disc;
  27215. })(_Primitive);
  27216. Primitives.Disc = Disc;
  27217. var Cylinder = (function (_super) {
  27218. __extends(Cylinder, _super);
  27219. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27220. if (subdivisions === void 0) { subdivisions = 1; }
  27221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27222. this.height = height;
  27223. this.diameterTop = diameterTop;
  27224. this.diameterBottom = diameterBottom;
  27225. this.tessellation = tessellation;
  27226. this.subdivisions = subdivisions;
  27227. this.side = side;
  27228. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27229. }
  27230. Cylinder.prototype._regenerateVertexData = function () {
  27231. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27232. };
  27233. Cylinder.prototype.copy = function (id) {
  27234. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27235. };
  27236. Cylinder.prototype.serialize = function () {
  27237. var serializationObject = _super.prototype.serialize.call(this);
  27238. serializationObject.height = this.height;
  27239. serializationObject.diameterTop = this.diameterTop;
  27240. serializationObject.diameterBottom = this.diameterBottom;
  27241. serializationObject.tessellation = this.tessellation;
  27242. return serializationObject;
  27243. };
  27244. Cylinder.Parse = function (parsedCylinder, scene) {
  27245. if (scene.getGeometryByID(parsedCylinder.id)) {
  27246. return null; // null since geometry could be something else than a cylinder...
  27247. }
  27248. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27249. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27250. scene.pushGeometry(cylinder, true);
  27251. return cylinder;
  27252. };
  27253. return Cylinder;
  27254. })(_Primitive);
  27255. Primitives.Cylinder = Cylinder;
  27256. var Torus = (function (_super) {
  27257. __extends(Torus, _super);
  27258. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27259. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27260. this.diameter = diameter;
  27261. this.thickness = thickness;
  27262. this.tessellation = tessellation;
  27263. this.side = side;
  27264. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27265. }
  27266. Torus.prototype._regenerateVertexData = function () {
  27267. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27268. };
  27269. Torus.prototype.copy = function (id) {
  27270. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27271. };
  27272. Torus.prototype.serialize = function () {
  27273. var serializationObject = _super.prototype.serialize.call(this);
  27274. serializationObject.diameter = this.diameter;
  27275. serializationObject.thickness = this.thickness;
  27276. serializationObject.tessellation = this.tessellation;
  27277. return serializationObject;
  27278. };
  27279. Torus.Parse = function (parsedTorus, scene) {
  27280. if (scene.getGeometryByID(parsedTorus.id)) {
  27281. return null; // null since geometry could be something else than a torus...
  27282. }
  27283. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27284. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27285. scene.pushGeometry(torus, true);
  27286. return torus;
  27287. };
  27288. return Torus;
  27289. })(_Primitive);
  27290. Primitives.Torus = Torus;
  27291. var Ground = (function (_super) {
  27292. __extends(Ground, _super);
  27293. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27294. this.width = width;
  27295. this.height = height;
  27296. this.subdivisions = subdivisions;
  27297. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27298. }
  27299. Ground.prototype._regenerateVertexData = function () {
  27300. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27301. };
  27302. Ground.prototype.copy = function (id) {
  27303. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27304. };
  27305. Ground.prototype.serialize = function () {
  27306. var serializationObject = _super.prototype.serialize.call(this);
  27307. serializationObject.width = this.width;
  27308. serializationObject.height = this.height;
  27309. serializationObject.subdivisions = this.subdivisions;
  27310. return serializationObject;
  27311. };
  27312. Ground.Parse = function (parsedGround, scene) {
  27313. if (scene.getGeometryByID(parsedGround.id)) {
  27314. return null; // null since geometry could be something else than a ground...
  27315. }
  27316. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27317. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27318. scene.pushGeometry(ground, true);
  27319. return ground;
  27320. };
  27321. return Ground;
  27322. })(_Primitive);
  27323. Primitives.Ground = Ground;
  27324. var TiledGround = (function (_super) {
  27325. __extends(TiledGround, _super);
  27326. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27327. this.xmin = xmin;
  27328. this.zmin = zmin;
  27329. this.xmax = xmax;
  27330. this.zmax = zmax;
  27331. this.subdivisions = subdivisions;
  27332. this.precision = precision;
  27333. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27334. }
  27335. TiledGround.prototype._regenerateVertexData = function () {
  27336. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27337. };
  27338. TiledGround.prototype.copy = function (id) {
  27339. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27340. };
  27341. return TiledGround;
  27342. })(_Primitive);
  27343. Primitives.TiledGround = TiledGround;
  27344. var Plane = (function (_super) {
  27345. __extends(Plane, _super);
  27346. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27347. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27348. this.size = size;
  27349. this.side = side;
  27350. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27351. }
  27352. Plane.prototype._regenerateVertexData = function () {
  27353. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27354. };
  27355. Plane.prototype.copy = function (id) {
  27356. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27357. };
  27358. Plane.prototype.serialize = function () {
  27359. var serializationObject = _super.prototype.serialize.call(this);
  27360. serializationObject.size = this.size;
  27361. return serializationObject;
  27362. };
  27363. Plane.Parse = function (parsedPlane, scene) {
  27364. if (scene.getGeometryByID(parsedPlane.id)) {
  27365. return null; // null since geometry could be something else than a ground...
  27366. }
  27367. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27368. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27369. scene.pushGeometry(plane, true);
  27370. return plane;
  27371. };
  27372. return Plane;
  27373. })(_Primitive);
  27374. Primitives.Plane = Plane;
  27375. var TorusKnot = (function (_super) {
  27376. __extends(TorusKnot, _super);
  27377. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27378. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27379. this.radius = radius;
  27380. this.tube = tube;
  27381. this.radialSegments = radialSegments;
  27382. this.tubularSegments = tubularSegments;
  27383. this.p = p;
  27384. this.q = q;
  27385. this.side = side;
  27386. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27387. }
  27388. TorusKnot.prototype._regenerateVertexData = function () {
  27389. 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 });
  27390. };
  27391. TorusKnot.prototype.copy = function (id) {
  27392. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27393. };
  27394. TorusKnot.prototype.serialize = function () {
  27395. var serializationObject = _super.prototype.serialize.call(this);
  27396. serializationObject.radius = this.radius;
  27397. serializationObject.tube = this.tube;
  27398. serializationObject.radialSegments = this.radialSegments;
  27399. serializationObject.tubularSegments = this.tubularSegments;
  27400. serializationObject.p = this.p;
  27401. serializationObject.q = this.q;
  27402. return serializationObject;
  27403. };
  27404. ;
  27405. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27406. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27407. return null; // null since geometry could be something else than a ground...
  27408. }
  27409. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27410. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27411. scene.pushGeometry(torusKnot, true);
  27412. return torusKnot;
  27413. };
  27414. return TorusKnot;
  27415. })(_Primitive);
  27416. Primitives.TorusKnot = TorusKnot;
  27417. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27418. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27419. })(BABYLON || (BABYLON = {}));
  27420. var BABYLON;
  27421. (function (BABYLON) {
  27422. var GroundMesh = (function (_super) {
  27423. __extends(GroundMesh, _super);
  27424. function GroundMesh(name, scene) {
  27425. _super.call(this, name, scene);
  27426. this.generateOctree = false;
  27427. this._worldInverse = new BABYLON.Matrix();
  27428. }
  27429. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27430. get: function () {
  27431. return this._subdivisions;
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27437. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27438. this._subdivisions = chunksCount;
  27439. this.subdivide(this._subdivisions);
  27440. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27441. };
  27442. /**
  27443. * Returns a height (y) value in the Worl system :
  27444. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27445. * Returns the ground y position if (x, z) are outside the ground surface.
  27446. * Not pertinent if the ground is rotated.
  27447. */
  27448. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27449. // express x and y in the ground local system
  27450. x -= this.position.x;
  27451. z -= this.position.z;
  27452. x /= this.scaling.x;
  27453. z /= this.scaling.z;
  27454. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27455. return this.position.y;
  27456. }
  27457. if (!this._heightQuads || this._heightQuads.length == 0) {
  27458. this._computeHeightQuads();
  27459. }
  27460. var facet = this._getFacetAt(x, z);
  27461. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27462. // return y in the World system
  27463. return y * this.scaling.y + this.position.y;
  27464. };
  27465. /**
  27466. * Returns a normalized vector (Vector3) orthogonal to the ground
  27467. * at the ground coordinates (x, z) expressed in the World system.
  27468. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27469. * Not pertinent if the ground is rotated.
  27470. */
  27471. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27472. var normal = new BABYLON.Vector3(0, 1, 0);
  27473. this.getNormalAtCoordinatesToRef(x, z, normal);
  27474. return normal;
  27475. };
  27476. /**
  27477. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27478. * at the ground coordinates (x, z) expressed in the World system.
  27479. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27480. * Not pertinent if the ground is rotated.
  27481. */
  27482. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27483. // express x and y in the ground local system
  27484. x -= this.position.x;
  27485. z -= this.position.z;
  27486. x /= this.scaling.x;
  27487. z /= this.scaling.z;
  27488. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27489. return;
  27490. }
  27491. if (!this._heightQuads || this._heightQuads.length == 0) {
  27492. this._computeHeightQuads();
  27493. }
  27494. var facet = this._getFacetAt(x, z);
  27495. ref.x = facet.x;
  27496. ref.y = facet.y;
  27497. ref.z = facet.z;
  27498. };
  27499. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27500. GroundMesh.prototype._getFacetAt = function (x, z) {
  27501. // retrieve col and row from x, z coordinates in the ground local system
  27502. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27503. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27504. var quad = this._heightQuads[row * this._subdivisions + col];
  27505. var facet;
  27506. if (z < quad.slope.x * x + quad.slope.y) {
  27507. facet = quad.facet1;
  27508. }
  27509. else {
  27510. facet = quad.facet2;
  27511. }
  27512. return facet;
  27513. };
  27514. // Populates the heightMap array with "facet" elements :
  27515. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27516. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27517. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  27518. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  27519. GroundMesh.prototype._computeHeightQuads = function () {
  27520. this._heightQuads = new Array();
  27521. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27522. var v1 = BABYLON.Vector3.Zero();
  27523. var v2 = BABYLON.Vector3.Zero();
  27524. var v3 = BABYLON.Vector3.Zero();
  27525. var v4 = BABYLON.Vector3.Zero();
  27526. var v1v2 = BABYLON.Vector3.Zero();
  27527. var v1v3 = BABYLON.Vector3.Zero();
  27528. var v1v4 = BABYLON.Vector3.Zero();
  27529. var norm1 = BABYLON.Vector3.Zero();
  27530. var norm2 = BABYLON.Vector3.Zero();
  27531. var i = 0;
  27532. var j = 0;
  27533. var k = 0;
  27534. var cd = 0; // 2D slope coefficient : z = cd * x + h
  27535. var h = 0;
  27536. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  27537. var d2 = 0;
  27538. for (var row = 0; row < this._subdivisions; row++) {
  27539. for (var col = 0; col < this._subdivisions; col++) {
  27540. i = col * 3;
  27541. j = row * (this._subdivisions + 1) * 3;
  27542. k = (row + 1) * (this._subdivisions + 1) * 3;
  27543. v1.x = positions[j + i];
  27544. v1.y = positions[j + i + 1];
  27545. v1.z = positions[j + i + 2];
  27546. v2.x = positions[j + i + 3];
  27547. v2.y = positions[j + i + 4];
  27548. v2.z = positions[j + i + 5];
  27549. v3.x = positions[k + i];
  27550. v3.y = positions[k + i + 1];
  27551. v3.z = positions[k + i + 2];
  27552. v4.x = positions[k + i + 3];
  27553. v4.y = positions[k + i + 4];
  27554. v4.z = positions[k + i + 5];
  27555. // 2D slope V1V4
  27556. cd = (v4.z - v1.z) / (v4.x - v1.x);
  27557. h = v1.z - cd * v1.x; // v1 belongs to the slope
  27558. var slope = new BABYLON.Vector2(cd, h);
  27559. // facet equations :
  27560. // we compute each facet normal vector
  27561. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  27562. // we compute the value d by applying the equation to v1 which belongs to the plane
  27563. // then we store the facet equation in a Vector4
  27564. v2.subtractToRef(v1, v1v2);
  27565. v3.subtractToRef(v1, v1v3);
  27566. v4.subtractToRef(v1, v1v4);
  27567. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  27568. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  27569. norm1.normalize();
  27570. norm2.normalize();
  27571. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  27572. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  27573. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  27574. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  27575. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  27576. this._heightQuads.push(quad);
  27577. }
  27578. }
  27579. };
  27580. return GroundMesh;
  27581. })(BABYLON.Mesh);
  27582. BABYLON.GroundMesh = GroundMesh;
  27583. })(BABYLON || (BABYLON = {}));
  27584. var BABYLON;
  27585. (function (BABYLON) {
  27586. var LinesMesh = (function (_super) {
  27587. __extends(LinesMesh, _super);
  27588. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27589. if (parent === void 0) { parent = null; }
  27590. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27591. this.color = new BABYLON.Color3(1, 1, 1);
  27592. this.alpha = 1;
  27593. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27594. attributes: ["position"],
  27595. uniforms: ["worldViewProjection", "color"],
  27596. needAlphaBlending: true
  27597. });
  27598. }
  27599. Object.defineProperty(LinesMesh.prototype, "material", {
  27600. get: function () {
  27601. return this._colorShader;
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27607. get: function () {
  27608. return false;
  27609. },
  27610. enumerable: true,
  27611. configurable: true
  27612. });
  27613. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27614. get: function () {
  27615. return false;
  27616. },
  27617. enumerable: true,
  27618. configurable: true
  27619. });
  27620. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27621. var engine = this.getScene().getEngine();
  27622. var indexToBind = this._geometry.getIndexBuffer();
  27623. // VBOs
  27624. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27625. // Color
  27626. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27627. };
  27628. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27629. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27630. return;
  27631. }
  27632. var engine = this.getScene().getEngine();
  27633. // Draw order
  27634. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27635. };
  27636. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27637. return null;
  27638. };
  27639. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27640. this._colorShader.dispose();
  27641. _super.prototype.dispose.call(this, doNotRecurse);
  27642. };
  27643. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27644. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27645. };
  27646. return LinesMesh;
  27647. })(BABYLON.Mesh);
  27648. BABYLON.LinesMesh = LinesMesh;
  27649. })(BABYLON || (BABYLON = {}));
  27650. var BABYLON;
  27651. (function (BABYLON) {
  27652. var DebugLayer = (function () {
  27653. function DebugLayer(scene) {
  27654. var _this = this;
  27655. this._transformationMatrix = BABYLON.Matrix.Identity();
  27656. this._enabled = false;
  27657. this._labelsEnabled = false;
  27658. this._displayStatistics = true;
  27659. this._displayTree = false;
  27660. this._displayLogs = false;
  27661. this._identityMatrix = BABYLON.Matrix.Identity();
  27662. this.axisRatio = 0.02;
  27663. this.accentColor = "orange";
  27664. this._scene = scene;
  27665. this._syncPositions = function () {
  27666. var engine = _this._scene.getEngine();
  27667. var canvasRect = engine.getRenderingCanvasClientRect();
  27668. if (_this._showUI) {
  27669. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27670. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27671. _this._statsDiv.style.width = "400px";
  27672. _this._statsDiv.style.height = "auto";
  27673. _this._statsSubsetDiv.style.maxHeight = "240px";
  27674. _this._optionsDiv.style.left = "0px";
  27675. _this._optionsDiv.style.top = "10px";
  27676. _this._optionsDiv.style.width = "200px";
  27677. _this._optionsDiv.style.height = "auto";
  27678. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27679. _this._logDiv.style.left = "0px";
  27680. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27681. _this._logDiv.style.width = "600px";
  27682. _this._logDiv.style.height = "160px";
  27683. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27684. _this._treeDiv.style.top = "10px";
  27685. _this._treeDiv.style.width = "300px";
  27686. _this._treeDiv.style.height = "auto";
  27687. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27688. }
  27689. _this._globalDiv.style.left = canvasRect.left + "px";
  27690. _this._globalDiv.style.top = canvasRect.top + "px";
  27691. _this._drawingCanvas.style.left = "0px";
  27692. _this._drawingCanvas.style.top = "0px";
  27693. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27694. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27695. var devicePixelRatio = window.devicePixelRatio || 1;
  27696. var context = _this._drawingContext;
  27697. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27698. context.mozBackingStorePixelRatio ||
  27699. context.msBackingStorePixelRatio ||
  27700. context.oBackingStorePixelRatio ||
  27701. context.backingStorePixelRatio || 1;
  27702. _this._ratio = devicePixelRatio / backingStoreRatio;
  27703. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27704. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27705. };
  27706. this._onCanvasClick = function (evt) {
  27707. _this._clickPosition = {
  27708. x: evt.clientX * _this._ratio,
  27709. y: evt.clientY * _this._ratio
  27710. };
  27711. };
  27712. this._syncUI = function () {
  27713. if (_this._showUI) {
  27714. if (_this._displayStatistics) {
  27715. _this._displayStats();
  27716. _this._statsDiv.style.display = "";
  27717. }
  27718. else {
  27719. _this._statsDiv.style.display = "none";
  27720. }
  27721. if (_this._displayLogs) {
  27722. _this._logDiv.style.display = "";
  27723. }
  27724. else {
  27725. _this._logDiv.style.display = "none";
  27726. }
  27727. if (_this._displayTree) {
  27728. _this._treeDiv.style.display = "";
  27729. if (_this._needToRefreshMeshesTree) {
  27730. _this._needToRefreshMeshesTree = false;
  27731. _this._refreshMeshesTreeContent();
  27732. }
  27733. }
  27734. else {
  27735. _this._treeDiv.style.display = "none";
  27736. }
  27737. }
  27738. };
  27739. this._syncData = function () {
  27740. if (_this._labelsEnabled || !_this._showUI) {
  27741. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27742. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27743. var engine = _this._scene.getEngine();
  27744. var viewport = _this._camera.viewport;
  27745. var globalViewport = viewport.toGlobal(engine);
  27746. // Meshes
  27747. var meshes = _this._camera.getActiveMeshes();
  27748. var index;
  27749. var projectedPosition;
  27750. for (index = 0; index < meshes.length; index++) {
  27751. var mesh = meshes.data[index];
  27752. var position = mesh.getBoundingInfo().boundingSphere.center;
  27753. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27754. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27755. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27756. }
  27757. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27758. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27759. }
  27760. }
  27761. // Cameras
  27762. var cameras = _this._scene.cameras;
  27763. for (index = 0; index < cameras.length; index++) {
  27764. var camera = cameras[index];
  27765. if (camera === _this._camera) {
  27766. continue;
  27767. }
  27768. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27769. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27770. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27771. _this._camera.detachControl(engine.getRenderingCanvas());
  27772. _this._camera = camera;
  27773. _this._camera.attachControl(engine.getRenderingCanvas());
  27774. }, function () { return "purple"; });
  27775. }
  27776. }
  27777. // Lights
  27778. var lights = _this._scene.lights;
  27779. for (index = 0; index < lights.length; index++) {
  27780. var light = lights[index];
  27781. if (light.position) {
  27782. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27783. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27784. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27785. light.setEnabled(!light.isEnabled());
  27786. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27787. }
  27788. }
  27789. }
  27790. }
  27791. _this._clickPosition = undefined;
  27792. };
  27793. }
  27794. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27795. while (this._treeSubsetDiv.hasChildNodes()) {
  27796. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27797. }
  27798. // Add meshes
  27799. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27800. sortedArray.sort(function (a, b) {
  27801. if (a.name === b.name) {
  27802. return 0;
  27803. }
  27804. return (a.name > b.name) ? 1 : -1;
  27805. });
  27806. for (var index = 0; index < sortedArray.length; index++) {
  27807. var mesh = sortedArray[index];
  27808. if (!mesh.isEnabled()) {
  27809. continue;
  27810. }
  27811. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27812. m.isVisible = element.checked;
  27813. }, mesh);
  27814. }
  27815. };
  27816. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27817. this._drawingContext.beginPath();
  27818. this._drawingContext.moveTo(zero.x, zero.y);
  27819. this._drawingContext.lineTo(unit.x, unit.y);
  27820. this._drawingContext.strokeStyle = color;
  27821. this._drawingContext.lineWidth = 4;
  27822. this._drawingContext.stroke();
  27823. this._drawingContext.font = "normal 14px Segoe UI";
  27824. this._drawingContext.fillStyle = color;
  27825. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27826. };
  27827. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27828. var position = mesh.getBoundingInfo().boundingSphere.center;
  27829. var worldMatrix = mesh.getWorldMatrix();
  27830. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27831. var unit = (unprojectedVector.subtract(position)).length();
  27832. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27833. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27834. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27835. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27836. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27837. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27838. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27839. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27840. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27841. };
  27842. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27843. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27844. this._drawingContext.font = "normal 12px Segoe UI";
  27845. var textMetrics = this._drawingContext.measureText(text);
  27846. var centerX = projectedPosition.x - textMetrics.width / 2;
  27847. var centerY = projectedPosition.y;
  27848. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27849. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27850. onClick();
  27851. }
  27852. this._drawingContext.beginPath();
  27853. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27854. this._drawingContext.fillStyle = getFillStyle();
  27855. this._drawingContext.globalAlpha = 0.5;
  27856. this._drawingContext.fill();
  27857. this._drawingContext.globalAlpha = 1.0;
  27858. this._drawingContext.strokeStyle = '#FFFFFF';
  27859. this._drawingContext.lineWidth = 1;
  27860. this._drawingContext.stroke();
  27861. this._drawingContext.fillStyle = "#FFFFFF";
  27862. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27863. this._drawingContext.beginPath();
  27864. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27865. this._drawingContext.fill();
  27866. }
  27867. };
  27868. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27869. if (!this._clickPosition) {
  27870. return false;
  27871. }
  27872. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27873. return false;
  27874. }
  27875. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27876. return false;
  27877. }
  27878. return true;
  27879. };
  27880. DebugLayer.prototype.isVisible = function () {
  27881. return this._enabled;
  27882. };
  27883. DebugLayer.prototype.hide = function () {
  27884. if (!this._enabled) {
  27885. return;
  27886. }
  27887. this._enabled = false;
  27888. var engine = this._scene.getEngine();
  27889. this._scene.unregisterBeforeRender(this._syncData);
  27890. this._scene.unregisterAfterRender(this._syncUI);
  27891. this._rootElement.removeChild(this._globalDiv);
  27892. this._scene.forceShowBoundingBoxes = false;
  27893. this._scene.forceWireframe = false;
  27894. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27895. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27896. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27897. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27898. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27899. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27900. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27901. BABYLON.StandardMaterial.LightmapEnabled = true;
  27902. this._scene.shadowsEnabled = true;
  27903. this._scene.particlesEnabled = true;
  27904. this._scene.postProcessesEnabled = true;
  27905. this._scene.collisionsEnabled = true;
  27906. this._scene.lightsEnabled = true;
  27907. this._scene.texturesEnabled = true;
  27908. this._scene.lensFlaresEnabled = true;
  27909. this._scene.proceduralTexturesEnabled = true;
  27910. this._scene.renderTargetsEnabled = true;
  27911. this._scene.probesEnabled = true;
  27912. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27913. };
  27914. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27915. if (showUI === void 0) { showUI = true; }
  27916. if (camera === void 0) { camera = null; }
  27917. if (rootElement === void 0) { rootElement = null; }
  27918. if (this._enabled) {
  27919. return;
  27920. }
  27921. this._enabled = true;
  27922. if (camera) {
  27923. this._camera = camera;
  27924. }
  27925. else {
  27926. this._camera = this._scene.activeCamera;
  27927. }
  27928. this._showUI = showUI;
  27929. var engine = this._scene.getEngine();
  27930. this._globalDiv = document.createElement("div");
  27931. this._rootElement = rootElement || document.body;
  27932. this._rootElement.appendChild(this._globalDiv);
  27933. this._generateDOMelements();
  27934. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27935. this._syncPositions();
  27936. this._scene.registerBeforeRender(this._syncData);
  27937. this._scene.registerAfterRender(this._syncUI);
  27938. };
  27939. DebugLayer.prototype._clearLabels = function () {
  27940. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27941. for (var index = 0; index < this._scene.meshes.length; index++) {
  27942. var mesh = this._scene.meshes[index];
  27943. mesh.renderOverlay = false;
  27944. }
  27945. };
  27946. DebugLayer.prototype._generateheader = function (root, text) {
  27947. var header = document.createElement("div");
  27948. header.innerHTML = text + "&nbsp;";
  27949. header.style.textAlign = "right";
  27950. header.style.width = "100%";
  27951. header.style.color = "white";
  27952. header.style.backgroundColor = "Black";
  27953. header.style.padding = "5px 5px 4px 0px";
  27954. header.style.marginLeft = "-5px";
  27955. header.style.fontWeight = "bold";
  27956. root.appendChild(header);
  27957. };
  27958. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27959. var label = document.createElement("label");
  27960. label.innerHTML = title;
  27961. label.style.color = color;
  27962. root.appendChild(label);
  27963. root.appendChild(document.createElement("br"));
  27964. };
  27965. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27966. if (tag === void 0) { tag = null; }
  27967. var label = document.createElement("label");
  27968. var boundingBoxesCheckbox = document.createElement("input");
  27969. boundingBoxesCheckbox.type = "checkbox";
  27970. boundingBoxesCheckbox.checked = initialState;
  27971. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27972. task(evt.target, tag);
  27973. });
  27974. label.appendChild(boundingBoxesCheckbox);
  27975. var container = document.createElement("span");
  27976. var leftPart = document.createElement("span");
  27977. var rightPart = document.createElement("span");
  27978. rightPart.style.cssFloat = "right";
  27979. leftPart.innerHTML = leftTitle;
  27980. rightPart.innerHTML = rightTitle;
  27981. rightPart.style.fontSize = "12px";
  27982. rightPart.style.maxWidth = "200px";
  27983. container.appendChild(leftPart);
  27984. container.appendChild(rightPart);
  27985. label.appendChild(container);
  27986. root.appendChild(label);
  27987. root.appendChild(document.createElement("br"));
  27988. };
  27989. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27990. if (tag === void 0) { tag = null; }
  27991. var label = document.createElement("label");
  27992. var checkBox = document.createElement("input");
  27993. checkBox.type = "checkbox";
  27994. checkBox.checked = initialState;
  27995. checkBox.addEventListener("change", function (evt) {
  27996. task(evt.target, tag);
  27997. });
  27998. label.appendChild(checkBox);
  27999. label.appendChild(document.createTextNode(title));
  28000. root.appendChild(label);
  28001. root.appendChild(document.createElement("br"));
  28002. };
  28003. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28004. if (tag === void 0) { tag = null; }
  28005. var button = document.createElement("button");
  28006. button.innerHTML = title;
  28007. button.style.height = "24px";
  28008. button.style.width = "150px";
  28009. button.style.marginBottom = "5px";
  28010. button.style.color = "#444444";
  28011. button.style.border = "1px solid white";
  28012. button.className = "debugLayerButton";
  28013. button.addEventListener("click", function (evt) {
  28014. task(evt.target, tag);
  28015. });
  28016. root.appendChild(button);
  28017. root.appendChild(document.createElement("br"));
  28018. };
  28019. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28020. if (tag === void 0) { tag = null; }
  28021. var label = document.createElement("label");
  28022. var boundingBoxesRadio = document.createElement("input");
  28023. boundingBoxesRadio.type = "radio";
  28024. boundingBoxesRadio.name = name;
  28025. boundingBoxesRadio.checked = initialState;
  28026. boundingBoxesRadio.addEventListener("change", function (evt) {
  28027. task(evt.target, tag);
  28028. });
  28029. label.appendChild(boundingBoxesRadio);
  28030. label.appendChild(document.createTextNode(title));
  28031. root.appendChild(label);
  28032. root.appendChild(document.createElement("br"));
  28033. };
  28034. DebugLayer.prototype._generateDOMelements = function () {
  28035. var _this = this;
  28036. this._globalDiv.id = "DebugLayer";
  28037. this._globalDiv.style.position = "absolute";
  28038. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28039. this._globalDiv.style.fontSize = "14px";
  28040. this._globalDiv.style.color = "white";
  28041. // Drawing canvas
  28042. this._drawingCanvas = document.createElement("canvas");
  28043. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28044. this._drawingCanvas.style.position = "absolute";
  28045. this._drawingCanvas.style.pointerEvents = "none";
  28046. this._drawingCanvas.style.backgroundColor = "transparent";
  28047. this._drawingContext = this._drawingCanvas.getContext("2d");
  28048. this._globalDiv.appendChild(this._drawingCanvas);
  28049. if (this._showUI) {
  28050. var background = "rgba(128, 128, 128, 0.4)";
  28051. var border = "rgb(180, 180, 180) solid 1px";
  28052. // Stats
  28053. this._statsDiv = document.createElement("div");
  28054. this._statsDiv.id = "DebugLayerStats";
  28055. this._statsDiv.style.border = border;
  28056. this._statsDiv.style.position = "absolute";
  28057. this._statsDiv.style.background = background;
  28058. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28059. this._generateheader(this._statsDiv, "STATISTICS");
  28060. this._statsSubsetDiv = document.createElement("div");
  28061. this._statsSubsetDiv.style.paddingTop = "5px";
  28062. this._statsSubsetDiv.style.paddingBottom = "5px";
  28063. this._statsSubsetDiv.style.overflowY = "auto";
  28064. this._statsDiv.appendChild(this._statsSubsetDiv);
  28065. // Tree
  28066. this._treeDiv = document.createElement("div");
  28067. this._treeDiv.id = "DebugLayerTree";
  28068. this._treeDiv.style.border = border;
  28069. this._treeDiv.style.position = "absolute";
  28070. this._treeDiv.style.background = background;
  28071. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28072. this._treeDiv.style.display = "none";
  28073. this._generateheader(this._treeDiv, "MESHES TREE");
  28074. this._treeSubsetDiv = document.createElement("div");
  28075. this._treeSubsetDiv.style.paddingTop = "5px";
  28076. this._treeSubsetDiv.style.paddingRight = "5px";
  28077. this._treeSubsetDiv.style.overflowY = "auto";
  28078. this._treeSubsetDiv.style.maxHeight = "300px";
  28079. this._treeDiv.appendChild(this._treeSubsetDiv);
  28080. this._needToRefreshMeshesTree = true;
  28081. // Logs
  28082. this._logDiv = document.createElement("div");
  28083. this._logDiv.style.border = border;
  28084. this._logDiv.id = "DebugLayerLogs";
  28085. this._logDiv.style.position = "absolute";
  28086. this._logDiv.style.background = background;
  28087. this._logDiv.style.padding = "0px 0px 0px 5px";
  28088. this._logDiv.style.display = "none";
  28089. this._generateheader(this._logDiv, "LOGS");
  28090. this._logSubsetDiv = document.createElement("div");
  28091. this._logSubsetDiv.style.height = "127px";
  28092. this._logSubsetDiv.style.paddingTop = "5px";
  28093. this._logSubsetDiv.style.overflowY = "auto";
  28094. this._logSubsetDiv.style.fontSize = "12px";
  28095. this._logSubsetDiv.style.fontFamily = "consolas";
  28096. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28097. this._logDiv.appendChild(this._logSubsetDiv);
  28098. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28099. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28100. };
  28101. // Options
  28102. this._optionsDiv = document.createElement("div");
  28103. this._optionsDiv.id = "DebugLayerOptions";
  28104. this._optionsDiv.style.border = border;
  28105. this._optionsDiv.style.position = "absolute";
  28106. this._optionsDiv.style.background = background;
  28107. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28108. this._optionsDiv.style.overflowY = "auto";
  28109. this._generateheader(this._optionsDiv, "OPTIONS");
  28110. this._optionsSubsetDiv = document.createElement("div");
  28111. this._optionsSubsetDiv.style.paddingTop = "5px";
  28112. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28113. this._optionsSubsetDiv.style.overflowY = "auto";
  28114. this._optionsSubsetDiv.style.maxHeight = "200px";
  28115. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28116. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28117. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28118. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28119. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28120. _this._displayTree = element.checked;
  28121. _this._needToRefreshMeshesTree = true;
  28122. });
  28123. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28124. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28125. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28126. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28127. _this._labelsEnabled = element.checked;
  28128. if (!_this._labelsEnabled) {
  28129. _this._clearLabels();
  28130. }
  28131. });
  28132. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28133. if (element.checked) {
  28134. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28135. }
  28136. else {
  28137. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28138. }
  28139. });
  28140. ;
  28141. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28142. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28143. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28144. if (element.checked) {
  28145. _this._scene.forceWireframe = false;
  28146. _this._scene.forcePointsCloud = false;
  28147. }
  28148. });
  28149. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28150. if (element.checked) {
  28151. _this._scene.forceWireframe = true;
  28152. _this._scene.forcePointsCloud = false;
  28153. }
  28154. });
  28155. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28156. if (element.checked) {
  28157. _this._scene.forceWireframe = false;
  28158. _this._scene.forcePointsCloud = true;
  28159. }
  28160. });
  28161. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28162. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28163. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28164. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28165. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28166. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28167. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28168. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28169. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28170. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28171. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  28172. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28173. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28174. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28175. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28176. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28177. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28178. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28179. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28180. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28181. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28182. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28183. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28184. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28185. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28186. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28187. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28188. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28189. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28190. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28191. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28192. if (element.checked) {
  28193. _this._scene.headphone = true;
  28194. }
  28195. });
  28196. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28197. if (element.checked) {
  28198. _this._scene.headphone = false;
  28199. }
  28200. });
  28201. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28202. _this._scene.audioEnabled = !element.checked;
  28203. });
  28204. }
  28205. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28206. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28207. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28208. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28209. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28210. if (_this._camera) {
  28211. console.log(_this._camera);
  28212. }
  28213. else {
  28214. console.warn("No camera defined, or debug layer created before camera creation!");
  28215. }
  28216. });
  28217. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28218. this._globalDiv.appendChild(this._statsDiv);
  28219. this._globalDiv.appendChild(this._logDiv);
  28220. this._globalDiv.appendChild(this._optionsDiv);
  28221. this._globalDiv.appendChild(this._treeDiv);
  28222. }
  28223. };
  28224. DebugLayer.prototype._displayStats = function () {
  28225. var scene = this._scene;
  28226. var engine = scene.getEngine();
  28227. var glInfo = engine.getGlInfo();
  28228. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28229. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28230. + "<b>Count</b><br>"
  28231. + "Total meshes: " + scene.meshes.length + "<br>"
  28232. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28233. + "Total materials: " + scene.materials.length + "<br>"
  28234. + "Total textures: " + scene.textures.length + "<br>"
  28235. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28236. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28237. + "Active bones: " + scene.getActiveBones() + "<br>"
  28238. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28239. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  28240. + "<b>Duration</b><br>"
  28241. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28242. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28243. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28244. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28245. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28246. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28247. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  28248. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  28249. + "</div>"
  28250. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28251. + "<b>Extensions</b><br>"
  28252. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28253. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28254. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28255. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  28256. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28257. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28258. + "<b>Caps.</b><br>"
  28259. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28260. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28261. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  28262. + "</div><br>"
  28263. + "<b>Info</b><br>"
  28264. + glInfo.version + "<br>"
  28265. + glInfo.renderer + "<br>";
  28266. if (this.customStatsFunction) {
  28267. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28268. }
  28269. };
  28270. return DebugLayer;
  28271. })();
  28272. BABYLON.DebugLayer = DebugLayer;
  28273. })(BABYLON || (BABYLON = {}));
  28274. var BABYLON;
  28275. (function (BABYLON) {
  28276. var DefaultLoadingScreen = (function () {
  28277. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28278. var _this = this;
  28279. if (_loadingText === void 0) { _loadingText = ""; }
  28280. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28281. this._renderingCanvas = _renderingCanvas;
  28282. this._loadingText = _loadingText;
  28283. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28284. // Resize
  28285. this._resizeLoadingUI = function () {
  28286. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28287. _this._loadingDiv.style.position = "absolute";
  28288. _this._loadingDiv.style.left = canvasRect.left + "px";
  28289. _this._loadingDiv.style.top = canvasRect.top + "px";
  28290. _this._loadingDiv.style.width = canvasRect.width + "px";
  28291. _this._loadingDiv.style.height = canvasRect.height + "px";
  28292. };
  28293. }
  28294. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28295. var _this = this;
  28296. if (this._loadingDiv) {
  28297. // Do not add a loading screen if there is already one
  28298. return;
  28299. }
  28300. this._loadingDiv = document.createElement("div");
  28301. this._loadingDiv.id = "babylonjsLoadingDiv";
  28302. this._loadingDiv.style.opacity = "0";
  28303. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28304. // Loading text
  28305. this._loadingTextDiv = document.createElement("div");
  28306. this._loadingTextDiv.style.position = "absolute";
  28307. this._loadingTextDiv.style.left = "0";
  28308. this._loadingTextDiv.style.top = "50%";
  28309. this._loadingTextDiv.style.marginTop = "80px";
  28310. this._loadingTextDiv.style.width = "100%";
  28311. this._loadingTextDiv.style.height = "20px";
  28312. this._loadingTextDiv.style.fontFamily = "Arial";
  28313. this._loadingTextDiv.style.fontSize = "14px";
  28314. this._loadingTextDiv.style.color = "white";
  28315. this._loadingTextDiv.style.textAlign = "center";
  28316. this._loadingTextDiv.innerHTML = "Loading";
  28317. this._loadingDiv.appendChild(this._loadingTextDiv);
  28318. //set the predefined text
  28319. this._loadingTextDiv.innerHTML = this._loadingText;
  28320. // Loading img
  28321. var imgBack = new Image();
  28322. 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==";
  28323. imgBack.style.position = "absolute";
  28324. imgBack.style.left = "50%";
  28325. imgBack.style.top = "50%";
  28326. imgBack.style.marginLeft = "-50px";
  28327. imgBack.style.marginTop = "-50px";
  28328. imgBack.style.transition = "transform 1.0s ease";
  28329. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28330. var deg = 360;
  28331. var onTransitionEnd = function () {
  28332. deg += 360;
  28333. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28334. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28335. };
  28336. imgBack.addEventListener("transitionend", onTransitionEnd);
  28337. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28338. this._loadingDiv.appendChild(imgBack);
  28339. // front image
  28340. var imgFront = new Image();
  28341. 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=";
  28342. imgFront.style.position = "absolute";
  28343. imgFront.style.left = "50%";
  28344. imgFront.style.top = "50%";
  28345. imgFront.style.marginLeft = "-50px";
  28346. imgFront.style.marginTop = "-50px";
  28347. this._loadingDiv.appendChild(imgFront);
  28348. this._resizeLoadingUI();
  28349. window.addEventListener("resize", this._resizeLoadingUI);
  28350. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28351. document.body.appendChild(this._loadingDiv);
  28352. setTimeout(function () {
  28353. _this._loadingDiv.style.opacity = "1";
  28354. imgBack.style.transform = "rotateZ(360deg)";
  28355. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28356. }, 0);
  28357. };
  28358. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28359. var _this = this;
  28360. if (!this._loadingDiv) {
  28361. return;
  28362. }
  28363. var onTransitionEnd = function () {
  28364. if (!_this._loadingDiv) {
  28365. return;
  28366. }
  28367. document.body.removeChild(_this._loadingDiv);
  28368. window.removeEventListener("resize", _this._resizeLoadingUI);
  28369. _this._loadingDiv = null;
  28370. };
  28371. this._loadingDiv.style.opacity = "0";
  28372. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28373. };
  28374. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28375. set: function (text) {
  28376. this._loadingText = text;
  28377. if (this._loadingTextDiv) {
  28378. this._loadingTextDiv.innerHTML = this._loadingText;
  28379. }
  28380. },
  28381. enumerable: true,
  28382. configurable: true
  28383. });
  28384. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28385. get: function () {
  28386. return this._loadingDivBackgroundColor;
  28387. },
  28388. set: function (color) {
  28389. this._loadingDivBackgroundColor = color;
  28390. if (!this._loadingDiv) {
  28391. return;
  28392. }
  28393. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28394. },
  28395. enumerable: true,
  28396. configurable: true
  28397. });
  28398. return DefaultLoadingScreen;
  28399. })();
  28400. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28401. })(BABYLON || (BABYLON = {}));
  28402. var BABYLON;
  28403. (function (BABYLON) {
  28404. var SIMDVector3 = (function () {
  28405. function SIMDVector3() {
  28406. }
  28407. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28408. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28409. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28410. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28411. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28412. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28413. 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));
  28414. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28415. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28416. };
  28417. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28418. var v0 = SIMD.float32x4.splat(x);
  28419. var v1 = SIMD.float32x4.splat(y);
  28420. var v2 = SIMD.float32x4.splat(z);
  28421. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28422. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28423. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28424. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28425. 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));
  28426. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28427. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28428. };
  28429. return SIMDVector3;
  28430. })();
  28431. BABYLON.SIMDVector3 = SIMDVector3;
  28432. var SIMDMatrix = (function () {
  28433. function SIMDMatrix() {
  28434. }
  28435. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28436. if (offset === void 0) { offset = 0; }
  28437. var tm = this.m;
  28438. var om = other.m;
  28439. var om0 = SIMD.float32x4.load(om, 0);
  28440. var om1 = SIMD.float32x4.load(om, 4);
  28441. var om2 = SIMD.float32x4.load(om, 8);
  28442. var om3 = SIMD.float32x4.load(om, 12);
  28443. var tm0 = SIMD.float32x4.load(tm, 0);
  28444. 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)))));
  28445. var tm1 = SIMD.float32x4.load(tm, 4);
  28446. 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)))));
  28447. var tm2 = SIMD.float32x4.load(tm, 8);
  28448. 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)))));
  28449. var tm3 = SIMD.float32x4.load(tm, 12);
  28450. 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)))));
  28451. };
  28452. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28453. var src = this.m;
  28454. var dest = other.m;
  28455. var row0, row1, row2, row3;
  28456. var tmp1;
  28457. var minor0, minor1, minor2, minor3;
  28458. var det;
  28459. // Load the 4 rows
  28460. var src0 = SIMD.float32x4.load(src, 0);
  28461. var src1 = SIMD.float32x4.load(src, 4);
  28462. var src2 = SIMD.float32x4.load(src, 8);
  28463. var src3 = SIMD.float32x4.load(src, 12);
  28464. // Transpose the source matrix. Sort of. Not a true transpose operation
  28465. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28466. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28467. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28468. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28469. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28470. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28471. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28472. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28473. // This is a true transposition, but it will lead to an incorrect result
  28474. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28475. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28476. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28477. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28478. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28479. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28480. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28481. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28482. // ----
  28483. tmp1 = SIMD.float32x4.mul(row2, row3);
  28484. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28485. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28486. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28487. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28488. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28489. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28490. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28491. // ----
  28492. tmp1 = SIMD.float32x4.mul(row1, row2);
  28493. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28494. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28495. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28496. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28497. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28498. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28499. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28500. // ----
  28501. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28502. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28503. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28504. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28505. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28506. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28507. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28508. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28509. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28510. // ----
  28511. tmp1 = SIMD.float32x4.mul(row0, row1);
  28512. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28513. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28514. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28515. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28516. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28517. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28518. // ----
  28519. tmp1 = SIMD.float32x4.mul(row0, row3);
  28520. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28521. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28522. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28523. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28524. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28525. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28526. // ----
  28527. tmp1 = SIMD.float32x4.mul(row0, row2);
  28528. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28529. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28530. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28531. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28532. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28533. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28534. // Compute determinant
  28535. det = SIMD.float32x4.mul(row0, minor0);
  28536. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28537. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28538. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28539. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28540. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28541. // These shuffles aren't necessary if the faulty transposition is done
  28542. // up at the top of this function.
  28543. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28544. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28545. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28546. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28547. // Compute final values by multiplying with 1/det
  28548. minor0 = SIMD.float32x4.mul(det, minor0);
  28549. minor1 = SIMD.float32x4.mul(det, minor1);
  28550. minor2 = SIMD.float32x4.mul(det, minor2);
  28551. minor3 = SIMD.float32x4.mul(det, minor3);
  28552. SIMD.float32x4.store(dest, 0, minor0);
  28553. SIMD.float32x4.store(dest, 4, minor1);
  28554. SIMD.float32x4.store(dest, 8, minor2);
  28555. SIMD.float32x4.store(dest, 12, minor3);
  28556. return this;
  28557. };
  28558. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28559. var out = result.m;
  28560. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28561. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28562. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28563. // cc.kmVec3Subtract(f, pCenter, pEye);
  28564. var f = SIMD.float32x4.sub(center, eye);
  28565. // cc.kmVec3Normalize(f, f);
  28566. var tmp = SIMD.float32x4.mul(f, f);
  28567. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28568. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28569. // cc.kmVec3Assign(up, pUp);
  28570. // cc.kmVec3Normalize(up, up);
  28571. tmp = SIMD.float32x4.mul(up, up);
  28572. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28573. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28574. // cc.kmVec3Cross(s, f, up);
  28575. 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)));
  28576. // cc.kmVec3Normalize(s, s);
  28577. tmp = SIMD.float32x4.mul(s, s);
  28578. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28579. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28580. // cc.kmVec3Cross(u, s, f);
  28581. 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)));
  28582. // cc.kmVec3Normalize(s, s);
  28583. tmp = SIMD.float32x4.mul(s, s);
  28584. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28585. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28586. var zero = SIMD.float32x4.splat(0.0);
  28587. s = SIMD.float32x4.neg(s);
  28588. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28589. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28590. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28591. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28592. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28593. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28594. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28595. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28596. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28597. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28598. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28599. var b3 = SIMD.float32x4.neg(eye);
  28600. b3 = SIMD.float32x4.withW(b3, 1.0);
  28601. 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)))));
  28602. 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)))));
  28603. 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)))));
  28604. 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)))));
  28605. };
  28606. return SIMDMatrix;
  28607. })();
  28608. BABYLON.SIMDMatrix = SIMDMatrix;
  28609. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28610. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28611. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28612. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28613. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28614. var SIMDHelper = (function () {
  28615. function SIMDHelper() {
  28616. }
  28617. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28618. get: function () {
  28619. return SIMDHelper._isEnabled;
  28620. },
  28621. enumerable: true,
  28622. configurable: true
  28623. });
  28624. SIMDHelper.DisableSIMD = function () {
  28625. // Replace functions
  28626. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28627. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28628. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28629. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28630. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28631. SIMDHelper._isEnabled = false;
  28632. };
  28633. SIMDHelper.EnableSIMD = function () {
  28634. if (window.SIMD === undefined) {
  28635. return;
  28636. }
  28637. // Replace functions
  28638. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28639. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28640. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28641. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28642. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28643. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28644. get: function () { return this._data[0]; },
  28645. set: function (value) {
  28646. if (!this._data) {
  28647. this._data = new Float32Array(3);
  28648. }
  28649. this._data[0] = value;
  28650. }
  28651. });
  28652. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28653. get: function () { return this._data[1]; },
  28654. set: function (value) {
  28655. this._data[1] = value;
  28656. }
  28657. });
  28658. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28659. get: function () { return this._data[2]; },
  28660. set: function (value) {
  28661. this._data[2] = value;
  28662. }
  28663. });
  28664. SIMDHelper._isEnabled = true;
  28665. };
  28666. SIMDHelper._isEnabled = false;
  28667. return SIMDHelper;
  28668. })();
  28669. BABYLON.SIMDHelper = SIMDHelper;
  28670. })(BABYLON || (BABYLON = {}));
  28671. var BABYLON;
  28672. (function (BABYLON) {
  28673. var ShaderMaterial = (function (_super) {
  28674. __extends(ShaderMaterial, _super);
  28675. function ShaderMaterial(name, scene, shaderPath, options) {
  28676. _super.call(this, name, scene);
  28677. this._textures = {};
  28678. this._floats = {};
  28679. this._floatsArrays = {};
  28680. this._colors3 = {};
  28681. this._colors4 = {};
  28682. this._vectors2 = {};
  28683. this._vectors3 = {};
  28684. this._vectors4 = {};
  28685. this._matrices = {};
  28686. this._matrices3x3 = {};
  28687. this._matrices2x2 = {};
  28688. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28689. this._shaderPath = shaderPath;
  28690. options.needAlphaBlending = options.needAlphaBlending || false;
  28691. options.needAlphaTesting = options.needAlphaTesting || false;
  28692. options.attributes = options.attributes || ["position", "normal", "uv"];
  28693. options.uniforms = options.uniforms || ["worldViewProjection"];
  28694. options.samplers = options.samplers || [];
  28695. options.defines = options.defines || [];
  28696. this._options = options;
  28697. }
  28698. ShaderMaterial.prototype.needAlphaBlending = function () {
  28699. return this._options.needAlphaBlending;
  28700. };
  28701. ShaderMaterial.prototype.needAlphaTesting = function () {
  28702. return this._options.needAlphaTesting;
  28703. };
  28704. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28705. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28706. this._options.uniforms.push(uniformName);
  28707. }
  28708. };
  28709. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28710. if (this._options.samplers.indexOf(name) === -1) {
  28711. this._options.samplers.push(name);
  28712. }
  28713. this._textures[name] = texture;
  28714. return this;
  28715. };
  28716. ShaderMaterial.prototype.setFloat = function (name, value) {
  28717. this._checkUniform(name);
  28718. this._floats[name] = value;
  28719. return this;
  28720. };
  28721. ShaderMaterial.prototype.setFloats = function (name, value) {
  28722. this._checkUniform(name);
  28723. this._floatsArrays[name] = value;
  28724. return this;
  28725. };
  28726. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28727. this._checkUniform(name);
  28728. this._colors3[name] = value;
  28729. return this;
  28730. };
  28731. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28732. this._checkUniform(name);
  28733. this._colors4[name] = value;
  28734. return this;
  28735. };
  28736. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28737. this._checkUniform(name);
  28738. this._vectors2[name] = value;
  28739. return this;
  28740. };
  28741. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28742. this._checkUniform(name);
  28743. this._vectors3[name] = value;
  28744. return this;
  28745. };
  28746. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28747. this._checkUniform(name);
  28748. this._vectors4[name] = value;
  28749. return this;
  28750. };
  28751. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28752. this._checkUniform(name);
  28753. this._matrices[name] = value;
  28754. return this;
  28755. };
  28756. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28757. this._checkUniform(name);
  28758. this._matrices3x3[name] = value;
  28759. return this;
  28760. };
  28761. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28762. this._checkUniform(name);
  28763. this._matrices2x2[name] = value;
  28764. return this;
  28765. };
  28766. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28767. var scene = this.getScene();
  28768. var engine = scene.getEngine();
  28769. if (!this.checkReadyOnEveryCall) {
  28770. if (this._renderId === scene.getRenderId()) {
  28771. return true;
  28772. }
  28773. }
  28774. // Instances
  28775. var defines = [];
  28776. var fallbacks = new BABYLON.EffectFallbacks();
  28777. if (useInstances) {
  28778. defines.push("#define INSTANCES");
  28779. }
  28780. for (var index = 0; index < this._options.defines.length; index++) {
  28781. defines.push(this._options.defines[index]);
  28782. }
  28783. // Bones
  28784. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28785. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28786. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28787. fallbacks.addCPUSkinningFallback(0, mesh);
  28788. }
  28789. // Alpha test
  28790. if (engine.getAlphaTesting()) {
  28791. defines.push("#define ALPHATEST");
  28792. }
  28793. var previousEffect = this._effect;
  28794. var join = defines.join("\n");
  28795. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28796. if (!this._effect.isReady()) {
  28797. return false;
  28798. }
  28799. if (previousEffect !== this._effect) {
  28800. scene.resetCachedMaterial();
  28801. }
  28802. this._renderId = scene.getRenderId();
  28803. return true;
  28804. };
  28805. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28806. var scene = this.getScene();
  28807. if (this._options.uniforms.indexOf("world") !== -1) {
  28808. this._effect.setMatrix("world", world);
  28809. }
  28810. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28811. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28812. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28813. }
  28814. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28815. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28816. }
  28817. };
  28818. ShaderMaterial.prototype.bind = function (world, mesh) {
  28819. // Std values
  28820. this.bindOnlyWorldMatrix(world);
  28821. if (this.getScene().getCachedMaterial() !== this) {
  28822. if (this._options.uniforms.indexOf("view") !== -1) {
  28823. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28824. }
  28825. if (this._options.uniforms.indexOf("projection") !== -1) {
  28826. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28827. }
  28828. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28829. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28830. }
  28831. // Bones
  28832. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28833. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28834. }
  28835. // Texture
  28836. for (var name in this._textures) {
  28837. this._effect.setTexture(name, this._textures[name]);
  28838. }
  28839. // Float
  28840. for (name in this._floats) {
  28841. this._effect.setFloat(name, this._floats[name]);
  28842. }
  28843. // Float s
  28844. for (name in this._floatsArrays) {
  28845. this._effect.setArray(name, this._floatsArrays[name]);
  28846. }
  28847. // Color3
  28848. for (name in this._colors3) {
  28849. this._effect.setColor3(name, this._colors3[name]);
  28850. }
  28851. // Color4
  28852. for (name in this._colors4) {
  28853. var color = this._colors4[name];
  28854. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28855. }
  28856. // Vector2
  28857. for (name in this._vectors2) {
  28858. this._effect.setVector2(name, this._vectors2[name]);
  28859. }
  28860. // Vector3
  28861. for (name in this._vectors3) {
  28862. this._effect.setVector3(name, this._vectors3[name]);
  28863. }
  28864. // Vector4
  28865. for (name in this._vectors4) {
  28866. this._effect.setVector4(name, this._vectors4[name]);
  28867. }
  28868. // Matrix
  28869. for (name in this._matrices) {
  28870. this._effect.setMatrix(name, this._matrices[name]);
  28871. }
  28872. // Matrix 3x3
  28873. for (name in this._matrices3x3) {
  28874. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28875. }
  28876. // Matrix 2x2
  28877. for (name in this._matrices2x2) {
  28878. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28879. }
  28880. }
  28881. _super.prototype.bind.call(this, world, mesh);
  28882. };
  28883. ShaderMaterial.prototype.clone = function (name) {
  28884. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28885. return newShaderMaterial;
  28886. };
  28887. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28888. for (var name in this._textures) {
  28889. this._textures[name].dispose();
  28890. }
  28891. this._textures = {};
  28892. _super.prototype.dispose.call(this, forceDisposeEffect);
  28893. };
  28894. ShaderMaterial.prototype.serialize = function () {
  28895. var serializationObject = _super.prototype.serialize.call(this);
  28896. serializationObject.options = this._options;
  28897. serializationObject.shaderPath = this._shaderPath;
  28898. serializationObject.customType = "BABYLON.ShaderMaterial";
  28899. // Texture
  28900. serializationObject.textures = {};
  28901. for (var name in this._textures) {
  28902. serializationObject.textures[name] = this._textures[name].serialize();
  28903. }
  28904. // Float
  28905. serializationObject.floats = {};
  28906. for (name in this._floats) {
  28907. serializationObject.floats[name] = this._floats[name];
  28908. }
  28909. // Float s
  28910. serializationObject.floatArrays = {};
  28911. for (name in this._floatsArrays) {
  28912. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28913. }
  28914. // Color3
  28915. serializationObject.colors3 = {};
  28916. for (name in this._colors3) {
  28917. serializationObject.colors3[name] = this._colors3[name].asArray();
  28918. }
  28919. // Color4
  28920. serializationObject.colors4 = {};
  28921. for (name in this._colors4) {
  28922. serializationObject.colors4[name] = this._colors4[name].asArray();
  28923. }
  28924. // Vector2
  28925. serializationObject.vectors2 = {};
  28926. for (name in this._vectors2) {
  28927. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28928. }
  28929. // Vector3
  28930. serializationObject.vectors3 = {};
  28931. for (name in this._vectors3) {
  28932. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28933. }
  28934. // Vector4
  28935. serializationObject.vectors4 = {};
  28936. for (name in this._vectors4) {
  28937. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28938. }
  28939. // Matrix
  28940. serializationObject.matrices = {};
  28941. for (name in this._matrices) {
  28942. serializationObject.matrices[name] = this._matrices[name].asArray();
  28943. }
  28944. // Matrix 3x3
  28945. serializationObject.matrices3x3 = {};
  28946. for (name in this._matrices3x3) {
  28947. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28948. }
  28949. // Matrix 2x2
  28950. serializationObject.matrices2x2 = {};
  28951. for (name in this._matrices2x2) {
  28952. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28953. }
  28954. return serializationObject;
  28955. };
  28956. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28957. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28958. // Texture
  28959. for (var name in source.textures) {
  28960. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28961. }
  28962. // Float
  28963. for (name in source.floats) {
  28964. material.setFloat(name, source.floats[name]);
  28965. }
  28966. // Float s
  28967. for (name in source.floatsArrays) {
  28968. material.setFloats(name, source.floatsArrays[name]);
  28969. }
  28970. // Color3
  28971. for (name in source.colors3) {
  28972. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28973. }
  28974. // Color4
  28975. for (name in source.colors4) {
  28976. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28977. }
  28978. // Vector2
  28979. for (name in source.vectors2) {
  28980. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28981. }
  28982. // Vector3
  28983. for (name in source.vectors3) {
  28984. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28985. }
  28986. // Vector4
  28987. for (name in source.vectors4) {
  28988. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28989. }
  28990. // Matrix
  28991. for (name in source.matrices) {
  28992. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28993. }
  28994. // Matrix 3x3
  28995. for (name in source.matrices3x3) {
  28996. material.setMatrix3x3(name, source.matrices3x3[name]);
  28997. }
  28998. // Matrix 2x2
  28999. for (name in source.matrices2x2) {
  29000. material.setMatrix2x2(name, source.matrices2x2[name]);
  29001. }
  29002. return material;
  29003. };
  29004. return ShaderMaterial;
  29005. })(BABYLON.Material);
  29006. BABYLON.ShaderMaterial = ShaderMaterial;
  29007. })(BABYLON || (BABYLON = {}));
  29008. var BABYLON;
  29009. (function (BABYLON) {
  29010. var Internals;
  29011. (function (Internals) {
  29012. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29013. // All values and structures referenced from:
  29014. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29015. var DDS_MAGIC = 0x20534444;
  29016. 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;
  29017. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29018. 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;
  29019. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29020. function FourCCToInt32(value) {
  29021. return value.charCodeAt(0) +
  29022. (value.charCodeAt(1) << 8) +
  29023. (value.charCodeAt(2) << 16) +
  29024. (value.charCodeAt(3) << 24);
  29025. }
  29026. function Int32ToFourCC(value) {
  29027. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29028. }
  29029. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29030. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29031. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29032. var headerLengthInt = 31; // The header length in 32 bit ints
  29033. // Offsets into the header array
  29034. var off_magic = 0;
  29035. var off_size = 1;
  29036. var off_flags = 2;
  29037. var off_height = 3;
  29038. var off_width = 4;
  29039. var off_mipmapCount = 7;
  29040. var off_pfFlags = 20;
  29041. var off_pfFourCC = 21;
  29042. var off_RGBbpp = 22;
  29043. var off_RMask = 23;
  29044. var off_GMask = 24;
  29045. var off_BMask = 25;
  29046. var off_AMask = 26;
  29047. var off_caps1 = 27;
  29048. var off_caps2 = 28;
  29049. ;
  29050. var DDSTools = (function () {
  29051. function DDSTools() {
  29052. }
  29053. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29054. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29055. var mipmapCount = 1;
  29056. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29057. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29058. }
  29059. return {
  29060. width: header[off_width],
  29061. height: header[off_height],
  29062. mipmapCount: mipmapCount,
  29063. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29064. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29065. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29066. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29067. };
  29068. };
  29069. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29070. var byteArray = new Uint8Array(dataLength);
  29071. var srcData = new Uint8Array(arrayBuffer);
  29072. var index = 0;
  29073. for (var y = height - 1; y >= 0; y--) {
  29074. for (var x = 0; x < width; x++) {
  29075. var srcPos = dataOffset + (x + y * width) * 4;
  29076. byteArray[index + 2] = srcData[srcPos];
  29077. byteArray[index + 1] = srcData[srcPos + 1];
  29078. byteArray[index] = srcData[srcPos + 2];
  29079. byteArray[index + 3] = srcData[srcPos + 3];
  29080. index += 4;
  29081. }
  29082. }
  29083. return byteArray;
  29084. };
  29085. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29086. var byteArray = new Uint8Array(dataLength);
  29087. var srcData = new Uint8Array(arrayBuffer);
  29088. var index = 0;
  29089. for (var y = height - 1; y >= 0; y--) {
  29090. for (var x = 0; x < width; x++) {
  29091. var srcPos = dataOffset + (x + y * width) * 3;
  29092. byteArray[index + 2] = srcData[srcPos];
  29093. byteArray[index + 1] = srcData[srcPos + 1];
  29094. byteArray[index] = srcData[srcPos + 2];
  29095. index += 3;
  29096. }
  29097. }
  29098. return byteArray;
  29099. };
  29100. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29101. var byteArray = new Uint8Array(dataLength);
  29102. var srcData = new Uint8Array(arrayBuffer);
  29103. var index = 0;
  29104. for (var y = height - 1; y >= 0; y--) {
  29105. for (var x = 0; x < width; x++) {
  29106. var srcPos = dataOffset + (x + y * width);
  29107. byteArray[index] = srcData[srcPos];
  29108. index++;
  29109. }
  29110. }
  29111. return byteArray;
  29112. };
  29113. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29114. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29115. if (header[off_magic] != DDS_MAGIC) {
  29116. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29117. return;
  29118. }
  29119. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29120. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29121. return;
  29122. }
  29123. if (info.isFourCC) {
  29124. fourCC = header[off_pfFourCC];
  29125. switch (fourCC) {
  29126. case FOURCC_DXT1:
  29127. blockBytes = 8;
  29128. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29129. break;
  29130. case FOURCC_DXT3:
  29131. blockBytes = 16;
  29132. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29133. break;
  29134. case FOURCC_DXT5:
  29135. blockBytes = 16;
  29136. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29137. break;
  29138. default:
  29139. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29140. return;
  29141. }
  29142. }
  29143. mipmapCount = 1;
  29144. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29145. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29146. }
  29147. var bpp = header[off_RGBbpp];
  29148. for (var face = 0; face < faces; face++) {
  29149. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29150. width = header[off_width];
  29151. height = header[off_height];
  29152. dataOffset = header[off_size] + 4;
  29153. for (i = 0; i < mipmapCount; ++i) {
  29154. if (info.isRGB) {
  29155. if (bpp === 24) {
  29156. dataLength = width * height * 3;
  29157. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29158. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29159. }
  29160. else {
  29161. dataLength = width * height * 4;
  29162. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29163. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29164. }
  29165. }
  29166. else if (info.isLuminance) {
  29167. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29168. var unpaddedRowSize = width;
  29169. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29170. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29171. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29172. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29173. }
  29174. else {
  29175. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29176. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29177. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29178. }
  29179. dataOffset += dataLength;
  29180. width *= 0.5;
  29181. height *= 0.5;
  29182. width = Math.max(1.0, width);
  29183. height = Math.max(1.0, height);
  29184. }
  29185. }
  29186. };
  29187. return DDSTools;
  29188. })();
  29189. Internals.DDSTools = DDSTools;
  29190. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29191. })(BABYLON || (BABYLON = {}));
  29192. var BABYLON;
  29193. (function (BABYLON) {
  29194. var CannonJSPlugin = (function () {
  29195. function CannonJSPlugin() {
  29196. this._registeredMeshes = [];
  29197. this._physicsMaterials = [];
  29198. this.name = "cannon";
  29199. this.updateBodyPosition = function (mesh) {
  29200. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29201. var registeredMesh = this._registeredMeshes[index];
  29202. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29203. var body = registeredMesh.body;
  29204. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29205. body.quaternion.copy(mesh.rotationQuaternion);
  29206. if (registeredMesh.deltaRotation) {
  29207. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29208. body.quaternion = body.quaternion.mult(tmpQ);
  29209. }
  29210. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29211. //calculate the correct body position:
  29212. var rotationQuaternion = mesh.rotationQuaternion;
  29213. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29214. mesh.computeWorldMatrix(true);
  29215. //get original center with no rotation
  29216. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29217. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29218. //rotation is back
  29219. mesh.rotationQuaternion = rotationQuaternion;
  29220. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29221. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29222. mesh.setPivotMatrix(p);
  29223. mesh.computeWorldMatrix(true);
  29224. //calculate the translation
  29225. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29226. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29227. //add it inverted to the delta
  29228. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29229. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29230. mesh.setPivotMatrix(oldPivot);
  29231. mesh.computeWorldMatrix(true);
  29232. }
  29233. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29234. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29235. }
  29236. body.position.set(center.x, center.y, center.z);
  29237. return;
  29238. }
  29239. }
  29240. };
  29241. }
  29242. CannonJSPlugin.prototype.initialize = function (iterations) {
  29243. if (iterations === void 0) { iterations = 10; }
  29244. this._world = new CANNON.World();
  29245. this._world.broadphase = new CANNON.NaiveBroadphase();
  29246. this._world.solver.iterations = iterations;
  29247. };
  29248. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29249. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29250. };
  29251. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29252. var _this = this;
  29253. this._world.step(delta);
  29254. this._registeredMeshes.forEach(function (registeredMesh) {
  29255. // Body position
  29256. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29257. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29258. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29259. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29260. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29261. if (registeredMesh.deltaRotation) {
  29262. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29263. }
  29264. //is the physics collision callback is set?
  29265. if (registeredMesh.mesh.onPhysicsCollide) {
  29266. if (!registeredMesh.collisionFunction) {
  29267. registeredMesh.collisionFunction = function (e) {
  29268. //find the mesh that collided with the registered mesh
  29269. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29270. if (_this._registeredMeshes[idx].body == e.body) {
  29271. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29272. }
  29273. }
  29274. };
  29275. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29276. }
  29277. }
  29278. else {
  29279. //unregister, in case the function was removed for some reason
  29280. if (registeredMesh.collisionFunction) {
  29281. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29282. }
  29283. }
  29284. });
  29285. };
  29286. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29287. this._gravity = gravity;
  29288. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29289. };
  29290. CannonJSPlugin.prototype.getGravity = function () {
  29291. return this._gravity;
  29292. };
  29293. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29294. this.unregisterMesh(mesh);
  29295. if (!mesh.rotationQuaternion) {
  29296. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29297. }
  29298. mesh.computeWorldMatrix(true);
  29299. var shape = this._createShape(mesh, impostor);
  29300. return this._createRigidBodyFromShape(shape, mesh, options);
  29301. };
  29302. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29303. //get the correct bounding box
  29304. var oldQuaternion = mesh.rotationQuaternion;
  29305. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29306. mesh.computeWorldMatrix(true);
  29307. var returnValue;
  29308. switch (impostor) {
  29309. case BABYLON.PhysicsEngine.SphereImpostor:
  29310. var bbox = mesh.getBoundingInfo().boundingBox;
  29311. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29312. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29313. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29314. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29315. break;
  29316. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29317. case BABYLON.PhysicsEngine.CylinderImpostor:
  29318. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29319. case BABYLON.PhysicsEngine.BoxImpostor:
  29320. bbox = mesh.getBoundingInfo().boundingBox;
  29321. var min = bbox.minimumWorld;
  29322. var max = bbox.maximumWorld;
  29323. var box = max.subtract(min).scale(0.5);
  29324. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29325. break;
  29326. case BABYLON.PhysicsEngine.PlaneImpostor:
  29327. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29328. returnValue = new CANNON.Plane();
  29329. break;
  29330. case BABYLON.PhysicsEngine.MeshImpostor:
  29331. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29332. var rawFaces = mesh.getIndices();
  29333. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29334. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29335. break;
  29336. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29337. returnValue = this._createHeightmap(mesh);
  29338. break;
  29339. }
  29340. mesh.rotationQuaternion = oldQuaternion;
  29341. return returnValue;
  29342. };
  29343. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29344. var verts = [], faces = [];
  29345. mesh.computeWorldMatrix(true);
  29346. //reuse this variable
  29347. var transformed = BABYLON.Vector3.Zero();
  29348. // Get vertices
  29349. for (var i = 0; i < rawVerts.length; i += 3) {
  29350. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29351. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29352. }
  29353. // Get faces
  29354. for (var j = 0; j < rawFaces.length; j += 3) {
  29355. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29356. }
  29357. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29358. return shape;
  29359. };
  29360. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29361. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29362. var matrix = [];
  29363. //For now pointDepth will not be used and will be automatically calculated.
  29364. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29365. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29366. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29367. var elementSize = dim * 2 / arraySize;
  29368. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29369. for (var i = 0; i < pos.length; i = i + 3) {
  29370. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29371. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29372. var y = pos[i + 1] + minY;
  29373. if (!matrix[x]) {
  29374. matrix[x] = [];
  29375. }
  29376. if (!matrix[x][z]) {
  29377. matrix[x][z] = y;
  29378. }
  29379. matrix[x][z] = Math.max(y, matrix[x][z]);
  29380. }
  29381. for (var x = 0; x <= arraySize; ++x) {
  29382. if (!matrix[x]) {
  29383. var loc = 1;
  29384. while (!matrix[(x + loc) % arraySize]) {
  29385. loc++;
  29386. }
  29387. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29388. }
  29389. for (var z = 0; z <= arraySize; ++z) {
  29390. if (!matrix[x][z]) {
  29391. var loc = 1;
  29392. var newValue;
  29393. while (newValue === undefined) {
  29394. newValue = matrix[x][(z + loc++) % arraySize];
  29395. }
  29396. matrix[x][z] = newValue;
  29397. }
  29398. }
  29399. }
  29400. var shape = new CANNON.Heightfield(matrix, {
  29401. elementSize: elementSize
  29402. });
  29403. //For future reference, needed for body transformation
  29404. shape.minY = minY;
  29405. return shape;
  29406. };
  29407. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29408. var index;
  29409. var mat;
  29410. for (index = 0; index < this._physicsMaterials.length; index++) {
  29411. mat = this._physicsMaterials[index];
  29412. if (mat.friction === friction && mat.restitution === restitution) {
  29413. return mat;
  29414. }
  29415. }
  29416. var currentMat = new CANNON.Material("mat");
  29417. this._physicsMaterials.push(currentMat);
  29418. for (index = 0; index < this._physicsMaterials.length; index++) {
  29419. mat = this._physicsMaterials[index];
  29420. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29421. this._world.addContactMaterial(contactMaterial);
  29422. }
  29423. return currentMat;
  29424. };
  29425. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29426. if (!mesh.rotationQuaternion) {
  29427. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29428. }
  29429. // The delta between the mesh position and the mesh bounding box center
  29430. var bbox = mesh.getBoundingInfo().boundingBox;
  29431. var deltaPosition = mesh.position.subtract(bbox.center);
  29432. var deltaRotation;
  29433. var material = this._addMaterial(options.friction, options.restitution);
  29434. var body = new CANNON.Body({
  29435. mass: options.mass,
  29436. material: material,
  29437. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29438. });
  29439. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29440. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29441. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29442. //-90 DEG in X, precalculated
  29443. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29444. body.quaternion = body.quaternion.mult(tmpQ);
  29445. //Invert! (Precalculated, 90 deg in X)
  29446. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29447. }
  29448. //If it is a heightfield, if should be centered.
  29449. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29450. //calculate the correct body position:
  29451. var rotationQuaternion = mesh.rotationQuaternion;
  29452. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29453. mesh.computeWorldMatrix(true);
  29454. //get original center with no rotation
  29455. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29456. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29457. //rotation is back
  29458. mesh.rotationQuaternion = rotationQuaternion;
  29459. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29460. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29461. mesh.setPivotMatrix(p);
  29462. mesh.computeWorldMatrix(true);
  29463. //calculate the translation
  29464. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29465. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29466. //add it inverted to the delta
  29467. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29468. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29469. mesh.setPivotMatrix(oldPivot);
  29470. mesh.computeWorldMatrix(true);
  29471. }
  29472. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29473. deltaPosition = BABYLON.Vector3.Zero();
  29474. }
  29475. //add the shape
  29476. body.addShape(shape);
  29477. this._world.add(body);
  29478. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29479. return body;
  29480. };
  29481. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29482. var initialMesh = parts[0].mesh;
  29483. this.unregisterMesh(initialMesh);
  29484. initialMesh.computeWorldMatrix(true);
  29485. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29486. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29487. for (var index = 1; index < parts.length; index++) {
  29488. var mesh = parts[index].mesh;
  29489. mesh.computeWorldMatrix(true);
  29490. var shape = this._createShape(mesh, parts[index].impostor);
  29491. var localPosition = mesh.position;
  29492. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29493. }
  29494. return body;
  29495. };
  29496. CannonJSPlugin.prototype._unbindBody = function (body) {
  29497. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29498. var registeredMesh = this._registeredMeshes[index];
  29499. if (registeredMesh.body === body) {
  29500. this._world.remove(registeredMesh.body);
  29501. registeredMesh.body = null;
  29502. registeredMesh.delta = null;
  29503. registeredMesh.deltaRotation = null;
  29504. }
  29505. }
  29506. };
  29507. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29508. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29509. var registeredMesh = this._registeredMeshes[index];
  29510. if (registeredMesh.mesh === mesh) {
  29511. // Remove body
  29512. if (registeredMesh.body) {
  29513. this._unbindBody(registeredMesh.body);
  29514. }
  29515. this._registeredMeshes.splice(index, 1);
  29516. return;
  29517. }
  29518. }
  29519. };
  29520. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29521. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29522. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29523. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29524. var registeredMesh = this._registeredMeshes[index];
  29525. if (registeredMesh.mesh === mesh) {
  29526. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29527. return;
  29528. }
  29529. }
  29530. };
  29531. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29532. var body1 = null, body2 = null;
  29533. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29534. var registeredMesh = this._registeredMeshes[index];
  29535. if (registeredMesh.mesh === mesh1) {
  29536. body1 = registeredMesh.body;
  29537. }
  29538. else if (registeredMesh.mesh === mesh2) {
  29539. body2 = registeredMesh.body;
  29540. }
  29541. }
  29542. if (!body1 || !body2) {
  29543. return false;
  29544. }
  29545. 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));
  29546. this._world.addConstraint(constraint);
  29547. return true;
  29548. };
  29549. CannonJSPlugin.prototype.dispose = function () {
  29550. while (this._registeredMeshes.length) {
  29551. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29552. }
  29553. };
  29554. CannonJSPlugin.prototype.isSupported = function () {
  29555. return window.CANNON !== undefined;
  29556. };
  29557. CannonJSPlugin.prototype.getWorldObject = function () {
  29558. return this._world;
  29559. };
  29560. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29561. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29562. var registeredMesh = this._registeredMeshes[index];
  29563. if (registeredMesh.mesh === mesh) {
  29564. return registeredMesh.body;
  29565. }
  29566. }
  29567. return null;
  29568. };
  29569. return CannonJSPlugin;
  29570. })();
  29571. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29572. })(BABYLON || (BABYLON = {}));
  29573. var BABYLON;
  29574. (function (BABYLON) {
  29575. var OimoJSPlugin = (function () {
  29576. function OimoJSPlugin() {
  29577. this._registeredMeshes = [];
  29578. this.name = "oimo";
  29579. /**
  29580. * Update the body position according to the mesh position
  29581. * @param mesh
  29582. */
  29583. this.updateBodyPosition = function (mesh) {
  29584. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29585. var registeredMesh = this._registeredMeshes[index];
  29586. var body = registeredMesh.body.body;
  29587. var updated = false;
  29588. var newPosition;
  29589. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29590. mesh.computeWorldMatrix(true);
  29591. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29592. updated = true;
  29593. }
  29594. else if (registeredMesh.mesh.parent === mesh) {
  29595. mesh.computeWorldMatrix(true);
  29596. registeredMesh.mesh.computeWorldMatrix(true);
  29597. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29598. updated = true;
  29599. }
  29600. if (updated) {
  29601. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29602. body.setQuaternion(mesh.rotationQuaternion);
  29603. body.sleeping = false;
  29604. //force Oimo to update the body's position
  29605. body.updatePosition(1);
  29606. }
  29607. }
  29608. };
  29609. }
  29610. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29611. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29612. };
  29613. OimoJSPlugin.prototype.initialize = function (iterations) {
  29614. this._world = new OIMO.World(null, null, iterations);
  29615. this._world.clear();
  29616. };
  29617. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29618. this._gravity = this._world.gravity = gravity;
  29619. };
  29620. OimoJSPlugin.prototype.getGravity = function () {
  29621. return this._gravity;
  29622. };
  29623. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29624. this.unregisterMesh(mesh);
  29625. if (!mesh.rotationQuaternion) {
  29626. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29627. }
  29628. mesh.computeWorldMatrix(true);
  29629. var bbox = mesh.getBoundingInfo().boundingBox;
  29630. // The delta between the mesh position and the mesh bounding box center
  29631. var deltaPosition = mesh.position.subtract(bbox.center);
  29632. //calculate rotation to fit Oimo's needs (Euler...)
  29633. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29634. //get the correct bounding box
  29635. var oldQuaternion = mesh.rotationQuaternion;
  29636. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29637. mesh.computeWorldMatrix(true);
  29638. var bodyConfig = {
  29639. name: mesh.uniqueId,
  29640. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29641. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29642. move: options.mass != 0,
  29643. config: [options.mass, options.friction, options.restitution],
  29644. world: this._world
  29645. };
  29646. // register mesh
  29647. switch (impostor) {
  29648. case BABYLON.PhysicsEngine.SphereImpostor:
  29649. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29650. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29651. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29652. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29653. bodyConfig.type = 'sphere';
  29654. bodyConfig.size = [size];
  29655. break;
  29656. case BABYLON.PhysicsEngine.PlaneImpostor:
  29657. //Oimo "fakes" a cylinder as a box, so why don't we!
  29658. case BABYLON.PhysicsEngine.CylinderImpostor:
  29659. case BABYLON.PhysicsEngine.BoxImpostor:
  29660. var min = bbox.minimumWorld;
  29661. var max = bbox.maximumWorld;
  29662. var box = max.subtract(min);
  29663. var sizeX = this._checkWithEpsilon(box.x);
  29664. var sizeY = this._checkWithEpsilon(box.y);
  29665. var sizeZ = this._checkWithEpsilon(box.z);
  29666. bodyConfig.type = 'box';
  29667. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29668. break;
  29669. }
  29670. var body = new OIMO.Body(bodyConfig);
  29671. //We have to access the rigid body's properties to set the quaternion.
  29672. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29673. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29674. //TEST
  29675. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29676. //update the internal rotation matrix
  29677. //body.body.syncShapes();
  29678. this._registeredMeshes.push({
  29679. mesh: mesh,
  29680. body: body,
  29681. delta: deltaPosition
  29682. });
  29683. //for the sake of consistency.
  29684. mesh.rotationQuaternion = oldQuaternion;
  29685. return body;
  29686. };
  29687. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29688. var types = [], sizes = [], positions = [], rotations = [];
  29689. var initialMesh = parts[0].mesh;
  29690. for (var index = 0; index < parts.length; index++) {
  29691. var part = parts[index];
  29692. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29693. types.push(bodyParameters.type);
  29694. sizes.push.apply(sizes, bodyParameters.size);
  29695. positions.push.apply(positions, bodyParameters.pos);
  29696. rotations.push.apply(rotations, bodyParameters.rot);
  29697. }
  29698. var body = new OIMO.Body({
  29699. name: initialMesh.uniqueId,
  29700. type: types,
  29701. size: sizes,
  29702. pos: positions,
  29703. rot: rotations,
  29704. move: options.mass != 0,
  29705. config: [options.mass, options.friction, options.restitution],
  29706. world: this._world
  29707. });
  29708. //Reset the body's rotation to be of the initial mesh's.
  29709. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29710. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29711. this._registeredMeshes.push({
  29712. mesh: initialMesh,
  29713. body: body
  29714. });
  29715. return body;
  29716. };
  29717. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29718. var mesh = part.mesh;
  29719. if (!mesh.rotationQuaternion) {
  29720. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29721. }
  29722. // We need the bounding box/sphere info to compute the physics body
  29723. mesh.computeWorldMatrix(true);
  29724. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29725. var bodyParameters = {
  29726. name: mesh.uniqueId,
  29727. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29728. //A bug in Oimo (Body class) prevents us from using rot directly.
  29729. rot: [0, 0, 0],
  29730. //For future reference, if the bug will ever be fixed.
  29731. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29732. };
  29733. var oldQuaternion = mesh.rotationQuaternion;
  29734. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29735. mesh.computeWorldMatrix(true);
  29736. switch (part.impostor) {
  29737. case BABYLON.PhysicsEngine.SphereImpostor:
  29738. var bbox = mesh.getBoundingInfo().boundingBox;
  29739. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29740. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29741. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29742. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29743. bodyParameters.type = 'sphere';
  29744. bodyParameters.size = [size, size, size];
  29745. break;
  29746. case BABYLON.PhysicsEngine.PlaneImpostor:
  29747. case BABYLON.PhysicsEngine.CylinderImpostor:
  29748. case BABYLON.PhysicsEngine.BoxImpostor:
  29749. bbox = mesh.getBoundingInfo().boundingBox;
  29750. var min = bbox.minimumWorld;
  29751. var max = bbox.maximumWorld;
  29752. var box = max.subtract(min);
  29753. var sizeX = this._checkWithEpsilon(box.x);
  29754. var sizeY = this._checkWithEpsilon(box.y);
  29755. var sizeZ = this._checkWithEpsilon(box.z);
  29756. bodyParameters.type = 'box';
  29757. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29758. break;
  29759. }
  29760. mesh.rotationQuaternion = oldQuaternion;
  29761. return bodyParameters;
  29762. };
  29763. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29764. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29765. var registeredMesh = this._registeredMeshes[index];
  29766. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29767. if (registeredMesh.body) {
  29768. this._world.removeRigidBody(registeredMesh.body.body);
  29769. this._unbindBody(registeredMesh.body);
  29770. }
  29771. this._registeredMeshes.splice(index, 1);
  29772. return;
  29773. }
  29774. }
  29775. };
  29776. OimoJSPlugin.prototype._unbindBody = function (body) {
  29777. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29778. var registeredMesh = this._registeredMeshes[index];
  29779. if (registeredMesh.body === body) {
  29780. registeredMesh.body = null;
  29781. }
  29782. }
  29783. };
  29784. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29785. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29786. var registeredMesh = this._registeredMeshes[index];
  29787. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29788. // Get object mass to have a behaviour similar to cannon.js
  29789. var mass = registeredMesh.body.body.massInfo.mass;
  29790. // The force is scaled with the mass of object
  29791. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29792. return;
  29793. }
  29794. }
  29795. };
  29796. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29797. var body1 = null, body2 = null;
  29798. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29799. var registeredMesh = this._registeredMeshes[index];
  29800. if (registeredMesh.mesh === mesh1) {
  29801. body1 = registeredMesh.body.body;
  29802. }
  29803. else if (registeredMesh.mesh === mesh2) {
  29804. body2 = registeredMesh.body.body;
  29805. }
  29806. }
  29807. if (!body1 || !body2) {
  29808. return false;
  29809. }
  29810. if (!options) {
  29811. options = {};
  29812. }
  29813. new OIMO.Link({
  29814. type: options.type,
  29815. body1: body1,
  29816. body2: body2,
  29817. min: options.min,
  29818. max: options.max,
  29819. axe1: options.axe1,
  29820. axe2: options.axe2,
  29821. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29822. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29823. collision: options.collision,
  29824. spring: options.spring,
  29825. world: this._world
  29826. });
  29827. return true;
  29828. };
  29829. OimoJSPlugin.prototype.dispose = function () {
  29830. this._world.clear();
  29831. while (this._registeredMeshes.length) {
  29832. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29833. }
  29834. };
  29835. OimoJSPlugin.prototype.isSupported = function () {
  29836. return OIMO !== undefined;
  29837. };
  29838. OimoJSPlugin.prototype.getWorldObject = function () {
  29839. return this._world;
  29840. };
  29841. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29842. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29843. var registeredMesh = this._registeredMeshes[index];
  29844. if (registeredMesh.mesh === mesh) {
  29845. return registeredMesh.body;
  29846. }
  29847. }
  29848. return null;
  29849. };
  29850. OimoJSPlugin.prototype._getLastShape = function (body) {
  29851. var lastShape = body.shapes;
  29852. while (lastShape.next) {
  29853. lastShape = lastShape.next;
  29854. }
  29855. return lastShape;
  29856. };
  29857. OimoJSPlugin.prototype.runOneStep = function (time) {
  29858. this._world.step();
  29859. // Update the position of all registered meshes
  29860. var i = this._registeredMeshes.length;
  29861. var m;
  29862. while (i--) {
  29863. var body = this._registeredMeshes[i].body.body;
  29864. var mesh = this._registeredMeshes[i].mesh;
  29865. if (!this._registeredMeshes[i].delta) {
  29866. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29867. }
  29868. if (!body.sleeping) {
  29869. //TODO check that
  29870. if (body.shapes.next) {
  29871. var parentShape = this._getLastShape(body);
  29872. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29873. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29874. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29875. }
  29876. else {
  29877. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29878. }
  29879. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29880. mesh.computeWorldMatrix();
  29881. }
  29882. //check if the collide callback is set.
  29883. if (mesh.onPhysicsCollide) {
  29884. var meshUniqueName = mesh.uniqueId;
  29885. var contact = this._world.contacts;
  29886. while (contact !== null) {
  29887. //is this body colliding with any other?
  29888. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29889. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29890. //get the mesh and execute the callback
  29891. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29892. if (otherMesh)
  29893. mesh.onPhysicsCollide(otherMesh, contact);
  29894. }
  29895. contact = contact.next;
  29896. }
  29897. }
  29898. }
  29899. };
  29900. return OimoJSPlugin;
  29901. })();
  29902. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29903. })(BABYLON || (BABYLON = {}));
  29904. var BABYLON;
  29905. (function (BABYLON) {
  29906. var DisplayPassPostProcess = (function (_super) {
  29907. __extends(DisplayPassPostProcess, _super);
  29908. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29909. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29910. }
  29911. return DisplayPassPostProcess;
  29912. })(BABYLON.PostProcess);
  29913. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29914. })(BABYLON || (BABYLON = {}));
  29915. var BABYLON;
  29916. (function (BABYLON) {
  29917. var SimplificationSettings = (function () {
  29918. function SimplificationSettings(quality, distance, optimizeMesh) {
  29919. this.quality = quality;
  29920. this.distance = distance;
  29921. this.optimizeMesh = optimizeMesh;
  29922. }
  29923. return SimplificationSettings;
  29924. })();
  29925. BABYLON.SimplificationSettings = SimplificationSettings;
  29926. var SimplificationQueue = (function () {
  29927. function SimplificationQueue() {
  29928. this.running = false;
  29929. this._simplificationArray = [];
  29930. }
  29931. SimplificationQueue.prototype.addTask = function (task) {
  29932. this._simplificationArray.push(task);
  29933. };
  29934. SimplificationQueue.prototype.executeNext = function () {
  29935. var task = this._simplificationArray.pop();
  29936. if (task) {
  29937. this.running = true;
  29938. this.runSimplification(task);
  29939. }
  29940. else {
  29941. this.running = false;
  29942. }
  29943. };
  29944. SimplificationQueue.prototype.runSimplification = function (task) {
  29945. var _this = this;
  29946. if (task.parallelProcessing) {
  29947. //parallel simplifier
  29948. task.settings.forEach(function (setting) {
  29949. var simplifier = _this.getSimplifier(task);
  29950. simplifier.simplify(setting, function (newMesh) {
  29951. task.mesh.addLODLevel(setting.distance, newMesh);
  29952. newMesh.isVisible = true;
  29953. //check if it is the last
  29954. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29955. //all done, run the success callback.
  29956. task.successCallback();
  29957. }
  29958. _this.executeNext();
  29959. });
  29960. });
  29961. }
  29962. else {
  29963. //single simplifier.
  29964. var simplifier = this.getSimplifier(task);
  29965. var runDecimation = function (setting, callback) {
  29966. simplifier.simplify(setting, function (newMesh) {
  29967. task.mesh.addLODLevel(setting.distance, newMesh);
  29968. newMesh.isVisible = true;
  29969. //run the next quality level
  29970. callback();
  29971. });
  29972. };
  29973. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29974. runDecimation(task.settings[loop.index], function () {
  29975. loop.executeNext();
  29976. });
  29977. }, function () {
  29978. //execution ended, run the success callback.
  29979. if (task.successCallback) {
  29980. task.successCallback();
  29981. }
  29982. _this.executeNext();
  29983. });
  29984. }
  29985. };
  29986. SimplificationQueue.prototype.getSimplifier = function (task) {
  29987. switch (task.simplificationType) {
  29988. case SimplificationType.QUADRATIC:
  29989. default:
  29990. return new QuadraticErrorSimplification(task.mesh);
  29991. }
  29992. };
  29993. return SimplificationQueue;
  29994. })();
  29995. BABYLON.SimplificationQueue = SimplificationQueue;
  29996. /**
  29997. * The implemented types of simplification.
  29998. * At the moment only Quadratic Error Decimation is implemented.
  29999. */
  30000. (function (SimplificationType) {
  30001. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30002. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30003. var SimplificationType = BABYLON.SimplificationType;
  30004. var DecimationTriangle = (function () {
  30005. function DecimationTriangle(vertices) {
  30006. this.vertices = vertices;
  30007. this.error = new Array(4);
  30008. this.deleted = false;
  30009. this.isDirty = false;
  30010. this.deletePending = false;
  30011. this.borderFactor = 0;
  30012. }
  30013. return DecimationTriangle;
  30014. })();
  30015. BABYLON.DecimationTriangle = DecimationTriangle;
  30016. var DecimationVertex = (function () {
  30017. function DecimationVertex(position, id) {
  30018. this.position = position;
  30019. this.id = id;
  30020. this.isBorder = true;
  30021. this.q = new QuadraticMatrix();
  30022. this.triangleCount = 0;
  30023. this.triangleStart = 0;
  30024. this.originalOffsets = [];
  30025. }
  30026. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30027. this.position.copyFrom(newPosition);
  30028. };
  30029. return DecimationVertex;
  30030. })();
  30031. BABYLON.DecimationVertex = DecimationVertex;
  30032. var QuadraticMatrix = (function () {
  30033. function QuadraticMatrix(data) {
  30034. this.data = new Array(10);
  30035. for (var i = 0; i < 10; ++i) {
  30036. if (data && data[i]) {
  30037. this.data[i] = data[i];
  30038. }
  30039. else {
  30040. this.data[i] = 0;
  30041. }
  30042. }
  30043. }
  30044. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30045. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30046. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30047. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30048. return det;
  30049. };
  30050. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30051. for (var i = 0; i < 10; ++i) {
  30052. this.data[i] += matrix.data[i];
  30053. }
  30054. };
  30055. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30056. for (var i = 0; i < 10; ++i) {
  30057. this.data[i] += data[i];
  30058. }
  30059. };
  30060. QuadraticMatrix.prototype.add = function (matrix) {
  30061. var m = new QuadraticMatrix();
  30062. for (var i = 0; i < 10; ++i) {
  30063. m.data[i] = this.data[i] + matrix.data[i];
  30064. }
  30065. return m;
  30066. };
  30067. QuadraticMatrix.FromData = function (a, b, c, d) {
  30068. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30069. };
  30070. //returning an array to avoid garbage collection
  30071. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30072. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30073. };
  30074. return QuadraticMatrix;
  30075. })();
  30076. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30077. var Reference = (function () {
  30078. function Reference(vertexId, triangleId) {
  30079. this.vertexId = vertexId;
  30080. this.triangleId = triangleId;
  30081. }
  30082. return Reference;
  30083. })();
  30084. BABYLON.Reference = Reference;
  30085. /**
  30086. * An implementation of the Quadratic Error simplification algorithm.
  30087. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30088. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30089. * @author RaananW
  30090. */
  30091. var QuadraticErrorSimplification = (function () {
  30092. function QuadraticErrorSimplification(_mesh) {
  30093. this._mesh = _mesh;
  30094. this.initialized = false;
  30095. this.syncIterations = 5000;
  30096. this.aggressiveness = 7;
  30097. this.decimationIterations = 100;
  30098. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30099. }
  30100. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30101. var _this = this;
  30102. this.initDecimatedMesh();
  30103. //iterating through the submeshes array, one after the other.
  30104. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30105. _this.initWithMesh(loop.index, function () {
  30106. _this.runDecimation(settings, loop.index, function () {
  30107. loop.executeNext();
  30108. });
  30109. }, settings.optimizeMesh);
  30110. }, function () {
  30111. setTimeout(function () {
  30112. successCallback(_this._reconstructedMesh);
  30113. }, 0);
  30114. });
  30115. };
  30116. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30117. var _this = this;
  30118. var gCount = 0;
  30119. triangle.vertices.forEach(function (vertex) {
  30120. var count = 0;
  30121. var vPos = vertex.position;
  30122. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30123. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30124. ++count;
  30125. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30126. ++count;
  30127. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30128. ++count;
  30129. if (count > 1) {
  30130. ++gCount;
  30131. }
  30132. ;
  30133. });
  30134. if (gCount > 1) {
  30135. console.log(triangle, gCount);
  30136. }
  30137. return gCount > 1;
  30138. };
  30139. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30140. var _this = this;
  30141. var targetCount = ~~(this.triangles.length * settings.quality);
  30142. var deletedTriangles = 0;
  30143. var triangleCount = this.triangles.length;
  30144. var iterationFunction = function (iteration, callback) {
  30145. setTimeout(function () {
  30146. if (iteration % 5 === 0) {
  30147. _this.updateMesh(iteration === 0);
  30148. }
  30149. for (var i = 0; i < _this.triangles.length; ++i) {
  30150. _this.triangles[i].isDirty = false;
  30151. }
  30152. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30153. var trianglesIterator = function (i) {
  30154. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30155. var t = _this.triangles[tIdx];
  30156. if (!t)
  30157. return;
  30158. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30159. return;
  30160. }
  30161. for (var j = 0; j < 3; ++j) {
  30162. if (t.error[j] < threshold) {
  30163. var deleted0 = [];
  30164. var deleted1 = [];
  30165. var v0 = t.vertices[j];
  30166. var v1 = t.vertices[(j + 1) % 3];
  30167. if (v0.isBorder !== v1.isBorder)
  30168. continue;
  30169. var p = BABYLON.Vector3.Zero();
  30170. var n = BABYLON.Vector3.Zero();
  30171. var uv = BABYLON.Vector2.Zero();
  30172. var color = new BABYLON.Color4(0, 0, 0, 1);
  30173. _this.calculateError(v0, v1, p, n, uv, color);
  30174. var delTr = [];
  30175. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30176. continue;
  30177. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30178. continue;
  30179. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30180. continue;
  30181. var uniqueArray = [];
  30182. delTr.forEach(function (deletedT) {
  30183. if (uniqueArray.indexOf(deletedT) === -1) {
  30184. deletedT.deletePending = true;
  30185. uniqueArray.push(deletedT);
  30186. }
  30187. });
  30188. if (uniqueArray.length % 2 !== 0) {
  30189. continue;
  30190. }
  30191. v0.q = v1.q.add(v0.q);
  30192. v0.updatePosition(p);
  30193. var tStart = _this.references.length;
  30194. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30195. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30196. var tCount = _this.references.length - tStart;
  30197. if (tCount <= v0.triangleCount) {
  30198. if (tCount) {
  30199. for (var c = 0; c < tCount; c++) {
  30200. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30201. }
  30202. }
  30203. }
  30204. else {
  30205. v0.triangleStart = tStart;
  30206. }
  30207. v0.triangleCount = tCount;
  30208. break;
  30209. }
  30210. }
  30211. };
  30212. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30213. }, 0);
  30214. };
  30215. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30216. if (triangleCount - deletedTriangles <= targetCount)
  30217. loop.breakLoop();
  30218. else {
  30219. iterationFunction(loop.index, function () {
  30220. loop.executeNext();
  30221. });
  30222. }
  30223. }, function () {
  30224. setTimeout(function () {
  30225. //reconstruct this part of the mesh
  30226. _this.reconstructMesh(submeshIndex);
  30227. successCallback();
  30228. }, 0);
  30229. });
  30230. };
  30231. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30232. var _this = this;
  30233. this.vertices = [];
  30234. this.triangles = [];
  30235. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30236. var indices = this._mesh.getIndices();
  30237. var submesh = this._mesh.subMeshes[submeshIndex];
  30238. var findInVertices = function (positionToSearch) {
  30239. if (optimizeMesh) {
  30240. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30241. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30242. return _this.vertices[ii];
  30243. }
  30244. }
  30245. }
  30246. return null;
  30247. };
  30248. var vertexReferences = [];
  30249. var vertexInit = function (i) {
  30250. var offset = i + submesh.verticesStart;
  30251. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30252. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30253. vertex.originalOffsets.push(offset);
  30254. if (vertex.id === _this.vertices.length) {
  30255. _this.vertices.push(vertex);
  30256. }
  30257. vertexReferences.push(vertex.id);
  30258. };
  30259. //var totalVertices = mesh.getTotalVertices();
  30260. var totalVertices = submesh.verticesCount;
  30261. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30262. var indicesInit = function (i) {
  30263. var offset = (submesh.indexStart / 3) + i;
  30264. var pos = (offset * 3);
  30265. var i0 = indices[pos + 0];
  30266. var i1 = indices[pos + 1];
  30267. var i2 = indices[pos + 2];
  30268. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30269. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30270. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30271. var triangle = new DecimationTriangle([v0, v1, v2]);
  30272. triangle.originalOffset = pos;
  30273. _this.triangles.push(triangle);
  30274. };
  30275. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30276. _this.init(callback);
  30277. });
  30278. });
  30279. };
  30280. QuadraticErrorSimplification.prototype.init = function (callback) {
  30281. var _this = this;
  30282. var triangleInit1 = function (i) {
  30283. var t = _this.triangles[i];
  30284. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30285. for (var j = 0; j < 3; j++) {
  30286. 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))));
  30287. }
  30288. };
  30289. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30290. var triangleInit2 = function (i) {
  30291. var t = _this.triangles[i];
  30292. for (var j = 0; j < 3; ++j) {
  30293. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30294. }
  30295. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30296. };
  30297. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30298. _this.initialized = true;
  30299. callback();
  30300. });
  30301. });
  30302. };
  30303. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30304. var newTriangles = [];
  30305. var i;
  30306. for (i = 0; i < this.vertices.length; ++i) {
  30307. this.vertices[i].triangleCount = 0;
  30308. }
  30309. var t;
  30310. var j;
  30311. for (i = 0; i < this.triangles.length; ++i) {
  30312. if (!this.triangles[i].deleted) {
  30313. t = this.triangles[i];
  30314. for (j = 0; j < 3; ++j) {
  30315. t.vertices[j].triangleCount = 1;
  30316. }
  30317. newTriangles.push(t);
  30318. }
  30319. }
  30320. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30321. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30322. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30323. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30324. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30325. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30326. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30327. var vertexCount = 0;
  30328. for (i = 0; i < this.vertices.length; ++i) {
  30329. var vertex = this.vertices[i];
  30330. vertex.id = vertexCount;
  30331. if (vertex.triangleCount) {
  30332. vertex.originalOffsets.forEach(function (originalOffset) {
  30333. newPositionData.push(vertex.position.x);
  30334. newPositionData.push(vertex.position.y);
  30335. newPositionData.push(vertex.position.z);
  30336. newNormalData.push(normalData[originalOffset * 3]);
  30337. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30338. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30339. if (uvs && uvs.length) {
  30340. newUVsData.push(uvs[(originalOffset * 2)]);
  30341. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30342. }
  30343. else if (colorsData && colorsData.length) {
  30344. newColorsData.push(colorsData[(originalOffset * 4)]);
  30345. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30346. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30347. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30348. }
  30349. ++vertexCount;
  30350. });
  30351. }
  30352. }
  30353. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30354. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30355. var submeshesArray = this._reconstructedMesh.subMeshes;
  30356. this._reconstructedMesh.subMeshes = [];
  30357. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30358. var originalIndices = this._mesh.getIndices();
  30359. for (i = 0; i < newTriangles.length; ++i) {
  30360. t = newTriangles[i]; //now get the new referencing point for each vertex
  30361. [0, 1, 2].forEach(function (idx) {
  30362. var id = originalIndices[t.originalOffset + idx];
  30363. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30364. if (offset < 0)
  30365. offset = 0;
  30366. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30367. });
  30368. }
  30369. //overwriting the old vertex buffers and indices.
  30370. this._reconstructedMesh.setIndices(newIndicesArray);
  30371. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30372. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30373. if (newUVsData.length > 0)
  30374. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30375. if (newColorsData.length > 0)
  30376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30377. //create submesh
  30378. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30379. if (submeshIndex > 0) {
  30380. this._reconstructedMesh.subMeshes = [];
  30381. submeshesArray.forEach(function (submesh) {
  30382. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30383. });
  30384. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30385. }
  30386. };
  30387. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30388. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30389. this._reconstructedMesh.material = this._mesh.material;
  30390. this._reconstructedMesh.parent = this._mesh.parent;
  30391. this._reconstructedMesh.isVisible = false;
  30392. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30393. };
  30394. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30395. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30396. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30397. if (t.deleted)
  30398. continue;
  30399. var s = this.references[vertex1.triangleStart + i].vertexId;
  30400. var v1 = t.vertices[(s + 1) % 3];
  30401. var v2 = t.vertices[(s + 2) % 3];
  30402. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30403. deletedArray[i] = true;
  30404. delTr.push(t);
  30405. continue;
  30406. }
  30407. var d1 = v1.position.subtract(point);
  30408. d1 = d1.normalize();
  30409. var d2 = v2.position.subtract(point);
  30410. d2 = d2.normalize();
  30411. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30412. return true;
  30413. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30414. deletedArray[i] = false;
  30415. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30416. return true;
  30417. }
  30418. return false;
  30419. };
  30420. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30421. var newDeleted = deletedTriangles;
  30422. for (var i = 0; i < vertex.triangleCount; ++i) {
  30423. var ref = this.references[vertex.triangleStart + i];
  30424. var t = this.triangles[ref.triangleId];
  30425. if (t.deleted)
  30426. continue;
  30427. if (deletedArray[i] && t.deletePending) {
  30428. t.deleted = true;
  30429. newDeleted++;
  30430. continue;
  30431. }
  30432. t.vertices[ref.vertexId] = origVertex;
  30433. t.isDirty = true;
  30434. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30435. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30436. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30437. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30438. this.references.push(ref);
  30439. }
  30440. return newDeleted;
  30441. };
  30442. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30443. for (var i = 0; i < this.vertices.length; ++i) {
  30444. var vCount = [];
  30445. var vId = [];
  30446. var v = this.vertices[i];
  30447. var j;
  30448. for (j = 0; j < v.triangleCount; ++j) {
  30449. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30450. for (var ii = 0; ii < 3; ii++) {
  30451. var ofs = 0;
  30452. var vv = triangle.vertices[ii];
  30453. while (ofs < vCount.length) {
  30454. if (vId[ofs] === vv.id)
  30455. break;
  30456. ++ofs;
  30457. }
  30458. if (ofs === vCount.length) {
  30459. vCount.push(1);
  30460. vId.push(vv.id);
  30461. }
  30462. else {
  30463. vCount[ofs]++;
  30464. }
  30465. }
  30466. }
  30467. for (j = 0; j < vCount.length; ++j) {
  30468. if (vCount[j] === 1) {
  30469. this.vertices[vId[j]].isBorder = true;
  30470. }
  30471. else {
  30472. this.vertices[vId[j]].isBorder = false;
  30473. }
  30474. }
  30475. }
  30476. };
  30477. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30478. if (identifyBorders === void 0) { identifyBorders = false; }
  30479. var i;
  30480. if (!identifyBorders) {
  30481. var newTrianglesVector = [];
  30482. for (i = 0; i < this.triangles.length; ++i) {
  30483. if (!this.triangles[i].deleted) {
  30484. newTrianglesVector.push(this.triangles[i]);
  30485. }
  30486. }
  30487. this.triangles = newTrianglesVector;
  30488. }
  30489. for (i = 0; i < this.vertices.length; ++i) {
  30490. this.vertices[i].triangleCount = 0;
  30491. this.vertices[i].triangleStart = 0;
  30492. }
  30493. var t;
  30494. var j;
  30495. var v;
  30496. for (i = 0; i < this.triangles.length; ++i) {
  30497. t = this.triangles[i];
  30498. for (j = 0; j < 3; ++j) {
  30499. v = t.vertices[j];
  30500. v.triangleCount++;
  30501. }
  30502. }
  30503. var tStart = 0;
  30504. for (i = 0; i < this.vertices.length; ++i) {
  30505. this.vertices[i].triangleStart = tStart;
  30506. tStart += this.vertices[i].triangleCount;
  30507. this.vertices[i].triangleCount = 0;
  30508. }
  30509. var newReferences = new Array(this.triangles.length * 3);
  30510. for (i = 0; i < this.triangles.length; ++i) {
  30511. t = this.triangles[i];
  30512. for (j = 0; j < 3; ++j) {
  30513. v = t.vertices[j];
  30514. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30515. v.triangleCount++;
  30516. }
  30517. }
  30518. this.references = newReferences;
  30519. if (identifyBorders) {
  30520. this.identifyBorder();
  30521. }
  30522. };
  30523. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30524. var x = point.x;
  30525. var y = point.y;
  30526. var z = point.z;
  30527. 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
  30528. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30529. };
  30530. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30531. var q = vertex1.q.add(vertex2.q);
  30532. var border = vertex1.isBorder && vertex2.isBorder;
  30533. var error = 0;
  30534. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30535. if (qDet !== 0 && !border) {
  30536. if (!pointResult) {
  30537. pointResult = BABYLON.Vector3.Zero();
  30538. }
  30539. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30540. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30541. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30542. error = this.vertexError(q, pointResult);
  30543. }
  30544. else {
  30545. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30546. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30547. var error1 = this.vertexError(q, vertex1.position);
  30548. var error2 = this.vertexError(q, vertex2.position);
  30549. var error3 = this.vertexError(q, p3);
  30550. error = Math.min(error1, error2, error3);
  30551. if (error === error1) {
  30552. if (pointResult) {
  30553. pointResult.copyFrom(vertex1.position);
  30554. }
  30555. }
  30556. else if (error === error2) {
  30557. if (pointResult) {
  30558. pointResult.copyFrom(vertex2.position);
  30559. }
  30560. }
  30561. else {
  30562. if (pointResult) {
  30563. pointResult.copyFrom(p3);
  30564. }
  30565. }
  30566. }
  30567. return error;
  30568. };
  30569. return QuadraticErrorSimplification;
  30570. })();
  30571. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30572. })(BABYLON || (BABYLON = {}));
  30573. var BABYLON;
  30574. (function (BABYLON) {
  30575. var serializedGeometries = [];
  30576. var serializeGeometry = function (geometry, serializationGeometries) {
  30577. if (serializedGeometries[geometry.id]) {
  30578. return;
  30579. }
  30580. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30581. serializationGeometries.boxes.push(geometry.serialize());
  30582. }
  30583. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30584. serializationGeometries.spheres.push(geometry.serialize());
  30585. }
  30586. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30587. serializationGeometries.cylinders.push(geometry.serialize());
  30588. }
  30589. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30590. serializationGeometries.toruses.push(geometry.serialize());
  30591. }
  30592. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30593. serializationGeometries.grounds.push(geometry.serialize());
  30594. }
  30595. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30596. serializationGeometries.planes.push(geometry.serialize());
  30597. }
  30598. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30599. serializationGeometries.torusKnots.push(geometry.serialize());
  30600. }
  30601. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30602. throw new Error("Unknown primitive type");
  30603. }
  30604. else {
  30605. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30606. }
  30607. serializedGeometries[geometry.id] = true;
  30608. };
  30609. var serializeMesh = function (mesh, serializationScene) {
  30610. var serializationObject = {};
  30611. serializationObject.name = mesh.name;
  30612. serializationObject.id = mesh.id;
  30613. if (BABYLON.Tags.HasTags(mesh)) {
  30614. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30615. }
  30616. serializationObject.position = mesh.position.asArray();
  30617. if (mesh.rotationQuaternion) {
  30618. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30619. }
  30620. else if (mesh.rotation) {
  30621. serializationObject.rotation = mesh.rotation.asArray();
  30622. }
  30623. serializationObject.scaling = mesh.scaling.asArray();
  30624. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30625. serializationObject.isEnabled = mesh.isEnabled();
  30626. serializationObject.isVisible = mesh.isVisible;
  30627. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30628. serializationObject.pickable = mesh.isPickable;
  30629. serializationObject.receiveShadows = mesh.receiveShadows;
  30630. serializationObject.billboardMode = mesh.billboardMode;
  30631. serializationObject.visibility = mesh.visibility;
  30632. serializationObject.checkCollisions = mesh.checkCollisions;
  30633. // Parent
  30634. if (mesh.parent) {
  30635. serializationObject.parentId = mesh.parent.id;
  30636. }
  30637. // Geometry
  30638. var geometry = mesh._geometry;
  30639. if (geometry) {
  30640. var geometryId = geometry.id;
  30641. serializationObject.geometryId = geometryId;
  30642. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30643. // 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
  30644. serializeGeometry(geometry, serializationScene.geometries);
  30645. }
  30646. // SubMeshes
  30647. serializationObject.subMeshes = [];
  30648. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30649. var subMesh = mesh.subMeshes[subIndex];
  30650. serializationObject.subMeshes.push({
  30651. materialIndex: subMesh.materialIndex,
  30652. verticesStart: subMesh.verticesStart,
  30653. verticesCount: subMesh.verticesCount,
  30654. indexStart: subMesh.indexStart,
  30655. indexCount: subMesh.indexCount
  30656. });
  30657. }
  30658. }
  30659. // Material
  30660. if (mesh.material) {
  30661. serializationObject.materialId = mesh.material.id;
  30662. }
  30663. else {
  30664. mesh.material = null;
  30665. }
  30666. // Skeleton
  30667. if (mesh.skeleton) {
  30668. serializationObject.skeletonId = mesh.skeleton.id;
  30669. }
  30670. // Physics
  30671. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30672. serializationObject.physicsMass = mesh.getPhysicsMass();
  30673. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30674. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30675. switch (mesh.getPhysicsImpostor()) {
  30676. case BABYLON.PhysicsEngine.BoxImpostor:
  30677. serializationObject.physicsImpostor = 1;
  30678. break;
  30679. case BABYLON.PhysicsEngine.SphereImpostor:
  30680. serializationObject.physicsImpostor = 2;
  30681. break;
  30682. }
  30683. }
  30684. // Instances
  30685. serializationObject.instances = [];
  30686. for (var index = 0; index < mesh.instances.length; index++) {
  30687. var instance = mesh.instances[index];
  30688. var serializationInstance = {
  30689. name: instance.name,
  30690. position: instance.position.asArray(),
  30691. scaling: instance.scaling.asArray()
  30692. };
  30693. if (instance.rotationQuaternion) {
  30694. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30695. }
  30696. else if (instance.rotation) {
  30697. serializationInstance.rotation = instance.rotation.asArray();
  30698. }
  30699. serializationObject.instances.push(serializationInstance);
  30700. // Animations
  30701. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30702. serializationInstance.ranges = instance.serializeAnimationRanges();
  30703. }
  30704. // Animations
  30705. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30706. serializationObject.ranges = mesh.serializeAnimationRanges();
  30707. // Layer mask
  30708. serializationObject.layerMask = mesh.layerMask;
  30709. return serializationObject;
  30710. };
  30711. var finalizeSingleMesh = function (mesh, serializationObject) {
  30712. //only works if the mesh is already loaded
  30713. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30714. //serialize material
  30715. if (mesh.material) {
  30716. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30717. serializationObject.materials = serializationObject.materials || [];
  30718. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30719. serializationObject.materials.push(mesh.material.serialize());
  30720. }
  30721. }
  30722. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30723. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30724. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30725. serializationObject.multiMaterials.push(mesh.material.serialize());
  30726. }
  30727. }
  30728. }
  30729. //serialize geometry
  30730. var geometry = mesh._geometry;
  30731. if (geometry) {
  30732. if (!serializationObject.geometries) {
  30733. serializationObject.geometries = {};
  30734. serializationObject.geometries.boxes = [];
  30735. serializationObject.geometries.spheres = [];
  30736. serializationObject.geometries.cylinders = [];
  30737. serializationObject.geometries.toruses = [];
  30738. serializationObject.geometries.grounds = [];
  30739. serializationObject.geometries.planes = [];
  30740. serializationObject.geometries.torusKnots = [];
  30741. serializationObject.geometries.vertexData = [];
  30742. }
  30743. serializeGeometry(geometry, serializationObject.geometries);
  30744. }
  30745. // Skeletons
  30746. if (mesh.skeleton) {
  30747. serializationObject.skeletons = serializationObject.skeletons || [];
  30748. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30749. }
  30750. //serialize the actual mesh
  30751. serializationObject.meshes = serializationObject.meshes || [];
  30752. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30753. }
  30754. };
  30755. var SceneSerializer = (function () {
  30756. function SceneSerializer() {
  30757. }
  30758. SceneSerializer.Serialize = function (scene) {
  30759. var serializationObject = {};
  30760. // Scene
  30761. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30762. serializationObject.autoClear = scene.autoClear;
  30763. serializationObject.clearColor = scene.clearColor.asArray();
  30764. serializationObject.ambientColor = scene.ambientColor.asArray();
  30765. serializationObject.gravity = scene.gravity.asArray();
  30766. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30767. serializationObject.workerCollisions = scene.workerCollisions;
  30768. // Fog
  30769. if (scene.fogMode && scene.fogMode !== 0) {
  30770. serializationObject.fogMode = scene.fogMode;
  30771. serializationObject.fogColor = scene.fogColor.asArray();
  30772. serializationObject.fogStart = scene.fogStart;
  30773. serializationObject.fogEnd = scene.fogEnd;
  30774. serializationObject.fogDensity = scene.fogDensity;
  30775. }
  30776. //Physics
  30777. if (scene.isPhysicsEnabled()) {
  30778. serializationObject.physicsEnabled = true;
  30779. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30780. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30781. }
  30782. // Lights
  30783. serializationObject.lights = [];
  30784. var index;
  30785. var light;
  30786. for (index = 0; index < scene.lights.length; index++) {
  30787. light = scene.lights[index];
  30788. serializationObject.lights.push(light.serialize());
  30789. }
  30790. // Cameras
  30791. serializationObject.cameras = [];
  30792. for (index = 0; index < scene.cameras.length; index++) {
  30793. var camera = scene.cameras[index];
  30794. serializationObject.cameras.push(camera.serialize());
  30795. }
  30796. if (scene.activeCamera) {
  30797. serializationObject.activeCameraID = scene.activeCamera.id;
  30798. }
  30799. // Materials
  30800. serializationObject.materials = [];
  30801. serializationObject.multiMaterials = [];
  30802. var material;
  30803. for (index = 0; index < scene.materials.length; index++) {
  30804. material = scene.materials[index];
  30805. serializationObject.materials.push(material.serialize());
  30806. }
  30807. // MultiMaterials
  30808. serializationObject.multiMaterials = [];
  30809. for (index = 0; index < scene.multiMaterials.length; index++) {
  30810. var multiMaterial = scene.multiMaterials[index];
  30811. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30812. }
  30813. // Skeletons
  30814. serializationObject.skeletons = [];
  30815. for (index = 0; index < scene.skeletons.length; index++) {
  30816. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30817. }
  30818. // Geometries
  30819. serializationObject.geometries = {};
  30820. serializationObject.geometries.boxes = [];
  30821. serializationObject.geometries.spheres = [];
  30822. serializationObject.geometries.cylinders = [];
  30823. serializationObject.geometries.toruses = [];
  30824. serializationObject.geometries.grounds = [];
  30825. serializationObject.geometries.planes = [];
  30826. serializationObject.geometries.torusKnots = [];
  30827. serializationObject.geometries.vertexData = [];
  30828. serializedGeometries = [];
  30829. var geometries = scene.getGeometries();
  30830. for (index = 0; index < geometries.length; index++) {
  30831. var geometry = geometries[index];
  30832. if (geometry.isReady()) {
  30833. serializeGeometry(geometry, serializationObject.geometries);
  30834. }
  30835. }
  30836. // Meshes
  30837. serializationObject.meshes = [];
  30838. for (index = 0; index < scene.meshes.length; index++) {
  30839. var abstractMesh = scene.meshes[index];
  30840. if (abstractMesh instanceof BABYLON.Mesh) {
  30841. var mesh = abstractMesh;
  30842. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30843. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30844. }
  30845. }
  30846. }
  30847. // Particles Systems
  30848. serializationObject.particleSystems = [];
  30849. for (index = 0; index < scene.particleSystems.length; index++) {
  30850. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30851. }
  30852. // Lens flares
  30853. serializationObject.lensFlareSystems = [];
  30854. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30855. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30856. }
  30857. // Shadows
  30858. serializationObject.shadowGenerators = [];
  30859. for (index = 0; index < scene.lights.length; index++) {
  30860. light = scene.lights[index];
  30861. if (light.getShadowGenerator()) {
  30862. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30863. }
  30864. }
  30865. return serializationObject;
  30866. };
  30867. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30868. if (withParents === void 0) { withParents = false; }
  30869. if (withChildren === void 0) { withChildren = false; }
  30870. var serializationObject = {};
  30871. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30872. if (withParents || withChildren) {
  30873. //deliberate for loop! not for each, appended should be processed as well.
  30874. for (var i = 0; i < toSerialize.length; ++i) {
  30875. if (withChildren) {
  30876. toSerialize[i].getDescendants().forEach(function (node) {
  30877. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30878. toSerialize.push(node);
  30879. }
  30880. });
  30881. }
  30882. //make sure the array doesn't contain the object already
  30883. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30884. toSerialize.push(toSerialize[i].parent);
  30885. }
  30886. }
  30887. }
  30888. toSerialize.forEach(function (mesh) {
  30889. finalizeSingleMesh(mesh, serializationObject);
  30890. });
  30891. return serializationObject;
  30892. };
  30893. return SceneSerializer;
  30894. })();
  30895. BABYLON.SceneSerializer = SceneSerializer;
  30896. })(BABYLON || (BABYLON = {}));
  30897. var BABYLON;
  30898. (function (BABYLON) {
  30899. // Unique ID when we import meshes from Babylon to CSG
  30900. var currentCSGMeshId = 0;
  30901. // # class Vertex
  30902. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30903. // one to provide additional features like texture coordinates and vertex
  30904. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30905. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30906. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30907. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30908. // is not used anywhere else.
  30909. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30910. var Vertex = (function () {
  30911. function Vertex(pos, normal, uv) {
  30912. this.pos = pos;
  30913. this.normal = normal;
  30914. this.uv = uv;
  30915. }
  30916. Vertex.prototype.clone = function () {
  30917. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30918. };
  30919. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30920. // orientation of a polygon is flipped.
  30921. Vertex.prototype.flip = function () {
  30922. this.normal = this.normal.scale(-1);
  30923. };
  30924. // Create a new vertex between this vertex and `other` by linearly
  30925. // interpolating all properties using a parameter of `t`. Subclasses should
  30926. // override this to interpolate additional properties.
  30927. Vertex.prototype.interpolate = function (other, t) {
  30928. 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));
  30929. };
  30930. return Vertex;
  30931. })();
  30932. // # class Plane
  30933. // Represents a plane in 3D space.
  30934. var Plane = (function () {
  30935. function Plane(normal, w) {
  30936. this.normal = normal;
  30937. this.w = w;
  30938. }
  30939. Plane.FromPoints = function (a, b, c) {
  30940. var v0 = c.subtract(a);
  30941. var v1 = b.subtract(a);
  30942. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30943. return null;
  30944. }
  30945. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30946. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30947. };
  30948. Plane.prototype.clone = function () {
  30949. return new Plane(this.normal.clone(), this.w);
  30950. };
  30951. Plane.prototype.flip = function () {
  30952. this.normal.scaleInPlace(-1);
  30953. this.w = -this.w;
  30954. };
  30955. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30956. // fragments in the appropriate lists. Coplanar polygons go into either
  30957. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30958. // respect to this plane. Polygons in front or in back of this plane go into
  30959. // either `front` or `back`.
  30960. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30961. var COPLANAR = 0;
  30962. var FRONT = 1;
  30963. var BACK = 2;
  30964. var SPANNING = 3;
  30965. // Classify each point as well as the entire polygon into one of the above
  30966. // four classes.
  30967. var polygonType = 0;
  30968. var types = [];
  30969. var i;
  30970. var t;
  30971. for (i = 0; i < polygon.vertices.length; i++) {
  30972. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30973. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30974. polygonType |= type;
  30975. types.push(type);
  30976. }
  30977. // Put the polygon in the correct list, splitting it when necessary.
  30978. switch (polygonType) {
  30979. case COPLANAR:
  30980. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30981. break;
  30982. case FRONT:
  30983. front.push(polygon);
  30984. break;
  30985. case BACK:
  30986. back.push(polygon);
  30987. break;
  30988. case SPANNING:
  30989. var f = [], b = [];
  30990. for (i = 0; i < polygon.vertices.length; i++) {
  30991. var j = (i + 1) % polygon.vertices.length;
  30992. var ti = types[i], tj = types[j];
  30993. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30994. if (ti !== BACK)
  30995. f.push(vi);
  30996. if (ti !== FRONT)
  30997. b.push(ti !== BACK ? vi.clone() : vi);
  30998. if ((ti | tj) === SPANNING) {
  30999. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31000. var v = vi.interpolate(vj, t);
  31001. f.push(v);
  31002. b.push(v.clone());
  31003. }
  31004. }
  31005. var poly;
  31006. if (f.length >= 3) {
  31007. poly = new Polygon(f, polygon.shared);
  31008. if (poly.plane)
  31009. front.push(poly);
  31010. }
  31011. if (b.length >= 3) {
  31012. poly = new Polygon(b, polygon.shared);
  31013. if (poly.plane)
  31014. back.push(poly);
  31015. }
  31016. break;
  31017. }
  31018. };
  31019. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31020. // point is on the plane.
  31021. Plane.EPSILON = 1e-5;
  31022. return Plane;
  31023. })();
  31024. // # class Polygon
  31025. // Represents a convex polygon. The vertices used to initialize a polygon must
  31026. // be coplanar and form a convex loop.
  31027. //
  31028. // Each convex polygon has a `shared` property, which is shared between all
  31029. // polygons that are clones of each other or were split from the same polygon.
  31030. // This can be used to define per-polygon properties (such as surface color).
  31031. var Polygon = (function () {
  31032. function Polygon(vertices, shared) {
  31033. this.vertices = vertices;
  31034. this.shared = shared;
  31035. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31036. }
  31037. Polygon.prototype.clone = function () {
  31038. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31039. return new Polygon(vertices, this.shared);
  31040. };
  31041. Polygon.prototype.flip = function () {
  31042. this.vertices.reverse().map(function (v) { v.flip(); });
  31043. this.plane.flip();
  31044. };
  31045. return Polygon;
  31046. })();
  31047. // # class Node
  31048. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31049. // by picking a polygon to split along. That polygon (and all other coplanar
  31050. // polygons) are added directly to that node and the other polygons are added to
  31051. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31052. // no distinction between internal and leaf nodes.
  31053. var Node = (function () {
  31054. function Node(polygons) {
  31055. this.plane = null;
  31056. this.front = null;
  31057. this.back = null;
  31058. this.polygons = [];
  31059. if (polygons) {
  31060. this.build(polygons);
  31061. }
  31062. }
  31063. Node.prototype.clone = function () {
  31064. var node = new Node();
  31065. node.plane = this.plane && this.plane.clone();
  31066. node.front = this.front && this.front.clone();
  31067. node.back = this.back && this.back.clone();
  31068. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31069. return node;
  31070. };
  31071. // Convert solid space to empty space and empty space to solid space.
  31072. Node.prototype.invert = function () {
  31073. for (var i = 0; i < this.polygons.length; i++) {
  31074. this.polygons[i].flip();
  31075. }
  31076. if (this.plane) {
  31077. this.plane.flip();
  31078. }
  31079. if (this.front) {
  31080. this.front.invert();
  31081. }
  31082. if (this.back) {
  31083. this.back.invert();
  31084. }
  31085. var temp = this.front;
  31086. this.front = this.back;
  31087. this.back = temp;
  31088. };
  31089. // Recursively remove all polygons in `polygons` that are inside this BSP
  31090. // tree.
  31091. Node.prototype.clipPolygons = function (polygons) {
  31092. if (!this.plane)
  31093. return polygons.slice();
  31094. var front = [], back = [];
  31095. for (var i = 0; i < polygons.length; i++) {
  31096. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31097. }
  31098. if (this.front) {
  31099. front = this.front.clipPolygons(front);
  31100. }
  31101. if (this.back) {
  31102. back = this.back.clipPolygons(back);
  31103. }
  31104. else {
  31105. back = [];
  31106. }
  31107. return front.concat(back);
  31108. };
  31109. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31110. // `bsp`.
  31111. Node.prototype.clipTo = function (bsp) {
  31112. this.polygons = bsp.clipPolygons(this.polygons);
  31113. if (this.front)
  31114. this.front.clipTo(bsp);
  31115. if (this.back)
  31116. this.back.clipTo(bsp);
  31117. };
  31118. // Return a list of all polygons in this BSP tree.
  31119. Node.prototype.allPolygons = function () {
  31120. var polygons = this.polygons.slice();
  31121. if (this.front)
  31122. polygons = polygons.concat(this.front.allPolygons());
  31123. if (this.back)
  31124. polygons = polygons.concat(this.back.allPolygons());
  31125. return polygons;
  31126. };
  31127. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31128. // new polygons are filtered down to the bottom of the tree and become new
  31129. // nodes there. Each set of polygons is partitioned using the first polygon
  31130. // (no heuristic is used to pick a good split).
  31131. Node.prototype.build = function (polygons) {
  31132. if (!polygons.length)
  31133. return;
  31134. if (!this.plane)
  31135. this.plane = polygons[0].plane.clone();
  31136. var front = [], back = [];
  31137. for (var i = 0; i < polygons.length; i++) {
  31138. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31139. }
  31140. if (front.length) {
  31141. if (!this.front)
  31142. this.front = new Node();
  31143. this.front.build(front);
  31144. }
  31145. if (back.length) {
  31146. if (!this.back)
  31147. this.back = new Node();
  31148. this.back.build(back);
  31149. }
  31150. };
  31151. return Node;
  31152. })();
  31153. var CSG = (function () {
  31154. function CSG() {
  31155. this.polygons = new Array();
  31156. }
  31157. // Convert BABYLON.Mesh to BABYLON.CSG
  31158. CSG.FromMesh = function (mesh) {
  31159. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31160. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31161. if (mesh instanceof BABYLON.Mesh) {
  31162. mesh.computeWorldMatrix(true);
  31163. matrix = mesh.getWorldMatrix();
  31164. meshPosition = mesh.position.clone();
  31165. meshRotation = mesh.rotation.clone();
  31166. if (mesh.rotationQuaternion) {
  31167. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31168. }
  31169. meshScaling = mesh.scaling.clone();
  31170. }
  31171. else {
  31172. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31173. }
  31174. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31175. var subMeshes = mesh.subMeshes;
  31176. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31177. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31178. vertices = [];
  31179. for (var j = 0; j < 3; j++) {
  31180. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31181. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31182. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31183. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31184. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31185. vertex = new Vertex(position, normal, uv);
  31186. vertices.push(vertex);
  31187. }
  31188. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31189. // To handle the case of degenerated triangle
  31190. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31191. if (polygon.plane)
  31192. polygons.push(polygon);
  31193. }
  31194. }
  31195. var csg = CSG.FromPolygons(polygons);
  31196. csg.matrix = matrix;
  31197. csg.position = meshPosition;
  31198. csg.rotation = meshRotation;
  31199. csg.scaling = meshScaling;
  31200. csg.rotationQuaternion = meshRotationQuaternion;
  31201. currentCSGMeshId++;
  31202. return csg;
  31203. };
  31204. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31205. CSG.FromPolygons = function (polygons) {
  31206. var csg = new CSG();
  31207. csg.polygons = polygons;
  31208. return csg;
  31209. };
  31210. CSG.prototype.clone = function () {
  31211. var csg = new CSG();
  31212. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31213. csg.copyTransformAttributes(this);
  31214. return csg;
  31215. };
  31216. CSG.prototype.toPolygons = function () {
  31217. return this.polygons;
  31218. };
  31219. CSG.prototype.union = function (csg) {
  31220. var a = new Node(this.clone().polygons);
  31221. var b = new Node(csg.clone().polygons);
  31222. a.clipTo(b);
  31223. b.clipTo(a);
  31224. b.invert();
  31225. b.clipTo(a);
  31226. b.invert();
  31227. a.build(b.allPolygons());
  31228. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31229. };
  31230. CSG.prototype.unionInPlace = function (csg) {
  31231. var a = new Node(this.polygons);
  31232. var b = new Node(csg.polygons);
  31233. a.clipTo(b);
  31234. b.clipTo(a);
  31235. b.invert();
  31236. b.clipTo(a);
  31237. b.invert();
  31238. a.build(b.allPolygons());
  31239. this.polygons = a.allPolygons();
  31240. };
  31241. CSG.prototype.subtract = function (csg) {
  31242. var a = new Node(this.clone().polygons);
  31243. var b = new Node(csg.clone().polygons);
  31244. a.invert();
  31245. a.clipTo(b);
  31246. b.clipTo(a);
  31247. b.invert();
  31248. b.clipTo(a);
  31249. b.invert();
  31250. a.build(b.allPolygons());
  31251. a.invert();
  31252. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31253. };
  31254. CSG.prototype.subtractInPlace = function (csg) {
  31255. var a = new Node(this.polygons);
  31256. var b = new Node(csg.polygons);
  31257. a.invert();
  31258. a.clipTo(b);
  31259. b.clipTo(a);
  31260. b.invert();
  31261. b.clipTo(a);
  31262. b.invert();
  31263. a.build(b.allPolygons());
  31264. a.invert();
  31265. this.polygons = a.allPolygons();
  31266. };
  31267. CSG.prototype.intersect = function (csg) {
  31268. var a = new Node(this.clone().polygons);
  31269. var b = new Node(csg.clone().polygons);
  31270. a.invert();
  31271. b.clipTo(a);
  31272. b.invert();
  31273. a.clipTo(b);
  31274. b.clipTo(a);
  31275. a.build(b.allPolygons());
  31276. a.invert();
  31277. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31278. };
  31279. CSG.prototype.intersectInPlace = function (csg) {
  31280. var a = new Node(this.polygons);
  31281. var b = new Node(csg.polygons);
  31282. a.invert();
  31283. b.clipTo(a);
  31284. b.invert();
  31285. a.clipTo(b);
  31286. b.clipTo(a);
  31287. a.build(b.allPolygons());
  31288. a.invert();
  31289. this.polygons = a.allPolygons();
  31290. };
  31291. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31292. // not modified.
  31293. CSG.prototype.inverse = function () {
  31294. var csg = this.clone();
  31295. csg.inverseInPlace();
  31296. return csg;
  31297. };
  31298. CSG.prototype.inverseInPlace = function () {
  31299. this.polygons.map(function (p) { p.flip(); });
  31300. };
  31301. // This is used to keep meshes transformations so they can be restored
  31302. // when we build back a Babylon Mesh
  31303. // NB : All CSG operations are performed in world coordinates
  31304. CSG.prototype.copyTransformAttributes = function (csg) {
  31305. this.matrix = csg.matrix;
  31306. this.position = csg.position;
  31307. this.rotation = csg.rotation;
  31308. this.scaling = csg.scaling;
  31309. this.rotationQuaternion = csg.rotationQuaternion;
  31310. return this;
  31311. };
  31312. // Build Raw mesh from CSG
  31313. // Coordinates here are in world space
  31314. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31315. var matrix = this.matrix.clone();
  31316. matrix.invert();
  31317. 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;
  31318. if (keepSubMeshes) {
  31319. // Sort Polygons, since subMeshes are indices range
  31320. polygons.sort(function (a, b) {
  31321. if (a.shared.meshId === b.shared.meshId) {
  31322. return a.shared.subMeshId - b.shared.subMeshId;
  31323. }
  31324. else {
  31325. return a.shared.meshId - b.shared.meshId;
  31326. }
  31327. });
  31328. }
  31329. for (var i = 0, il = polygons.length; i < il; i++) {
  31330. polygon = polygons[i];
  31331. // Building SubMeshes
  31332. if (!subMesh_dict[polygon.shared.meshId]) {
  31333. subMesh_dict[polygon.shared.meshId] = {};
  31334. }
  31335. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31336. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31337. indexStart: +Infinity,
  31338. indexEnd: -Infinity,
  31339. materialIndex: polygon.shared.materialIndex
  31340. };
  31341. }
  31342. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31343. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31344. polygonIndices[0] = 0;
  31345. polygonIndices[1] = j - 1;
  31346. polygonIndices[2] = j;
  31347. for (var k = 0; k < 3; k++) {
  31348. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31349. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31350. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31351. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31352. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31353. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31354. // Check if 2 points can be merged
  31355. if (!(typeof vertex_idx !== 'undefined' &&
  31356. normals[vertex_idx * 3] === localNormal.x &&
  31357. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31358. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31359. uvs[vertex_idx * 2] === uv.x &&
  31360. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31361. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31362. uvs.push(uv.x, uv.y);
  31363. normals.push(normal.x, normal.y, normal.z);
  31364. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31365. }
  31366. indices.push(vertex_idx);
  31367. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31368. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31369. currentIndex++;
  31370. }
  31371. }
  31372. }
  31373. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31374. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31375. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31376. mesh.setIndices(indices);
  31377. if (keepSubMeshes) {
  31378. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31379. var materialIndexOffset = 0, materialMaxIndex;
  31380. mesh.subMeshes = new Array();
  31381. for (var m in subMesh_dict) {
  31382. materialMaxIndex = -1;
  31383. for (var sm in subMesh_dict[m]) {
  31384. subMesh_obj = subMesh_dict[m][sm];
  31385. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31386. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31387. }
  31388. materialIndexOffset += ++materialMaxIndex;
  31389. }
  31390. }
  31391. return mesh;
  31392. };
  31393. // Build Mesh from CSG taking material and transforms into account
  31394. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31395. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31396. mesh.material = material;
  31397. mesh.position.copyFrom(this.position);
  31398. mesh.rotation.copyFrom(this.rotation);
  31399. if (this.rotationQuaternion) {
  31400. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31401. }
  31402. mesh.scaling.copyFrom(this.scaling);
  31403. mesh.computeWorldMatrix(true);
  31404. return mesh;
  31405. };
  31406. return CSG;
  31407. })();
  31408. BABYLON.CSG = CSG;
  31409. })(BABYLON || (BABYLON = {}));
  31410. var BABYLON;
  31411. (function (BABYLON) {
  31412. var VRDistortionCorrectionPostProcess = (function (_super) {
  31413. __extends(VRDistortionCorrectionPostProcess, _super);
  31414. //ANY
  31415. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31416. var _this = this;
  31417. _super.call(this, name, "vrDistortionCorrection", [
  31418. 'LensCenter',
  31419. 'Scale',
  31420. 'ScaleIn',
  31421. 'HmdWarpParam'
  31422. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31423. this._isRightEye = isRightEye;
  31424. this._distortionFactors = vrMetrics.distortionK;
  31425. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31426. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31427. this.onSizeChanged = function () {
  31428. _this.aspectRatio = _this.width * .5 / _this.height;
  31429. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31430. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31431. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31432. };
  31433. this.onApply = function (effect) {
  31434. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31435. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31436. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31437. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31438. };
  31439. }
  31440. return VRDistortionCorrectionPostProcess;
  31441. })(BABYLON.PostProcess);
  31442. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31443. })(BABYLON || (BABYLON = {}));
  31444. // Mainly based on these 2 articles :
  31445. // 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
  31446. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31447. var BABYLON;
  31448. (function (BABYLON) {
  31449. (function (JoystickAxis) {
  31450. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31451. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31452. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31453. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31454. var JoystickAxis = BABYLON.JoystickAxis;
  31455. var VirtualJoystick = (function () {
  31456. function VirtualJoystick(leftJoystick) {
  31457. var _this = this;
  31458. if (leftJoystick) {
  31459. this._leftJoystick = true;
  31460. }
  31461. else {
  31462. this._leftJoystick = false;
  31463. }
  31464. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31465. VirtualJoystick._globalJoystickIndex++;
  31466. // By default left & right arrow keys are moving the X
  31467. // and up & down keys are moving the Y
  31468. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31469. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31470. this.reverseLeftRight = false;
  31471. this.reverseUpDown = false;
  31472. // collections of pointers
  31473. this._touches = new BABYLON.SmartCollection();
  31474. this.deltaPosition = BABYLON.Vector3.Zero();
  31475. this._joystickSensibility = 25;
  31476. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31477. this._rotationSpeed = 25;
  31478. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31479. this._rotateOnAxisRelativeToMesh = false;
  31480. this._onResize = function (evt) {
  31481. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31482. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31483. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31484. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31485. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31486. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31487. };
  31488. // injecting a canvas element on top of the canvas 3D game
  31489. if (!VirtualJoystick.vjCanvas) {
  31490. window.addEventListener("resize", this._onResize, false);
  31491. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31492. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31493. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31494. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31495. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31496. VirtualJoystick.vjCanvas.style.width = "100%";
  31497. VirtualJoystick.vjCanvas.style.height = "100%";
  31498. VirtualJoystick.vjCanvas.style.position = "absolute";
  31499. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31500. VirtualJoystick.vjCanvas.style.top = "0px";
  31501. VirtualJoystick.vjCanvas.style.left = "0px";
  31502. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31503. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31504. // Support for jQuery PEP polyfill
  31505. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31506. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31507. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31508. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31509. document.body.appendChild(VirtualJoystick.vjCanvas);
  31510. }
  31511. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31512. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31513. this.pressed = false;
  31514. // default joystick color
  31515. this._joystickColor = "cyan";
  31516. this._joystickPointerID = -1;
  31517. // current joystick position
  31518. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31519. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31520. // origin joystick position
  31521. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31522. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31523. this._onPointerDownHandlerRef = function (evt) {
  31524. _this._onPointerDown(evt);
  31525. };
  31526. this._onPointerMoveHandlerRef = function (evt) {
  31527. _this._onPointerMove(evt);
  31528. };
  31529. this._onPointerOutHandlerRef = function (evt) {
  31530. _this._onPointerUp(evt);
  31531. };
  31532. this._onPointerUpHandlerRef = function (evt) {
  31533. _this._onPointerUp(evt);
  31534. };
  31535. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31536. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31537. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31538. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31539. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31540. evt.preventDefault(); // Disables system menu
  31541. }, false);
  31542. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31543. }
  31544. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31545. this._joystickSensibility = newJoystickSensibility;
  31546. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31547. };
  31548. VirtualJoystick.prototype._onPointerDown = function (e) {
  31549. var positionOnScreenCondition;
  31550. e.preventDefault();
  31551. if (this._leftJoystick === true) {
  31552. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31553. }
  31554. else {
  31555. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31556. }
  31557. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31558. // First contact will be dedicated to the virtual joystick
  31559. this._joystickPointerID = e.pointerId;
  31560. this._joystickPointerStartPos.x = e.clientX;
  31561. this._joystickPointerStartPos.y = e.clientY;
  31562. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31563. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31564. this._deltaJoystickVector.x = 0;
  31565. this._deltaJoystickVector.y = 0;
  31566. this.pressed = true;
  31567. this._touches.add(e.pointerId.toString(), e);
  31568. }
  31569. else {
  31570. // You can only trigger the action buttons with a joystick declared
  31571. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31572. this._action();
  31573. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31574. }
  31575. }
  31576. };
  31577. VirtualJoystick.prototype._onPointerMove = function (e) {
  31578. // If the current pointer is the one associated to the joystick (first touch contact)
  31579. if (this._joystickPointerID == e.pointerId) {
  31580. this._joystickPointerPos.x = e.clientX;
  31581. this._joystickPointerPos.y = e.clientY;
  31582. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31583. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31584. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31585. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31586. switch (this._axisTargetedByLeftAndRight) {
  31587. case JoystickAxis.X:
  31588. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31589. break;
  31590. case JoystickAxis.Y:
  31591. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31592. break;
  31593. case JoystickAxis.Z:
  31594. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31595. break;
  31596. }
  31597. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31598. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31599. switch (this._axisTargetedByUpAndDown) {
  31600. case JoystickAxis.X:
  31601. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31602. break;
  31603. case JoystickAxis.Y:
  31604. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31605. break;
  31606. case JoystickAxis.Z:
  31607. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31608. break;
  31609. }
  31610. }
  31611. else {
  31612. if (this._touches.item(e.pointerId.toString())) {
  31613. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31614. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31615. }
  31616. }
  31617. };
  31618. VirtualJoystick.prototype._onPointerUp = function (e) {
  31619. if (this._joystickPointerID == e.pointerId) {
  31620. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31621. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31622. this._joystickPointerID = -1;
  31623. this.pressed = false;
  31624. }
  31625. else {
  31626. var touch = this._touches.item(e.pointerId.toString());
  31627. if (touch) {
  31628. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31629. }
  31630. }
  31631. this._deltaJoystickVector.x = 0;
  31632. this._deltaJoystickVector.y = 0;
  31633. this._touches.remove(e.pointerId.toString());
  31634. };
  31635. /**
  31636. * Change the color of the virtual joystick
  31637. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31638. */
  31639. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31640. this._joystickColor = newColor;
  31641. };
  31642. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31643. this._action = action;
  31644. };
  31645. // Define which axis you'd like to control for left & right
  31646. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31647. switch (axis) {
  31648. case JoystickAxis.X:
  31649. case JoystickAxis.Y:
  31650. case JoystickAxis.Z:
  31651. this._axisTargetedByLeftAndRight = axis;
  31652. break;
  31653. default:
  31654. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31655. break;
  31656. }
  31657. };
  31658. // Define which axis you'd like to control for up & down
  31659. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31660. switch (axis) {
  31661. case JoystickAxis.X:
  31662. case JoystickAxis.Y:
  31663. case JoystickAxis.Z:
  31664. this._axisTargetedByUpAndDown = axis;
  31665. break;
  31666. default:
  31667. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31668. break;
  31669. }
  31670. };
  31671. VirtualJoystick.prototype._clearCanvas = function () {
  31672. if (this._leftJoystick) {
  31673. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31674. }
  31675. else {
  31676. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31677. }
  31678. };
  31679. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31680. var _this = this;
  31681. if (this.pressed) {
  31682. this._touches.forEach(function (touch) {
  31683. if (touch.pointerId === _this._joystickPointerID) {
  31684. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31685. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31686. VirtualJoystick.vjCanvasContext.beginPath();
  31687. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31688. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31689. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31690. VirtualJoystick.vjCanvasContext.stroke();
  31691. VirtualJoystick.vjCanvasContext.closePath();
  31692. VirtualJoystick.vjCanvasContext.beginPath();
  31693. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31694. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31695. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31696. VirtualJoystick.vjCanvasContext.stroke();
  31697. VirtualJoystick.vjCanvasContext.closePath();
  31698. VirtualJoystick.vjCanvasContext.beginPath();
  31699. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31700. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31701. VirtualJoystick.vjCanvasContext.stroke();
  31702. VirtualJoystick.vjCanvasContext.closePath();
  31703. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31704. }
  31705. else {
  31706. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31707. VirtualJoystick.vjCanvasContext.beginPath();
  31708. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31709. VirtualJoystick.vjCanvasContext.beginPath();
  31710. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31711. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31712. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31713. VirtualJoystick.vjCanvasContext.stroke();
  31714. VirtualJoystick.vjCanvasContext.closePath();
  31715. touch.prevX = touch.x;
  31716. touch.prevY = touch.y;
  31717. }
  31718. ;
  31719. });
  31720. }
  31721. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31722. };
  31723. VirtualJoystick.prototype.releaseCanvas = function () {
  31724. if (VirtualJoystick.vjCanvas) {
  31725. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31726. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31727. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31728. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31729. window.removeEventListener("resize", this._onResize);
  31730. document.body.removeChild(VirtualJoystick.vjCanvas);
  31731. VirtualJoystick.vjCanvas = null;
  31732. }
  31733. };
  31734. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31735. VirtualJoystick._globalJoystickIndex = 0;
  31736. return VirtualJoystick;
  31737. })();
  31738. BABYLON.VirtualJoystick = VirtualJoystick;
  31739. })(BABYLON || (BABYLON = {}));
  31740. var BABYLON;
  31741. (function (BABYLON) {
  31742. // We're mainly based on the logic defined into the FreeCamera code
  31743. var VirtualJoysticksCamera = (function (_super) {
  31744. __extends(VirtualJoysticksCamera, _super);
  31745. function VirtualJoysticksCamera(name, position, scene) {
  31746. _super.call(this, name, position, scene);
  31747. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31748. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31749. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31750. this._leftjoystick.setJoystickSensibility(0.15);
  31751. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31752. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31753. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31754. this._rightjoystick.reverseUpDown = true;
  31755. this._rightjoystick.setJoystickSensibility(0.05);
  31756. this._rightjoystick.setJoystickColor("yellow");
  31757. }
  31758. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31759. return this._leftjoystick;
  31760. };
  31761. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31762. return this._rightjoystick;
  31763. };
  31764. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31765. var speed = this._computeLocalCameraSpeed() * 50;
  31766. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31767. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31768. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31769. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31770. if (!this._leftjoystick.pressed) {
  31771. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31772. }
  31773. if (!this._rightjoystick.pressed) {
  31774. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31775. }
  31776. _super.prototype._checkInputs.call(this);
  31777. };
  31778. VirtualJoysticksCamera.prototype.dispose = function () {
  31779. this._leftjoystick.releaseCanvas();
  31780. _super.prototype.dispose.call(this);
  31781. };
  31782. return VirtualJoysticksCamera;
  31783. })(BABYLON.FreeCamera);
  31784. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31785. })(BABYLON || (BABYLON = {}));
  31786. var BABYLON;
  31787. (function (BABYLON) {
  31788. var AnaglyphPostProcess = (function (_super) {
  31789. __extends(AnaglyphPostProcess, _super);
  31790. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31791. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31792. }
  31793. return AnaglyphPostProcess;
  31794. })(BABYLON.PostProcess);
  31795. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31796. })(BABYLON || (BABYLON = {}));
  31797. var BABYLON;
  31798. (function (BABYLON) {
  31799. var OutlineRenderer = (function () {
  31800. function OutlineRenderer(scene) {
  31801. this._scene = scene;
  31802. }
  31803. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31804. var _this = this;
  31805. if (useOverlay === void 0) { useOverlay = false; }
  31806. var scene = this._scene;
  31807. var engine = this._scene.getEngine();
  31808. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31809. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31810. return;
  31811. }
  31812. var mesh = subMesh.getRenderingMesh();
  31813. var material = subMesh.getMaterial();
  31814. engine.enableEffect(this._effect);
  31815. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31816. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31817. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31818. // Bones
  31819. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31820. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31821. }
  31822. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31823. // Alpha test
  31824. if (material && material.needAlphaTesting()) {
  31825. var alphaTexture = material.getAlphaTestTexture();
  31826. this._effect.setTexture("diffuseSampler", alphaTexture);
  31827. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31828. }
  31829. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31830. };
  31831. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31832. var defines = [];
  31833. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31834. var mesh = subMesh.getMesh();
  31835. var material = subMesh.getMaterial();
  31836. // Alpha test
  31837. if (material && material.needAlphaTesting()) {
  31838. defines.push("#define ALPHATEST");
  31839. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31840. attribs.push(BABYLON.VertexBuffer.UVKind);
  31841. defines.push("#define UV1");
  31842. }
  31843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31845. defines.push("#define UV2");
  31846. }
  31847. }
  31848. // Bones
  31849. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31850. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31851. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31852. if (mesh.numBoneInfluencers > 4) {
  31853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31855. }
  31856. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31857. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31858. }
  31859. else {
  31860. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31861. }
  31862. // Instances
  31863. if (useInstances) {
  31864. defines.push("#define INSTANCES");
  31865. attribs.push("world0");
  31866. attribs.push("world1");
  31867. attribs.push("world2");
  31868. attribs.push("world3");
  31869. }
  31870. // Get correct effect
  31871. var join = defines.join("\n");
  31872. if (this._cachedDefines !== join) {
  31873. this._cachedDefines = join;
  31874. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31875. }
  31876. return this._effect.isReady();
  31877. };
  31878. return OutlineRenderer;
  31879. })();
  31880. BABYLON.OutlineRenderer = OutlineRenderer;
  31881. })(BABYLON || (BABYLON = {}));
  31882. var BABYLON;
  31883. (function (BABYLON) {
  31884. var MeshAssetTask = (function () {
  31885. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31886. this.name = name;
  31887. this.meshesNames = meshesNames;
  31888. this.rootUrl = rootUrl;
  31889. this.sceneFilename = sceneFilename;
  31890. this.isCompleted = false;
  31891. }
  31892. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31893. var _this = this;
  31894. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31895. _this.loadedMeshes = meshes;
  31896. _this.loadedParticleSystems = particleSystems;
  31897. _this.loadedSkeletons = skeletons;
  31898. _this.isCompleted = true;
  31899. if (_this.onSuccess) {
  31900. _this.onSuccess(_this);
  31901. }
  31902. onSuccess();
  31903. }, null, function () {
  31904. if (_this.onError) {
  31905. _this.onError(_this);
  31906. }
  31907. onError();
  31908. });
  31909. };
  31910. return MeshAssetTask;
  31911. })();
  31912. BABYLON.MeshAssetTask = MeshAssetTask;
  31913. var TextFileAssetTask = (function () {
  31914. function TextFileAssetTask(name, url) {
  31915. this.name = name;
  31916. this.url = url;
  31917. this.isCompleted = false;
  31918. }
  31919. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31920. var _this = this;
  31921. BABYLON.Tools.LoadFile(this.url, function (data) {
  31922. _this.text = data;
  31923. _this.isCompleted = true;
  31924. if (_this.onSuccess) {
  31925. _this.onSuccess(_this);
  31926. }
  31927. onSuccess();
  31928. }, null, scene.database, false, function () {
  31929. if (_this.onError) {
  31930. _this.onError(_this);
  31931. }
  31932. onError();
  31933. });
  31934. };
  31935. return TextFileAssetTask;
  31936. })();
  31937. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31938. var BinaryFileAssetTask = (function () {
  31939. function BinaryFileAssetTask(name, url) {
  31940. this.name = name;
  31941. this.url = url;
  31942. this.isCompleted = false;
  31943. }
  31944. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31945. var _this = this;
  31946. BABYLON.Tools.LoadFile(this.url, function (data) {
  31947. _this.data = data;
  31948. _this.isCompleted = true;
  31949. if (_this.onSuccess) {
  31950. _this.onSuccess(_this);
  31951. }
  31952. onSuccess();
  31953. }, null, scene.database, true, function () {
  31954. if (_this.onError) {
  31955. _this.onError(_this);
  31956. }
  31957. onError();
  31958. });
  31959. };
  31960. return BinaryFileAssetTask;
  31961. })();
  31962. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31963. var ImageAssetTask = (function () {
  31964. function ImageAssetTask(name, url) {
  31965. this.name = name;
  31966. this.url = url;
  31967. this.isCompleted = false;
  31968. }
  31969. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31970. var _this = this;
  31971. var img = new Image();
  31972. img.onload = function () {
  31973. _this.image = img;
  31974. _this.isCompleted = true;
  31975. if (_this.onSuccess) {
  31976. _this.onSuccess(_this);
  31977. }
  31978. onSuccess();
  31979. };
  31980. img.onerror = function () {
  31981. if (_this.onError) {
  31982. _this.onError(_this);
  31983. }
  31984. onError();
  31985. };
  31986. img.src = this.url;
  31987. };
  31988. return ImageAssetTask;
  31989. })();
  31990. BABYLON.ImageAssetTask = ImageAssetTask;
  31991. var TextureAssetTask = (function () {
  31992. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31994. this.name = name;
  31995. this.url = url;
  31996. this.noMipmap = noMipmap;
  31997. this.invertY = invertY;
  31998. this.samplingMode = samplingMode;
  31999. this.isCompleted = false;
  32000. }
  32001. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32002. var _this = this;
  32003. var onload = function () {
  32004. _this.isCompleted = true;
  32005. if (_this.onSuccess) {
  32006. _this.onSuccess(_this);
  32007. }
  32008. onSuccess();
  32009. };
  32010. var onerror = function () {
  32011. if (_this.onError) {
  32012. _this.onError(_this);
  32013. }
  32014. onError();
  32015. };
  32016. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  32017. };
  32018. return TextureAssetTask;
  32019. })();
  32020. BABYLON.TextureAssetTask = TextureAssetTask;
  32021. var AssetsManager = (function () {
  32022. function AssetsManager(scene) {
  32023. this._tasks = new Array();
  32024. this._waitingTasksCount = 0;
  32025. this.useDefaultLoadingScreen = true;
  32026. this._scene = scene;
  32027. }
  32028. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32029. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32030. this._tasks.push(task);
  32031. return task;
  32032. };
  32033. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32034. var task = new TextFileAssetTask(taskName, url);
  32035. this._tasks.push(task);
  32036. return task;
  32037. };
  32038. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32039. var task = new BinaryFileAssetTask(taskName, url);
  32040. this._tasks.push(task);
  32041. return task;
  32042. };
  32043. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32044. var task = new ImageAssetTask(taskName, url);
  32045. this._tasks.push(task);
  32046. return task;
  32047. };
  32048. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32050. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32051. this._tasks.push(task);
  32052. return task;
  32053. };
  32054. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32055. this._waitingTasksCount--;
  32056. if (this._waitingTasksCount === 0) {
  32057. if (this.onFinish) {
  32058. this.onFinish(this._tasks);
  32059. }
  32060. this._scene.getEngine().hideLoadingUI();
  32061. }
  32062. };
  32063. AssetsManager.prototype._runTask = function (task) {
  32064. var _this = this;
  32065. task.run(this._scene, function () {
  32066. if (_this.onTaskSuccess) {
  32067. _this.onTaskSuccess(task);
  32068. }
  32069. _this._decreaseWaitingTasksCount();
  32070. }, function () {
  32071. if (_this.onTaskError) {
  32072. _this.onTaskError(task);
  32073. }
  32074. _this._decreaseWaitingTasksCount();
  32075. });
  32076. };
  32077. AssetsManager.prototype.reset = function () {
  32078. this._tasks = new Array();
  32079. return this;
  32080. };
  32081. AssetsManager.prototype.load = function () {
  32082. this._waitingTasksCount = this._tasks.length;
  32083. if (this._waitingTasksCount === 0) {
  32084. if (this.onFinish) {
  32085. this.onFinish(this._tasks);
  32086. }
  32087. return this;
  32088. }
  32089. if (this.useDefaultLoadingScreen) {
  32090. this._scene.getEngine().displayLoadingUI();
  32091. }
  32092. for (var index = 0; index < this._tasks.length; index++) {
  32093. var task = this._tasks[index];
  32094. this._runTask(task);
  32095. }
  32096. return this;
  32097. };
  32098. return AssetsManager;
  32099. })();
  32100. BABYLON.AssetsManager = AssetsManager;
  32101. })(BABYLON || (BABYLON = {}));
  32102. var BABYLON;
  32103. (function (BABYLON) {
  32104. var VRDeviceOrientationFreeCamera = (function (_super) {
  32105. __extends(VRDeviceOrientationFreeCamera, _super);
  32106. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32107. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32108. _super.call(this, name, position, scene);
  32109. this._alpha = 0;
  32110. this._beta = 0;
  32111. this._gamma = 0;
  32112. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32113. metrics.compensateDistortion = compensateDistortion;
  32114. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32115. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32116. }
  32117. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32118. this._alpha = +evt.alpha | 0;
  32119. this._beta = +evt.beta | 0;
  32120. this._gamma = +evt.gamma | 0;
  32121. if (this._gamma < 0) {
  32122. this._gamma = 90 + this._gamma;
  32123. }
  32124. else {
  32125. // Incline it in the correct angle.
  32126. this._gamma = 270 - this._gamma;
  32127. }
  32128. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32129. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32130. this.rotation.z = this._beta / 180.0 * Math.PI;
  32131. };
  32132. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32133. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32134. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32135. };
  32136. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32137. _super.prototype.detachControl.call(this, element);
  32138. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32139. };
  32140. return VRDeviceOrientationFreeCamera;
  32141. })(BABYLON.FreeCamera);
  32142. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32143. })(BABYLON || (BABYLON = {}));
  32144. var BABYLON;
  32145. (function (BABYLON) {
  32146. var WebVRFreeCamera = (function (_super) {
  32147. __extends(WebVRFreeCamera, _super);
  32148. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32149. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32150. _super.call(this, name, position, scene);
  32151. this._hmdDevice = null;
  32152. this._sensorDevice = null;
  32153. this._cacheState = null;
  32154. this._cacheQuaternion = new BABYLON.Quaternion();
  32155. this._cacheRotation = BABYLON.Vector3.Zero();
  32156. this._vrEnabled = false;
  32157. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32158. metrics.compensateDistortion = compensateDistortion;
  32159. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32160. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32161. }
  32162. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32163. var size = devices.length;
  32164. var i = 0;
  32165. // Reset devices.
  32166. this._sensorDevice = null;
  32167. this._hmdDevice = null;
  32168. // Search for a HmdDevice.
  32169. while (i < size && this._hmdDevice === null) {
  32170. if (devices[i] instanceof HMDVRDevice) {
  32171. this._hmdDevice = devices[i];
  32172. }
  32173. i++;
  32174. }
  32175. i = 0;
  32176. while (i < size && this._sensorDevice === null) {
  32177. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32178. this._sensorDevice = devices[i];
  32179. }
  32180. i++;
  32181. }
  32182. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32183. };
  32184. WebVRFreeCamera.prototype._checkInputs = function () {
  32185. if (this._vrEnabled) {
  32186. this._cacheState = this._sensorDevice.getState();
  32187. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32188. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32189. this.rotation.x = -this._cacheRotation.z;
  32190. this.rotation.y = -this._cacheRotation.y;
  32191. this.rotation.z = this._cacheRotation.x;
  32192. }
  32193. _super.prototype._checkInputs.call(this);
  32194. };
  32195. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32196. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32197. if (navigator.getVRDevices) {
  32198. navigator.getVRDevices().then(this._getWebVRDevices);
  32199. }
  32200. else if (navigator.mozGetVRDevices) {
  32201. navigator.mozGetVRDevices(this._getWebVRDevices);
  32202. }
  32203. };
  32204. WebVRFreeCamera.prototype.detachControl = function (element) {
  32205. _super.prototype.detachControl.call(this, element);
  32206. this._vrEnabled = false;
  32207. };
  32208. return WebVRFreeCamera;
  32209. })(BABYLON.FreeCamera);
  32210. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32211. })(BABYLON || (BABYLON = {}));
  32212. var BABYLON;
  32213. (function (BABYLON) {
  32214. // Standard optimizations
  32215. var SceneOptimization = (function () {
  32216. function SceneOptimization(priority) {
  32217. if (priority === void 0) { priority = 0; }
  32218. this.priority = priority;
  32219. this.apply = function (scene) {
  32220. return true; // Return true if everything that can be done was applied
  32221. };
  32222. }
  32223. return SceneOptimization;
  32224. })();
  32225. BABYLON.SceneOptimization = SceneOptimization;
  32226. var TextureOptimization = (function (_super) {
  32227. __extends(TextureOptimization, _super);
  32228. function TextureOptimization(priority, maximumSize) {
  32229. var _this = this;
  32230. if (priority === void 0) { priority = 0; }
  32231. if (maximumSize === void 0) { maximumSize = 1024; }
  32232. _super.call(this, priority);
  32233. this.priority = priority;
  32234. this.maximumSize = maximumSize;
  32235. this.apply = function (scene) {
  32236. var allDone = true;
  32237. for (var index = 0; index < scene.textures.length; index++) {
  32238. var texture = scene.textures[index];
  32239. if (!texture.canRescale) {
  32240. continue;
  32241. }
  32242. var currentSize = texture.getSize();
  32243. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32244. if (maxDimension > _this.maximumSize) {
  32245. texture.scale(0.5);
  32246. allDone = false;
  32247. }
  32248. }
  32249. return allDone;
  32250. };
  32251. }
  32252. return TextureOptimization;
  32253. })(SceneOptimization);
  32254. BABYLON.TextureOptimization = TextureOptimization;
  32255. var HardwareScalingOptimization = (function (_super) {
  32256. __extends(HardwareScalingOptimization, _super);
  32257. function HardwareScalingOptimization(priority, maximumScale) {
  32258. var _this = this;
  32259. if (priority === void 0) { priority = 0; }
  32260. if (maximumScale === void 0) { maximumScale = 2; }
  32261. _super.call(this, priority);
  32262. this.priority = priority;
  32263. this.maximumScale = maximumScale;
  32264. this._currentScale = 1;
  32265. this.apply = function (scene) {
  32266. _this._currentScale++;
  32267. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32268. return _this._currentScale >= _this.maximumScale;
  32269. };
  32270. }
  32271. return HardwareScalingOptimization;
  32272. })(SceneOptimization);
  32273. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32274. var ShadowsOptimization = (function (_super) {
  32275. __extends(ShadowsOptimization, _super);
  32276. function ShadowsOptimization() {
  32277. _super.apply(this, arguments);
  32278. this.apply = function (scene) {
  32279. scene.shadowsEnabled = false;
  32280. return true;
  32281. };
  32282. }
  32283. return ShadowsOptimization;
  32284. })(SceneOptimization);
  32285. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32286. var PostProcessesOptimization = (function (_super) {
  32287. __extends(PostProcessesOptimization, _super);
  32288. function PostProcessesOptimization() {
  32289. _super.apply(this, arguments);
  32290. this.apply = function (scene) {
  32291. scene.postProcessesEnabled = false;
  32292. return true;
  32293. };
  32294. }
  32295. return PostProcessesOptimization;
  32296. })(SceneOptimization);
  32297. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32298. var LensFlaresOptimization = (function (_super) {
  32299. __extends(LensFlaresOptimization, _super);
  32300. function LensFlaresOptimization() {
  32301. _super.apply(this, arguments);
  32302. this.apply = function (scene) {
  32303. scene.lensFlaresEnabled = false;
  32304. return true;
  32305. };
  32306. }
  32307. return LensFlaresOptimization;
  32308. })(SceneOptimization);
  32309. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32310. var ParticlesOptimization = (function (_super) {
  32311. __extends(ParticlesOptimization, _super);
  32312. function ParticlesOptimization() {
  32313. _super.apply(this, arguments);
  32314. this.apply = function (scene) {
  32315. scene.particlesEnabled = false;
  32316. return true;
  32317. };
  32318. }
  32319. return ParticlesOptimization;
  32320. })(SceneOptimization);
  32321. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32322. var RenderTargetsOptimization = (function (_super) {
  32323. __extends(RenderTargetsOptimization, _super);
  32324. function RenderTargetsOptimization() {
  32325. _super.apply(this, arguments);
  32326. this.apply = function (scene) {
  32327. scene.renderTargetsEnabled = false;
  32328. return true;
  32329. };
  32330. }
  32331. return RenderTargetsOptimization;
  32332. })(SceneOptimization);
  32333. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32334. var MergeMeshesOptimization = (function (_super) {
  32335. __extends(MergeMeshesOptimization, _super);
  32336. function MergeMeshesOptimization() {
  32337. var _this = this;
  32338. _super.apply(this, arguments);
  32339. this._canBeMerged = function (abstractMesh) {
  32340. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32341. return false;
  32342. }
  32343. var mesh = abstractMesh;
  32344. if (!mesh.isVisible || !mesh.isEnabled()) {
  32345. return false;
  32346. }
  32347. if (mesh.instances.length > 0) {
  32348. return false;
  32349. }
  32350. if (mesh.skeleton || mesh.hasLODLevels) {
  32351. return false;
  32352. }
  32353. if (mesh.parent) {
  32354. return false;
  32355. }
  32356. return true;
  32357. };
  32358. this.apply = function (scene, updateSelectionTree) {
  32359. var globalPool = scene.meshes.slice(0);
  32360. var globalLength = globalPool.length;
  32361. for (var index = 0; index < globalLength; index++) {
  32362. var currentPool = new Array();
  32363. var current = globalPool[index];
  32364. // Checks
  32365. if (!_this._canBeMerged(current)) {
  32366. continue;
  32367. }
  32368. currentPool.push(current);
  32369. // Find compatible meshes
  32370. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32371. var otherMesh = globalPool[subIndex];
  32372. if (!_this._canBeMerged(otherMesh)) {
  32373. continue;
  32374. }
  32375. if (otherMesh.material !== current.material) {
  32376. continue;
  32377. }
  32378. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32379. continue;
  32380. }
  32381. currentPool.push(otherMesh);
  32382. globalLength--;
  32383. globalPool.splice(subIndex, 1);
  32384. subIndex--;
  32385. }
  32386. if (currentPool.length < 2) {
  32387. continue;
  32388. }
  32389. // Merge meshes
  32390. BABYLON.Mesh.MergeMeshes(currentPool);
  32391. }
  32392. if (updateSelectionTree != undefined) {
  32393. if (updateSelectionTree) {
  32394. scene.createOrUpdateSelectionOctree();
  32395. }
  32396. }
  32397. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32398. scene.createOrUpdateSelectionOctree();
  32399. }
  32400. return true;
  32401. };
  32402. }
  32403. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32404. get: function () {
  32405. return MergeMeshesOptimization._UpdateSelectionTree;
  32406. },
  32407. set: function (value) {
  32408. MergeMeshesOptimization._UpdateSelectionTree = value;
  32409. },
  32410. enumerable: true,
  32411. configurable: true
  32412. });
  32413. MergeMeshesOptimization._UpdateSelectionTree = false;
  32414. return MergeMeshesOptimization;
  32415. })(SceneOptimization);
  32416. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32417. // Options
  32418. var SceneOptimizerOptions = (function () {
  32419. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32420. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32421. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32422. this.targetFrameRate = targetFrameRate;
  32423. this.trackerDuration = trackerDuration;
  32424. this.optimizations = new Array();
  32425. }
  32426. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32427. var result = new SceneOptimizerOptions(targetFrameRate);
  32428. var priority = 0;
  32429. result.optimizations.push(new MergeMeshesOptimization(priority));
  32430. result.optimizations.push(new ShadowsOptimization(priority));
  32431. result.optimizations.push(new LensFlaresOptimization(priority));
  32432. // Next priority
  32433. priority++;
  32434. result.optimizations.push(new PostProcessesOptimization(priority));
  32435. result.optimizations.push(new ParticlesOptimization(priority));
  32436. // Next priority
  32437. priority++;
  32438. result.optimizations.push(new TextureOptimization(priority, 1024));
  32439. return result;
  32440. };
  32441. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32442. var result = new SceneOptimizerOptions(targetFrameRate);
  32443. var priority = 0;
  32444. result.optimizations.push(new MergeMeshesOptimization(priority));
  32445. result.optimizations.push(new ShadowsOptimization(priority));
  32446. result.optimizations.push(new LensFlaresOptimization(priority));
  32447. // Next priority
  32448. priority++;
  32449. result.optimizations.push(new PostProcessesOptimization(priority));
  32450. result.optimizations.push(new ParticlesOptimization(priority));
  32451. // Next priority
  32452. priority++;
  32453. result.optimizations.push(new TextureOptimization(priority, 512));
  32454. // Next priority
  32455. priority++;
  32456. result.optimizations.push(new RenderTargetsOptimization(priority));
  32457. // Next priority
  32458. priority++;
  32459. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32460. return result;
  32461. };
  32462. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32463. var result = new SceneOptimizerOptions(targetFrameRate);
  32464. var priority = 0;
  32465. result.optimizations.push(new MergeMeshesOptimization(priority));
  32466. result.optimizations.push(new ShadowsOptimization(priority));
  32467. result.optimizations.push(new LensFlaresOptimization(priority));
  32468. // Next priority
  32469. priority++;
  32470. result.optimizations.push(new PostProcessesOptimization(priority));
  32471. result.optimizations.push(new ParticlesOptimization(priority));
  32472. // Next priority
  32473. priority++;
  32474. result.optimizations.push(new TextureOptimization(priority, 256));
  32475. // Next priority
  32476. priority++;
  32477. result.optimizations.push(new RenderTargetsOptimization(priority));
  32478. // Next priority
  32479. priority++;
  32480. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32481. return result;
  32482. };
  32483. return SceneOptimizerOptions;
  32484. })();
  32485. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32486. // Scene optimizer tool
  32487. var SceneOptimizer = (function () {
  32488. function SceneOptimizer() {
  32489. }
  32490. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32491. // TODO: add an epsilon
  32492. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32493. if (onSuccess) {
  32494. onSuccess();
  32495. }
  32496. return;
  32497. }
  32498. // Apply current level of optimizations
  32499. var allDone = true;
  32500. var noOptimizationApplied = true;
  32501. for (var index = 0; index < options.optimizations.length; index++) {
  32502. var optimization = options.optimizations[index];
  32503. if (optimization.priority === currentPriorityLevel) {
  32504. noOptimizationApplied = false;
  32505. allDone = allDone && optimization.apply(scene);
  32506. }
  32507. }
  32508. // If no optimization was applied, this is a failure :(
  32509. if (noOptimizationApplied) {
  32510. if (onFailure) {
  32511. onFailure();
  32512. }
  32513. return;
  32514. }
  32515. // If all optimizations were done, move to next level
  32516. if (allDone) {
  32517. currentPriorityLevel++;
  32518. }
  32519. // Let's the system running for a specific amount of time before checking FPS
  32520. scene.executeWhenReady(function () {
  32521. setTimeout(function () {
  32522. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32523. }, options.trackerDuration);
  32524. });
  32525. };
  32526. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32527. if (!options) {
  32528. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32529. }
  32530. // Let's the system running for a specific amount of time before checking FPS
  32531. scene.executeWhenReady(function () {
  32532. setTimeout(function () {
  32533. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32534. }, options.trackerDuration);
  32535. });
  32536. };
  32537. return SceneOptimizer;
  32538. })();
  32539. BABYLON.SceneOptimizer = SceneOptimizer;
  32540. })(BABYLON || (BABYLON = {}));
  32541. var BABYLON;
  32542. (function (BABYLON) {
  32543. var Internals;
  32544. (function (Internals) {
  32545. var MeshLODLevel = (function () {
  32546. function MeshLODLevel(distance, mesh) {
  32547. this.distance = distance;
  32548. this.mesh = mesh;
  32549. }
  32550. return MeshLODLevel;
  32551. })();
  32552. Internals.MeshLODLevel = MeshLODLevel;
  32553. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32554. })(BABYLON || (BABYLON = {}));
  32555. var BABYLON;
  32556. (function (BABYLON) {
  32557. var RawTexture = (function (_super) {
  32558. __extends(RawTexture, _super);
  32559. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32560. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32561. if (invertY === void 0) { invertY = false; }
  32562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32563. _super.call(this, null, scene, !generateMipMaps, invertY);
  32564. this.format = format;
  32565. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32566. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32567. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32568. }
  32569. RawTexture.prototype.update = function (data) {
  32570. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32571. };
  32572. // Statics
  32573. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32575. if (invertY === void 0) { invertY = false; }
  32576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32577. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32578. };
  32579. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32580. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32581. if (invertY === void 0) { invertY = false; }
  32582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32583. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32584. };
  32585. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32586. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32587. if (invertY === void 0) { invertY = false; }
  32588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32589. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32590. };
  32591. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32592. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32593. if (invertY === void 0) { invertY = false; }
  32594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32595. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32596. };
  32597. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32598. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32599. if (invertY === void 0) { invertY = false; }
  32600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32601. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32602. };
  32603. return RawTexture;
  32604. })(BABYLON.Texture);
  32605. BABYLON.RawTexture = RawTexture;
  32606. })(BABYLON || (BABYLON = {}));
  32607. var BABYLON;
  32608. (function (BABYLON) {
  32609. var IndexedVector2 = (function (_super) {
  32610. __extends(IndexedVector2, _super);
  32611. function IndexedVector2(original, index) {
  32612. _super.call(this, original.x, original.y);
  32613. this.index = index;
  32614. }
  32615. return IndexedVector2;
  32616. })(BABYLON.Vector2);
  32617. var PolygonPoints = (function () {
  32618. function PolygonPoints() {
  32619. this.elements = new Array();
  32620. }
  32621. PolygonPoints.prototype.add = function (originalPoints) {
  32622. var _this = this;
  32623. var result = new Array();
  32624. originalPoints.forEach(function (point) {
  32625. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32626. var newPoint = new IndexedVector2(point, _this.elements.length);
  32627. result.push(newPoint);
  32628. _this.elements.push(newPoint);
  32629. }
  32630. });
  32631. return result;
  32632. };
  32633. PolygonPoints.prototype.computeBounds = function () {
  32634. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32635. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32636. this.elements.forEach(function (point) {
  32637. // x
  32638. if (point.x < lmin.x) {
  32639. lmin.x = point.x;
  32640. }
  32641. else if (point.x > lmax.x) {
  32642. lmax.x = point.x;
  32643. }
  32644. // y
  32645. if (point.y < lmin.y) {
  32646. lmin.y = point.y;
  32647. }
  32648. else if (point.y > lmax.y) {
  32649. lmax.y = point.y;
  32650. }
  32651. });
  32652. return {
  32653. min: lmin,
  32654. max: lmax,
  32655. width: lmax.x - lmin.x,
  32656. height: lmax.y - lmin.y
  32657. };
  32658. };
  32659. return PolygonPoints;
  32660. })();
  32661. var Polygon = (function () {
  32662. function Polygon() {
  32663. }
  32664. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32665. return [
  32666. new BABYLON.Vector2(xmin, ymin),
  32667. new BABYLON.Vector2(xmax, ymin),
  32668. new BABYLON.Vector2(xmax, ymax),
  32669. new BABYLON.Vector2(xmin, ymax)
  32670. ];
  32671. };
  32672. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32673. if (cx === void 0) { cx = 0; }
  32674. if (cy === void 0) { cy = 0; }
  32675. if (numberOfSides === void 0) { numberOfSides = 32; }
  32676. var result = new Array();
  32677. var angle = 0;
  32678. var increment = (Math.PI * 2) / numberOfSides;
  32679. for (var i = 0; i < numberOfSides; i++) {
  32680. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32681. angle -= increment;
  32682. }
  32683. return result;
  32684. };
  32685. Polygon.Parse = function (input) {
  32686. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32687. var i, result = [];
  32688. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32689. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32690. }
  32691. return result;
  32692. };
  32693. Polygon.StartingAt = function (x, y) {
  32694. return BABYLON.Path2.StartingAt(x, y);
  32695. };
  32696. return Polygon;
  32697. })();
  32698. BABYLON.Polygon = Polygon;
  32699. var PolygonMeshBuilder = (function () {
  32700. function PolygonMeshBuilder(name, contours, scene) {
  32701. this._points = new PolygonPoints();
  32702. this._outlinepoints = new PolygonPoints();
  32703. this._holes = [];
  32704. if (!("poly2tri" in window)) {
  32705. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32706. }
  32707. this._name = name;
  32708. this._scene = scene;
  32709. var points;
  32710. if (contours instanceof BABYLON.Path2) {
  32711. points = contours.getPoints();
  32712. }
  32713. else {
  32714. points = contours;
  32715. }
  32716. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32717. this._outlinepoints.add(points);
  32718. }
  32719. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32720. this._swctx.addHole(this._points.add(hole));
  32721. var holepoints = new PolygonPoints();
  32722. holepoints.add(hole);
  32723. this._holes.push(holepoints);
  32724. return this;
  32725. };
  32726. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32727. var _this = this;
  32728. if (updatable === void 0) { updatable = false; }
  32729. var result = new BABYLON.Mesh(this._name, this._scene);
  32730. var normals = [];
  32731. var positions = [];
  32732. var uvs = [];
  32733. var bounds = this._points.computeBounds();
  32734. this._points.elements.forEach(function (p) {
  32735. normals.push(0, 1.0, 0);
  32736. positions.push(p.x, 0, p.y);
  32737. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32738. });
  32739. var indices = [];
  32740. this._swctx.triangulate();
  32741. this._swctx.getTriangles().forEach(function (triangle) {
  32742. triangle.getPoints().forEach(function (point) {
  32743. indices.push(point.index);
  32744. });
  32745. });
  32746. if (depth > 0) {
  32747. var positionscount = (positions.length / 3); //get the current pointcount
  32748. this._points.elements.forEach(function (p) {
  32749. normals.push(0, -1.0, 0);
  32750. positions.push(p.x, -depth, p.y);
  32751. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32752. });
  32753. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32754. var p2;
  32755. var poscounter = 0;
  32756. this._swctx.getTriangles().forEach(function (triangle) {
  32757. triangle.getPoints().forEach(function (point) {
  32758. switch (poscounter) {
  32759. case 0:
  32760. p1 = point;
  32761. break;
  32762. case 1:
  32763. p2 = point;
  32764. break;
  32765. case 2:
  32766. indices.push(point.index + positionscount);
  32767. indices.push(p2.index + positionscount);
  32768. indices.push(p1.index + positionscount);
  32769. poscounter = -1;
  32770. break;
  32771. }
  32772. poscounter++;
  32773. //indices.push((<IndexedVector2>point).index + positionscount);
  32774. });
  32775. });
  32776. //Add the sides
  32777. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32778. this._holes.forEach(function (hole) {
  32779. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32780. });
  32781. }
  32782. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32783. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32784. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32785. result.setIndices(indices);
  32786. return result;
  32787. };
  32788. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32789. var StartIndex = positions.length / 3;
  32790. var ulength = 0;
  32791. for (var i = 0; i < points.elements.length; i++) {
  32792. var p = points.elements[i];
  32793. var p1;
  32794. if ((i + 1) > points.elements.length - 1) {
  32795. p1 = points.elements[0];
  32796. }
  32797. else {
  32798. p1 = points.elements[i + 1];
  32799. }
  32800. positions.push(p.x, 0, p.y);
  32801. positions.push(p.x, -depth, p.y);
  32802. positions.push(p1.x, 0, p1.y);
  32803. positions.push(p1.x, -depth, p1.y);
  32804. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32805. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32806. var v3 = v2.subtract(v1);
  32807. var v4 = new BABYLON.Vector3(0, 1, 0);
  32808. var vn = BABYLON.Vector3.Cross(v3, v4);
  32809. vn = vn.normalize();
  32810. uvs.push(ulength / bounds.width, 0);
  32811. uvs.push(ulength / bounds.width, 1);
  32812. ulength += v3.length();
  32813. uvs.push((ulength / bounds.width), 0);
  32814. uvs.push((ulength / bounds.width), 1);
  32815. if (!flip) {
  32816. normals.push(-vn.x, -vn.y, -vn.z);
  32817. normals.push(-vn.x, -vn.y, -vn.z);
  32818. normals.push(-vn.x, -vn.y, -vn.z);
  32819. normals.push(-vn.x, -vn.y, -vn.z);
  32820. indices.push(StartIndex);
  32821. indices.push(StartIndex + 1);
  32822. indices.push(StartIndex + 2);
  32823. indices.push(StartIndex + 1);
  32824. indices.push(StartIndex + 3);
  32825. indices.push(StartIndex + 2);
  32826. }
  32827. else {
  32828. normals.push(vn.x, vn.y, vn.z);
  32829. normals.push(vn.x, vn.y, vn.z);
  32830. normals.push(vn.x, vn.y, vn.z);
  32831. normals.push(vn.x, vn.y, vn.z);
  32832. indices.push(StartIndex);
  32833. indices.push(StartIndex + 2);
  32834. indices.push(StartIndex + 1);
  32835. indices.push(StartIndex + 1);
  32836. indices.push(StartIndex + 2);
  32837. indices.push(StartIndex + 3);
  32838. }
  32839. StartIndex += 4;
  32840. }
  32841. ;
  32842. };
  32843. return PolygonMeshBuilder;
  32844. })();
  32845. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32846. })(BABYLON || (BABYLON = {}));
  32847. var BABYLON;
  32848. (function (BABYLON) {
  32849. var Octree = (function () {
  32850. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32851. if (maxDepth === void 0) { maxDepth = 2; }
  32852. this.maxDepth = maxDepth;
  32853. this.dynamicContent = new Array();
  32854. this._maxBlockCapacity = maxBlockCapacity || 64;
  32855. this._selectionContent = new BABYLON.SmartArray(1024);
  32856. this._creationFunc = creationFunc;
  32857. }
  32858. // Methods
  32859. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32860. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32861. };
  32862. Octree.prototype.addMesh = function (entry) {
  32863. for (var index = 0; index < this.blocks.length; index++) {
  32864. var block = this.blocks[index];
  32865. block.addEntry(entry);
  32866. }
  32867. };
  32868. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32869. this._selectionContent.reset();
  32870. for (var index = 0; index < this.blocks.length; index++) {
  32871. var block = this.blocks[index];
  32872. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32873. }
  32874. if (allowDuplicate) {
  32875. this._selectionContent.concat(this.dynamicContent);
  32876. }
  32877. else {
  32878. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32879. }
  32880. return this._selectionContent;
  32881. };
  32882. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32883. this._selectionContent.reset();
  32884. for (var index = 0; index < this.blocks.length; index++) {
  32885. var block = this.blocks[index];
  32886. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32887. }
  32888. if (allowDuplicate) {
  32889. this._selectionContent.concat(this.dynamicContent);
  32890. }
  32891. else {
  32892. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32893. }
  32894. return this._selectionContent;
  32895. };
  32896. Octree.prototype.intersectsRay = function (ray) {
  32897. this._selectionContent.reset();
  32898. for (var index = 0; index < this.blocks.length; index++) {
  32899. var block = this.blocks[index];
  32900. block.intersectsRay(ray, this._selectionContent);
  32901. }
  32902. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32903. return this._selectionContent;
  32904. };
  32905. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32906. target.blocks = new Array();
  32907. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32908. // Segmenting space
  32909. for (var x = 0; x < 2; x++) {
  32910. for (var y = 0; y < 2; y++) {
  32911. for (var z = 0; z < 2; z++) {
  32912. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32913. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32914. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32915. block.addEntries(entries);
  32916. target.blocks.push(block);
  32917. }
  32918. }
  32919. }
  32920. };
  32921. Octree.CreationFuncForMeshes = function (entry, block) {
  32922. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32923. block.entries.push(entry);
  32924. }
  32925. };
  32926. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32927. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32928. block.entries.push(entry);
  32929. }
  32930. };
  32931. return Octree;
  32932. })();
  32933. BABYLON.Octree = Octree;
  32934. })(BABYLON || (BABYLON = {}));
  32935. var BABYLON;
  32936. (function (BABYLON) {
  32937. var OctreeBlock = (function () {
  32938. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32939. this.entries = new Array();
  32940. this._boundingVectors = new Array();
  32941. this._capacity = capacity;
  32942. this._depth = depth;
  32943. this._maxDepth = maxDepth;
  32944. this._creationFunc = creationFunc;
  32945. this._minPoint = minPoint;
  32946. this._maxPoint = maxPoint;
  32947. this._boundingVectors.push(minPoint.clone());
  32948. this._boundingVectors.push(maxPoint.clone());
  32949. this._boundingVectors.push(minPoint.clone());
  32950. this._boundingVectors[2].x = maxPoint.x;
  32951. this._boundingVectors.push(minPoint.clone());
  32952. this._boundingVectors[3].y = maxPoint.y;
  32953. this._boundingVectors.push(minPoint.clone());
  32954. this._boundingVectors[4].z = maxPoint.z;
  32955. this._boundingVectors.push(maxPoint.clone());
  32956. this._boundingVectors[5].z = minPoint.z;
  32957. this._boundingVectors.push(maxPoint.clone());
  32958. this._boundingVectors[6].x = minPoint.x;
  32959. this._boundingVectors.push(maxPoint.clone());
  32960. this._boundingVectors[7].y = minPoint.y;
  32961. }
  32962. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32963. // Property
  32964. get: function () {
  32965. return this._capacity;
  32966. },
  32967. enumerable: true,
  32968. configurable: true
  32969. });
  32970. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32971. get: function () {
  32972. return this._minPoint;
  32973. },
  32974. enumerable: true,
  32975. configurable: true
  32976. });
  32977. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32978. get: function () {
  32979. return this._maxPoint;
  32980. },
  32981. enumerable: true,
  32982. configurable: true
  32983. });
  32984. // Methods
  32985. OctreeBlock.prototype.addEntry = function (entry) {
  32986. if (this.blocks) {
  32987. for (var index = 0; index < this.blocks.length; index++) {
  32988. var block = this.blocks[index];
  32989. block.addEntry(entry);
  32990. }
  32991. return;
  32992. }
  32993. this._creationFunc(entry, this);
  32994. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32995. this.createInnerBlocks();
  32996. }
  32997. };
  32998. OctreeBlock.prototype.addEntries = function (entries) {
  32999. for (var index = 0; index < entries.length; index++) {
  33000. var mesh = entries[index];
  33001. this.addEntry(mesh);
  33002. }
  33003. };
  33004. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33005. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33006. if (this.blocks) {
  33007. for (var index = 0; index < this.blocks.length; index++) {
  33008. var block = this.blocks[index];
  33009. block.select(frustumPlanes, selection, allowDuplicate);
  33010. }
  33011. return;
  33012. }
  33013. if (allowDuplicate) {
  33014. selection.concat(this.entries);
  33015. }
  33016. else {
  33017. selection.concatWithNoDuplicate(this.entries);
  33018. }
  33019. }
  33020. };
  33021. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33022. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33023. if (this.blocks) {
  33024. for (var index = 0; index < this.blocks.length; index++) {
  33025. var block = this.blocks[index];
  33026. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33027. }
  33028. return;
  33029. }
  33030. if (allowDuplicate) {
  33031. selection.concat(this.entries);
  33032. }
  33033. else {
  33034. selection.concatWithNoDuplicate(this.entries);
  33035. }
  33036. }
  33037. };
  33038. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33039. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33040. if (this.blocks) {
  33041. for (var index = 0; index < this.blocks.length; index++) {
  33042. var block = this.blocks[index];
  33043. block.intersectsRay(ray, selection);
  33044. }
  33045. return;
  33046. }
  33047. selection.concatWithNoDuplicate(this.entries);
  33048. }
  33049. };
  33050. OctreeBlock.prototype.createInnerBlocks = function () {
  33051. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33052. };
  33053. return OctreeBlock;
  33054. })();
  33055. BABYLON.OctreeBlock = OctreeBlock;
  33056. })(BABYLON || (BABYLON = {}));
  33057. var BABYLON;
  33058. (function (BABYLON) {
  33059. var BlurPostProcess = (function (_super) {
  33060. __extends(BlurPostProcess, _super);
  33061. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33062. var _this = this;
  33063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33064. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33065. this.direction = direction;
  33066. this.blurWidth = blurWidth;
  33067. this.onApply = function (effect) {
  33068. effect.setFloat2("screenSize", _this.width, _this.height);
  33069. effect.setVector2("direction", _this.direction);
  33070. effect.setFloat("blurWidth", _this.blurWidth);
  33071. };
  33072. }
  33073. return BlurPostProcess;
  33074. })(BABYLON.PostProcess);
  33075. BABYLON.BlurPostProcess = BlurPostProcess;
  33076. })(BABYLON || (BABYLON = {}));
  33077. var BABYLON;
  33078. (function (BABYLON) {
  33079. var RefractionPostProcess = (function (_super) {
  33080. __extends(RefractionPostProcess, _super);
  33081. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33082. var _this = this;
  33083. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33084. this.color = color;
  33085. this.depth = depth;
  33086. this.colorLevel = colorLevel;
  33087. this.onActivate = function (cam) {
  33088. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33089. };
  33090. this.onApply = function (effect) {
  33091. effect.setColor3("baseColor", _this.color);
  33092. effect.setFloat("depth", _this.depth);
  33093. effect.setFloat("colorLevel", _this.colorLevel);
  33094. effect.setTexture("refractionSampler", _this._refRexture);
  33095. };
  33096. }
  33097. // Methods
  33098. RefractionPostProcess.prototype.dispose = function (camera) {
  33099. if (this._refRexture) {
  33100. this._refRexture.dispose();
  33101. }
  33102. _super.prototype.dispose.call(this, camera);
  33103. };
  33104. return RefractionPostProcess;
  33105. })(BABYLON.PostProcess);
  33106. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33107. })(BABYLON || (BABYLON = {}));
  33108. var BABYLON;
  33109. (function (BABYLON) {
  33110. var BlackAndWhitePostProcess = (function (_super) {
  33111. __extends(BlackAndWhitePostProcess, _super);
  33112. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33113. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33114. }
  33115. return BlackAndWhitePostProcess;
  33116. })(BABYLON.PostProcess);
  33117. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33118. })(BABYLON || (BABYLON = {}));
  33119. var BABYLON;
  33120. (function (BABYLON) {
  33121. var ConvolutionPostProcess = (function (_super) {
  33122. __extends(ConvolutionPostProcess, _super);
  33123. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33124. var _this = this;
  33125. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33126. this.kernel = kernel;
  33127. this.onApply = function (effect) {
  33128. effect.setFloat2("screenSize", _this.width, _this.height);
  33129. effect.setArray("kernel", _this.kernel);
  33130. };
  33131. }
  33132. // Statics
  33133. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33134. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33135. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33136. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33137. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33138. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33139. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33140. return ConvolutionPostProcess;
  33141. })(BABYLON.PostProcess);
  33142. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33143. })(BABYLON || (BABYLON = {}));
  33144. var BABYLON;
  33145. (function (BABYLON) {
  33146. var FilterPostProcess = (function (_super) {
  33147. __extends(FilterPostProcess, _super);
  33148. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33149. var _this = this;
  33150. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33151. this.kernelMatrix = kernelMatrix;
  33152. this.onApply = function (effect) {
  33153. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33154. };
  33155. }
  33156. return FilterPostProcess;
  33157. })(BABYLON.PostProcess);
  33158. BABYLON.FilterPostProcess = FilterPostProcess;
  33159. })(BABYLON || (BABYLON = {}));
  33160. var BABYLON;
  33161. (function (BABYLON) {
  33162. var FxaaPostProcess = (function (_super) {
  33163. __extends(FxaaPostProcess, _super);
  33164. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33165. var _this = this;
  33166. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33167. this.onSizeChanged = function () {
  33168. _this.texelWidth = 1.0 / _this.width;
  33169. _this.texelHeight = 1.0 / _this.height;
  33170. };
  33171. this.onApply = function (effect) {
  33172. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33173. };
  33174. }
  33175. return FxaaPostProcess;
  33176. })(BABYLON.PostProcess);
  33177. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33178. })(BABYLON || (BABYLON = {}));
  33179. var BABYLON;
  33180. (function (BABYLON) {
  33181. var StereoscopicInterlacePostProcess = (function (_super) {
  33182. __extends(StereoscopicInterlacePostProcess, _super);
  33183. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33184. var _this = this;
  33185. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33186. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33187. this.onSizeChanged = function () {
  33188. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33189. };
  33190. this.onApply = function (effect) {
  33191. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33192. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33193. };
  33194. }
  33195. return StereoscopicInterlacePostProcess;
  33196. })(BABYLON.PostProcess);
  33197. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33198. })(BABYLON || (BABYLON = {}));
  33199. var BABYLON;
  33200. (function (BABYLON) {
  33201. var LensFlare = (function () {
  33202. function LensFlare(size, position, color, imgUrl, system) {
  33203. this.size = size;
  33204. this.position = position;
  33205. this.dispose = function () {
  33206. if (this.texture) {
  33207. this.texture.dispose();
  33208. }
  33209. // Remove from scene
  33210. var index = this._system.lensFlares.indexOf(this);
  33211. this._system.lensFlares.splice(index, 1);
  33212. };
  33213. this.color = color || new BABYLON.Color3(1, 1, 1);
  33214. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33215. this._system = system;
  33216. system.lensFlares.push(this);
  33217. }
  33218. return LensFlare;
  33219. })();
  33220. BABYLON.LensFlare = LensFlare;
  33221. })(BABYLON || (BABYLON = {}));
  33222. var BABYLON;
  33223. (function (BABYLON) {
  33224. var LensFlareSystem = (function () {
  33225. function LensFlareSystem(name, emitter, scene) {
  33226. this.name = name;
  33227. this.lensFlares = new Array();
  33228. this.borderLimit = 300;
  33229. this.layerMask = 0x0FFFFFFF;
  33230. this._vertexDeclaration = [2];
  33231. this._vertexStrideSize = 2 * 4;
  33232. this._isEnabled = true;
  33233. this._scene = scene;
  33234. this._emitter = emitter;
  33235. scene.lensFlareSystems.push(this);
  33236. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33237. // VBO
  33238. var vertices = [];
  33239. vertices.push(1, 1);
  33240. vertices.push(-1, 1);
  33241. vertices.push(-1, -1);
  33242. vertices.push(1, -1);
  33243. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33244. // Indices
  33245. var indices = [];
  33246. indices.push(0);
  33247. indices.push(1);
  33248. indices.push(2);
  33249. indices.push(0);
  33250. indices.push(2);
  33251. indices.push(3);
  33252. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33253. // Effects
  33254. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33255. }
  33256. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33257. get: function () {
  33258. return this._isEnabled;
  33259. },
  33260. set: function (value) {
  33261. this._isEnabled = value;
  33262. },
  33263. enumerable: true,
  33264. configurable: true
  33265. });
  33266. LensFlareSystem.prototype.getScene = function () {
  33267. return this._scene;
  33268. };
  33269. LensFlareSystem.prototype.getEmitter = function () {
  33270. return this._emitter;
  33271. };
  33272. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33273. this._emitter = newEmitter;
  33274. };
  33275. LensFlareSystem.prototype.getEmitterPosition = function () {
  33276. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33277. };
  33278. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33279. var position = this.getEmitterPosition();
  33280. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33281. this._positionX = position.x;
  33282. this._positionY = position.y;
  33283. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33284. if (position.z > 0) {
  33285. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33286. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33287. return true;
  33288. }
  33289. }
  33290. return false;
  33291. };
  33292. LensFlareSystem.prototype._isVisible = function () {
  33293. if (!this._isEnabled) {
  33294. return false;
  33295. }
  33296. var emitterPosition = this.getEmitterPosition();
  33297. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33298. var distance = direction.length();
  33299. direction.normalize();
  33300. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33301. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33302. return !pickInfo.hit || pickInfo.distance > distance;
  33303. };
  33304. LensFlareSystem.prototype.render = function () {
  33305. if (!this._effect.isReady())
  33306. return false;
  33307. var engine = this._scene.getEngine();
  33308. var viewport = this._scene.activeCamera.viewport;
  33309. var globalViewport = viewport.toScreenGlobal(engine);
  33310. // Position
  33311. if (!this.computeEffectivePosition(globalViewport)) {
  33312. return false;
  33313. }
  33314. // Visibility
  33315. if (!this._isVisible()) {
  33316. return false;
  33317. }
  33318. // Intensity
  33319. var awayX;
  33320. var awayY;
  33321. if (this._positionX < this.borderLimit + globalViewport.x) {
  33322. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33323. }
  33324. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33325. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33326. }
  33327. else {
  33328. awayX = 0;
  33329. }
  33330. if (this._positionY < this.borderLimit + globalViewport.y) {
  33331. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33332. }
  33333. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33334. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33335. }
  33336. else {
  33337. awayY = 0;
  33338. }
  33339. var away = (awayX > awayY) ? awayX : awayY;
  33340. if (away > this.borderLimit) {
  33341. away = this.borderLimit;
  33342. }
  33343. var intensity = 1.0 - (away / this.borderLimit);
  33344. if (intensity < 0) {
  33345. return false;
  33346. }
  33347. if (intensity > 1.0) {
  33348. intensity = 1.0;
  33349. }
  33350. // Position
  33351. var centerX = globalViewport.x + globalViewport.width / 2;
  33352. var centerY = globalViewport.y + globalViewport.height / 2;
  33353. var distX = centerX - this._positionX;
  33354. var distY = centerY - this._positionY;
  33355. // Effects
  33356. engine.enableEffect(this._effect);
  33357. engine.setState(false);
  33358. engine.setDepthBuffer(false);
  33359. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33360. // VBOs
  33361. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33362. // Flares
  33363. for (var index = 0; index < this.lensFlares.length; index++) {
  33364. var flare = this.lensFlares[index];
  33365. var x = centerX - (distX * flare.position);
  33366. var y = centerY - (distY * flare.position);
  33367. var cw = flare.size;
  33368. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33369. var cx = 2 * (x / globalViewport.width) - 1.0;
  33370. var cy = 1.0 - 2 * (y / globalViewport.height);
  33371. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33372. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33373. // Texture
  33374. this._effect.setTexture("textureSampler", flare.texture);
  33375. // Color
  33376. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33377. // Draw order
  33378. engine.draw(true, 0, 6);
  33379. }
  33380. engine.setDepthBuffer(true);
  33381. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33382. return true;
  33383. };
  33384. LensFlareSystem.prototype.dispose = function () {
  33385. if (this._vertexBuffer) {
  33386. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33387. this._vertexBuffer = null;
  33388. }
  33389. if (this._indexBuffer) {
  33390. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33391. this._indexBuffer = null;
  33392. }
  33393. while (this.lensFlares.length) {
  33394. this.lensFlares[0].dispose();
  33395. }
  33396. // Remove from scene
  33397. var index = this._scene.lensFlareSystems.indexOf(this);
  33398. this._scene.lensFlareSystems.splice(index, 1);
  33399. };
  33400. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33401. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33402. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33403. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33404. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33405. var parsedFlare = parsedLensFlareSystem.flares[index];
  33406. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33407. }
  33408. return lensFlareSystem;
  33409. };
  33410. LensFlareSystem.prototype.serialize = function () {
  33411. var serializationObject = {};
  33412. serializationObject.emitterId = this.getEmitter().id;
  33413. serializationObject.borderLimit = this.borderLimit;
  33414. serializationObject.flares = [];
  33415. for (var index = 0; index < this.lensFlares.length; index++) {
  33416. var flare = this.lensFlares[index];
  33417. serializationObject.flares.push({
  33418. size: flare.size,
  33419. position: flare.position,
  33420. color: flare.color.asArray(),
  33421. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33422. });
  33423. }
  33424. return serializationObject;
  33425. };
  33426. return LensFlareSystem;
  33427. })();
  33428. BABYLON.LensFlareSystem = LensFlareSystem;
  33429. })(BABYLON || (BABYLON = {}));
  33430. var BABYLON;
  33431. (function (BABYLON) {
  33432. // We're mainly based on the logic defined into the FreeCamera code
  33433. var DeviceOrientationCamera = (function (_super) {
  33434. __extends(DeviceOrientationCamera, _super);
  33435. function DeviceOrientationCamera(name, position, scene) {
  33436. var _this = this;
  33437. _super.call(this, name, position, scene);
  33438. this._offsetX = null;
  33439. this._offsetY = null;
  33440. this._orientationGamma = 0;
  33441. this._orientationBeta = 0;
  33442. this._initialOrientationGamma = 0;
  33443. this._initialOrientationBeta = 0;
  33444. this.angularSensibility = 10000.0;
  33445. this.moveSensibility = 50.0;
  33446. window.addEventListener("resize", function () {
  33447. _this._initialOrientationGamma = null;
  33448. }, false);
  33449. }
  33450. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33451. var _this = this;
  33452. if (this._attachedCanvas) {
  33453. return;
  33454. }
  33455. this._attachedCanvas = canvas;
  33456. if (!this._orientationChanged) {
  33457. this._orientationChanged = function (evt) {
  33458. if (!_this._initialOrientationGamma) {
  33459. _this._initialOrientationGamma = evt.gamma;
  33460. _this._initialOrientationBeta = evt.beta;
  33461. }
  33462. _this._orientationGamma = evt.gamma;
  33463. _this._orientationBeta = evt.beta;
  33464. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33465. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33466. };
  33467. }
  33468. window.addEventListener("deviceorientation", this._orientationChanged);
  33469. };
  33470. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33471. if (this._attachedCanvas !== canvas) {
  33472. return;
  33473. }
  33474. window.removeEventListener("deviceorientation", this._orientationChanged);
  33475. this._attachedCanvas = null;
  33476. this._orientationGamma = 0;
  33477. this._orientationBeta = 0;
  33478. this._initialOrientationGamma = 0;
  33479. this._initialOrientationBeta = 0;
  33480. };
  33481. DeviceOrientationCamera.prototype._checkInputs = function () {
  33482. if (!this._offsetX) {
  33483. return;
  33484. }
  33485. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33486. var speed = this._computeLocalCameraSpeed();
  33487. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33488. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33489. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33490. _super.prototype._checkInputs.call(this);
  33491. };
  33492. return DeviceOrientationCamera;
  33493. })(BABYLON.FreeCamera);
  33494. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33495. })(BABYLON || (BABYLON = {}));
  33496. var BABYLON;
  33497. (function (BABYLON) {
  33498. var Gamepads = (function () {
  33499. function Gamepads(ongamedpadconnected) {
  33500. var _this = this;
  33501. this.babylonGamepads = [];
  33502. this.oneGamepadConnected = false;
  33503. this.isMonitoring = false;
  33504. this.gamepadEventSupported = 'GamepadEvent' in window;
  33505. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33506. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33507. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  33508. this._callbackGamepadConnected = ongamedpadconnected;
  33509. if (this.gamepadSupportAvailable) {
  33510. // Checking if the gamepad connected event is supported (like in Firefox)
  33511. if (this.gamepadEventSupported) {
  33512. window.addEventListener('gamepadconnected', function (evt) {
  33513. _this._onGamepadConnected(evt);
  33514. }, false);
  33515. window.addEventListener('gamepaddisconnected', function (evt) {
  33516. _this._onGamepadDisconnected(evt);
  33517. }, false);
  33518. }
  33519. else {
  33520. this._startMonitoringGamepads();
  33521. }
  33522. if (!this.oneGamepadConnected) {
  33523. this._insertGamepadDOMInstructions();
  33524. }
  33525. }
  33526. else {
  33527. this._insertGamepadDOMNotSupported();
  33528. }
  33529. }
  33530. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33531. Gamepads.gamepadDOMInfo = document.createElement("div");
  33532. var buttonAImage = document.createElement("img");
  33533. buttonAImage.src = this.buttonADataURL;
  33534. var spanMessage = document.createElement("span");
  33535. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33536. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33537. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33538. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33539. Gamepads.gamepadDOMInfo.style.width = "100%";
  33540. Gamepads.gamepadDOMInfo.style.height = "48px";
  33541. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33542. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33543. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33544. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33545. buttonAImage.style.position = "relative";
  33546. buttonAImage.style.bottom = "8px";
  33547. spanMessage.style.position = "relative";
  33548. spanMessage.style.fontSize = "32px";
  33549. spanMessage.style.bottom = "32px";
  33550. spanMessage.style.color = "green";
  33551. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33552. };
  33553. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33554. Gamepads.gamepadDOMInfo = document.createElement("div");
  33555. var spanMessage = document.createElement("span");
  33556. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33557. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33558. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33559. Gamepads.gamepadDOMInfo.style.width = "100%";
  33560. Gamepads.gamepadDOMInfo.style.height = "40px";
  33561. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33562. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33563. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33564. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33565. spanMessage.style.position = "relative";
  33566. spanMessage.style.fontSize = "32px";
  33567. spanMessage.style.color = "red";
  33568. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33569. };
  33570. Gamepads.prototype.dispose = function () {
  33571. if (Gamepads.gamepadDOMInfo) {
  33572. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33573. }
  33574. };
  33575. Gamepads.prototype._onGamepadConnected = function (evt) {
  33576. var newGamepad = this._addNewGamepad(evt.gamepad);
  33577. if (this._callbackGamepadConnected)
  33578. this._callbackGamepadConnected(newGamepad);
  33579. this._startMonitoringGamepads();
  33580. };
  33581. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33582. if (!this.oneGamepadConnected) {
  33583. this.oneGamepadConnected = true;
  33584. if (Gamepads.gamepadDOMInfo) {
  33585. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33586. Gamepads.gamepadDOMInfo = null;
  33587. }
  33588. }
  33589. var newGamepad;
  33590. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33591. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33592. }
  33593. else {
  33594. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33595. }
  33596. this.babylonGamepads.push(newGamepad);
  33597. return newGamepad;
  33598. };
  33599. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33600. // Remove the gamepad from the list of gamepads to monitor.
  33601. for (var i in this.babylonGamepads) {
  33602. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33603. this.babylonGamepads.splice(i, 1);
  33604. break;
  33605. }
  33606. }
  33607. // If no gamepads are left, stop the polling loop.
  33608. if (this.babylonGamepads.length == 0) {
  33609. this._stopMonitoringGamepads();
  33610. }
  33611. };
  33612. Gamepads.prototype._startMonitoringGamepads = function () {
  33613. if (!this.isMonitoring) {
  33614. this.isMonitoring = true;
  33615. this._checkGamepadsStatus();
  33616. }
  33617. };
  33618. Gamepads.prototype._stopMonitoringGamepads = function () {
  33619. this.isMonitoring = false;
  33620. };
  33621. Gamepads.prototype._checkGamepadsStatus = function () {
  33622. var _this = this;
  33623. // updating gamepad objects
  33624. this._updateGamepadObjects();
  33625. for (var i in this.babylonGamepads) {
  33626. this.babylonGamepads[i].update();
  33627. }
  33628. if (this.isMonitoring) {
  33629. if (window.requestAnimationFrame) {
  33630. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33631. }
  33632. else if (window.mozRequestAnimationFrame) {
  33633. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33634. }
  33635. else if (window.webkitRequestAnimationFrame) {
  33636. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33637. }
  33638. }
  33639. };
  33640. // This function is called only on Chrome, which does not yet support
  33641. // connection/disconnection events, but requires you to monitor
  33642. // an array for changes.
  33643. Gamepads.prototype._updateGamepadObjects = function () {
  33644. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33645. for (var i = 0; i < gamepads.length; i++) {
  33646. if (gamepads[i]) {
  33647. if (!(gamepads[i].index in this.babylonGamepads)) {
  33648. var newGamepad = this._addNewGamepad(gamepads[i]);
  33649. if (this._callbackGamepadConnected) {
  33650. this._callbackGamepadConnected(newGamepad);
  33651. }
  33652. }
  33653. else {
  33654. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33655. }
  33656. }
  33657. }
  33658. };
  33659. return Gamepads;
  33660. })();
  33661. BABYLON.Gamepads = Gamepads;
  33662. var StickValues = (function () {
  33663. function StickValues(x, y) {
  33664. this.x = x;
  33665. this.y = y;
  33666. }
  33667. return StickValues;
  33668. })();
  33669. BABYLON.StickValues = StickValues;
  33670. var Gamepad = (function () {
  33671. function Gamepad(id, index, browserGamepad) {
  33672. this.id = id;
  33673. this.index = index;
  33674. this.browserGamepad = browserGamepad;
  33675. if (this.browserGamepad.axes.length >= 2) {
  33676. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33677. }
  33678. if (this.browserGamepad.axes.length >= 4) {
  33679. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33680. }
  33681. }
  33682. Gamepad.prototype.onleftstickchanged = function (callback) {
  33683. this._onleftstickchanged = callback;
  33684. };
  33685. Gamepad.prototype.onrightstickchanged = function (callback) {
  33686. this._onrightstickchanged = callback;
  33687. };
  33688. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33689. get: function () {
  33690. return this._leftStick;
  33691. },
  33692. set: function (newValues) {
  33693. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33694. this._onleftstickchanged(newValues);
  33695. }
  33696. this._leftStick = newValues;
  33697. },
  33698. enumerable: true,
  33699. configurable: true
  33700. });
  33701. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33702. get: function () {
  33703. return this._rightStick;
  33704. },
  33705. set: function (newValues) {
  33706. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33707. this._onrightstickchanged(newValues);
  33708. }
  33709. this._rightStick = newValues;
  33710. },
  33711. enumerable: true,
  33712. configurable: true
  33713. });
  33714. Gamepad.prototype.update = function () {
  33715. if (this._leftStick) {
  33716. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33717. }
  33718. if (this._rightStick) {
  33719. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33720. }
  33721. };
  33722. return Gamepad;
  33723. })();
  33724. BABYLON.Gamepad = Gamepad;
  33725. var GenericPad = (function (_super) {
  33726. __extends(GenericPad, _super);
  33727. function GenericPad(id, index, gamepad) {
  33728. _super.call(this, id, index, gamepad);
  33729. this.id = id;
  33730. this.index = index;
  33731. this.gamepad = gamepad;
  33732. this._buttons = new Array(gamepad.buttons.length);
  33733. }
  33734. GenericPad.prototype.onbuttondown = function (callback) {
  33735. this._onbuttondown = callback;
  33736. };
  33737. GenericPad.prototype.onbuttonup = function (callback) {
  33738. this._onbuttonup = callback;
  33739. };
  33740. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33741. if (newValue !== currentValue) {
  33742. if (this._onbuttondown && newValue === 1) {
  33743. this._onbuttondown(buttonIndex);
  33744. }
  33745. if (this._onbuttonup && newValue === 0) {
  33746. this._onbuttonup(buttonIndex);
  33747. }
  33748. }
  33749. return newValue;
  33750. };
  33751. GenericPad.prototype.update = function () {
  33752. _super.prototype.update.call(this);
  33753. for (var index = 0; index < this._buttons.length; index++) {
  33754. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33755. }
  33756. };
  33757. return GenericPad;
  33758. })(Gamepad);
  33759. BABYLON.GenericPad = GenericPad;
  33760. (function (Xbox360Button) {
  33761. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33762. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33763. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33764. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33765. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33766. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33767. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33768. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33769. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33770. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33771. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33772. var Xbox360Button = BABYLON.Xbox360Button;
  33773. (function (Xbox360Dpad) {
  33774. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33775. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33776. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33777. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33778. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33779. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33780. var Xbox360Pad = (function (_super) {
  33781. __extends(Xbox360Pad, _super);
  33782. function Xbox360Pad() {
  33783. _super.apply(this, arguments);
  33784. this._leftTrigger = 0;
  33785. this._rightTrigger = 0;
  33786. this._buttonA = 0;
  33787. this._buttonB = 0;
  33788. this._buttonX = 0;
  33789. this._buttonY = 0;
  33790. this._buttonBack = 0;
  33791. this._buttonStart = 0;
  33792. this._buttonLB = 0;
  33793. this._buttonRB = 0;
  33794. this._buttonLeftStick = 0;
  33795. this._buttonRightStick = 0;
  33796. this._dPadUp = 0;
  33797. this._dPadDown = 0;
  33798. this._dPadLeft = 0;
  33799. this._dPadRight = 0;
  33800. }
  33801. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33802. this._onlefttriggerchanged = callback;
  33803. };
  33804. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33805. this._onrighttriggerchanged = callback;
  33806. };
  33807. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33808. get: function () {
  33809. return this._leftTrigger;
  33810. },
  33811. set: function (newValue) {
  33812. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33813. this._onlefttriggerchanged(newValue);
  33814. }
  33815. this._leftTrigger = newValue;
  33816. },
  33817. enumerable: true,
  33818. configurable: true
  33819. });
  33820. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33821. get: function () {
  33822. return this._rightTrigger;
  33823. },
  33824. set: function (newValue) {
  33825. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33826. this._onrighttriggerchanged(newValue);
  33827. }
  33828. this._rightTrigger = newValue;
  33829. },
  33830. enumerable: true,
  33831. configurable: true
  33832. });
  33833. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33834. this._onbuttondown = callback;
  33835. };
  33836. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33837. this._onbuttonup = callback;
  33838. };
  33839. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33840. this._ondpaddown = callback;
  33841. };
  33842. Xbox360Pad.prototype.ondpadup = function (callback) {
  33843. this._ondpadup = callback;
  33844. };
  33845. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33846. if (newValue !== currentValue) {
  33847. if (this._onbuttondown && newValue === 1) {
  33848. this._onbuttondown(buttonType);
  33849. }
  33850. if (this._onbuttonup && newValue === 0) {
  33851. this._onbuttonup(buttonType);
  33852. }
  33853. }
  33854. return newValue;
  33855. };
  33856. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33857. if (newValue !== currentValue) {
  33858. if (this._ondpaddown && newValue === 1) {
  33859. this._ondpaddown(buttonType);
  33860. }
  33861. if (this._ondpadup && newValue === 0) {
  33862. this._ondpadup(buttonType);
  33863. }
  33864. }
  33865. return newValue;
  33866. };
  33867. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33868. get: function () {
  33869. return this._buttonA;
  33870. },
  33871. set: function (value) {
  33872. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33873. },
  33874. enumerable: true,
  33875. configurable: true
  33876. });
  33877. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33878. get: function () {
  33879. return this._buttonB;
  33880. },
  33881. set: function (value) {
  33882. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33883. },
  33884. enumerable: true,
  33885. configurable: true
  33886. });
  33887. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33888. get: function () {
  33889. return this._buttonX;
  33890. },
  33891. set: function (value) {
  33892. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33893. },
  33894. enumerable: true,
  33895. configurable: true
  33896. });
  33897. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33898. get: function () {
  33899. return this._buttonY;
  33900. },
  33901. set: function (value) {
  33902. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33903. },
  33904. enumerable: true,
  33905. configurable: true
  33906. });
  33907. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33908. get: function () {
  33909. return this._buttonStart;
  33910. },
  33911. set: function (value) {
  33912. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33913. },
  33914. enumerable: true,
  33915. configurable: true
  33916. });
  33917. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33918. get: function () {
  33919. return this._buttonBack;
  33920. },
  33921. set: function (value) {
  33922. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33923. },
  33924. enumerable: true,
  33925. configurable: true
  33926. });
  33927. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33928. get: function () {
  33929. return this._buttonLB;
  33930. },
  33931. set: function (value) {
  33932. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33933. },
  33934. enumerable: true,
  33935. configurable: true
  33936. });
  33937. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33938. get: function () {
  33939. return this._buttonRB;
  33940. },
  33941. set: function (value) {
  33942. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33943. },
  33944. enumerable: true,
  33945. configurable: true
  33946. });
  33947. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33948. get: function () {
  33949. return this._buttonLeftStick;
  33950. },
  33951. set: function (value) {
  33952. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33953. },
  33954. enumerable: true,
  33955. configurable: true
  33956. });
  33957. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33958. get: function () {
  33959. return this._buttonRightStick;
  33960. },
  33961. set: function (value) {
  33962. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33963. },
  33964. enumerable: true,
  33965. configurable: true
  33966. });
  33967. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33968. get: function () {
  33969. return this._dPadUp;
  33970. },
  33971. set: function (value) {
  33972. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33973. },
  33974. enumerable: true,
  33975. configurable: true
  33976. });
  33977. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33978. get: function () {
  33979. return this._dPadDown;
  33980. },
  33981. set: function (value) {
  33982. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33983. },
  33984. enumerable: true,
  33985. configurable: true
  33986. });
  33987. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33988. get: function () {
  33989. return this._dPadLeft;
  33990. },
  33991. set: function (value) {
  33992. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33993. },
  33994. enumerable: true,
  33995. configurable: true
  33996. });
  33997. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33998. get: function () {
  33999. return this._dPadRight;
  34000. },
  34001. set: function (value) {
  34002. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  34003. },
  34004. enumerable: true,
  34005. configurable: true
  34006. });
  34007. Xbox360Pad.prototype.update = function () {
  34008. _super.prototype.update.call(this);
  34009. this.buttonA = this.browserGamepad.buttons[0].value;
  34010. this.buttonB = this.browserGamepad.buttons[1].value;
  34011. this.buttonX = this.browserGamepad.buttons[2].value;
  34012. this.buttonY = this.browserGamepad.buttons[3].value;
  34013. this.buttonLB = this.browserGamepad.buttons[4].value;
  34014. this.buttonRB = this.browserGamepad.buttons[5].value;
  34015. this.leftTrigger = this.browserGamepad.buttons[6].value;
  34016. this.rightTrigger = this.browserGamepad.buttons[7].value;
  34017. this.buttonBack = this.browserGamepad.buttons[8].value;
  34018. this.buttonStart = this.browserGamepad.buttons[9].value;
  34019. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  34020. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  34021. this.dPadUp = this.browserGamepad.buttons[12].value;
  34022. this.dPadDown = this.browserGamepad.buttons[13].value;
  34023. this.dPadLeft = this.browserGamepad.buttons[14].value;
  34024. this.dPadRight = this.browserGamepad.buttons[15].value;
  34025. };
  34026. return Xbox360Pad;
  34027. })(Gamepad);
  34028. BABYLON.Xbox360Pad = Xbox360Pad;
  34029. })(BABYLON || (BABYLON = {}));
  34030. var BABYLON;
  34031. (function (BABYLON) {
  34032. // We're mainly based on the logic defined into the FreeCamera code
  34033. var GamepadCamera = (function (_super) {
  34034. __extends(GamepadCamera, _super);
  34035. function GamepadCamera(name, position, scene) {
  34036. var _this = this;
  34037. _super.call(this, name, position, scene);
  34038. this.angularSensibility = 200;
  34039. this.moveSensibility = 75;
  34040. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  34041. }
  34042. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  34043. // Only the first gamepad can control the camera
  34044. if (gamepad.index === 0) {
  34045. this._gamepad = gamepad;
  34046. }
  34047. };
  34048. GamepadCamera.prototype._checkInputs = function () {
  34049. if (this._gamepad) {
  34050. var LSValues = this._gamepad.leftStick;
  34051. var normalizedLX = LSValues.x / this.moveSensibility;
  34052. var normalizedLY = LSValues.y / this.moveSensibility;
  34053. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  34054. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  34055. var RSValues = this._gamepad.rightStick;
  34056. var normalizedRX = RSValues.x / this.angularSensibility;
  34057. var normalizedRY = RSValues.y / this.angularSensibility;
  34058. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  34059. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  34060. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  34061. var speed = this._computeLocalCameraSpeed() * 50.0;
  34062. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  34063. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  34064. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  34065. }
  34066. _super.prototype._checkInputs.call(this);
  34067. };
  34068. GamepadCamera.prototype.dispose = function () {
  34069. this._gamepads.dispose();
  34070. _super.prototype.dispose.call(this);
  34071. };
  34072. return GamepadCamera;
  34073. })(BABYLON.FreeCamera);
  34074. BABYLON.GamepadCamera = GamepadCamera;
  34075. })(BABYLON || (BABYLON = {}));
  34076. var BABYLON;
  34077. (function (BABYLON) {
  34078. var Analyser = (function () {
  34079. function Analyser(scene) {
  34080. this.SMOOTHING = 0.75;
  34081. this.FFT_SIZE = 512;
  34082. this.BARGRAPHAMPLITUDE = 256;
  34083. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34084. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34085. this._scene = scene;
  34086. this._audioEngine = BABYLON.Engine.audioEngine;
  34087. if (this._audioEngine.canUseWebAudio) {
  34088. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34089. this._webAudioAnalyser.minDecibels = -140;
  34090. this._webAudioAnalyser.maxDecibels = 0;
  34091. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34092. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34093. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34094. }
  34095. }
  34096. Analyser.prototype.getFrequencyBinCount = function () {
  34097. if (this._audioEngine.canUseWebAudio) {
  34098. return this._webAudioAnalyser.frequencyBinCount;
  34099. }
  34100. else {
  34101. return 0;
  34102. }
  34103. };
  34104. Analyser.prototype.getByteFrequencyData = function () {
  34105. if (this._audioEngine.canUseWebAudio) {
  34106. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34107. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34108. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34109. }
  34110. return this._byteFreqs;
  34111. };
  34112. Analyser.prototype.getByteTimeDomainData = function () {
  34113. if (this._audioEngine.canUseWebAudio) {
  34114. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34115. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34116. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34117. }
  34118. return this._byteTime;
  34119. };
  34120. Analyser.prototype.getFloatFrequencyData = function () {
  34121. if (this._audioEngine.canUseWebAudio) {
  34122. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34123. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34124. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34125. }
  34126. return this._floatFreqs;
  34127. };
  34128. Analyser.prototype.drawDebugCanvas = function () {
  34129. var _this = this;
  34130. if (this._audioEngine.canUseWebAudio) {
  34131. if (!this._debugCanvas) {
  34132. this._debugCanvas = document.createElement("canvas");
  34133. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34134. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34135. this._debugCanvas.style.position = "absolute";
  34136. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34137. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34138. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34139. document.body.appendChild(this._debugCanvas);
  34140. this._registerFunc = function () {
  34141. _this.drawDebugCanvas();
  34142. };
  34143. this._scene.registerBeforeRender(this._registerFunc);
  34144. }
  34145. if (this._registerFunc) {
  34146. var workingArray = this.getByteFrequencyData();
  34147. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34148. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34149. // Draw the frequency domain chart.
  34150. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34151. var value = workingArray[i];
  34152. var percent = value / this.BARGRAPHAMPLITUDE;
  34153. var height = this.DEBUGCANVASSIZE.height * percent;
  34154. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34155. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34156. var hue = i / this.getFrequencyBinCount() * 360;
  34157. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34158. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34159. }
  34160. }
  34161. }
  34162. };
  34163. Analyser.prototype.stopDebugCanvas = function () {
  34164. if (this._debugCanvas) {
  34165. this._scene.unregisterBeforeRender(this._registerFunc);
  34166. this._registerFunc = null;
  34167. document.body.removeChild(this._debugCanvas);
  34168. this._debugCanvas = null;
  34169. this._debugCanvasContext = null;
  34170. }
  34171. };
  34172. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34173. if (this._audioEngine.canUseWebAudio) {
  34174. inputAudioNode.connect(this._webAudioAnalyser);
  34175. this._webAudioAnalyser.connect(outputAudioNode);
  34176. }
  34177. };
  34178. Analyser.prototype.dispose = function () {
  34179. if (this._audioEngine.canUseWebAudio) {
  34180. this._webAudioAnalyser.disconnect();
  34181. }
  34182. };
  34183. return Analyser;
  34184. })();
  34185. BABYLON.Analyser = Analyser;
  34186. })(BABYLON || (BABYLON = {}));
  34187. var BABYLON;
  34188. (function (BABYLON) {
  34189. var AudioEngine = (function () {
  34190. function AudioEngine() {
  34191. this._audioContext = null;
  34192. this._audioContextInitialized = false;
  34193. this.canUseWebAudio = false;
  34194. this.WarnedWebAudioUnsupported = false;
  34195. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34196. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34197. this.canUseWebAudio = true;
  34198. }
  34199. }
  34200. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34201. get: function () {
  34202. if (!this._audioContextInitialized) {
  34203. this._initializeAudioContext();
  34204. }
  34205. return this._audioContext;
  34206. },
  34207. enumerable: true,
  34208. configurable: true
  34209. });
  34210. AudioEngine.prototype._initializeAudioContext = function () {
  34211. try {
  34212. if (this.canUseWebAudio) {
  34213. this._audioContext = new AudioContext();
  34214. // create a global volume gain node
  34215. this.masterGain = this._audioContext.createGain();
  34216. this.masterGain.gain.value = 1;
  34217. this.masterGain.connect(this._audioContext.destination);
  34218. this._audioContextInitialized = true;
  34219. }
  34220. }
  34221. catch (e) {
  34222. this.canUseWebAudio = false;
  34223. BABYLON.Tools.Error("Web Audio: " + e.message);
  34224. }
  34225. };
  34226. AudioEngine.prototype.dispose = function () {
  34227. if (this.canUseWebAudio && this._audioContextInitialized) {
  34228. if (this._connectedAnalyser) {
  34229. this._connectedAnalyser.stopDebugCanvas();
  34230. this._connectedAnalyser.dispose();
  34231. this.masterGain.disconnect();
  34232. this.masterGain.connect(this._audioContext.destination);
  34233. this._connectedAnalyser = null;
  34234. }
  34235. this.masterGain.gain.value = 1;
  34236. }
  34237. this.WarnedWebAudioUnsupported = false;
  34238. };
  34239. AudioEngine.prototype.getGlobalVolume = function () {
  34240. if (this.canUseWebAudio && this._audioContextInitialized) {
  34241. return this.masterGain.gain.value;
  34242. }
  34243. else {
  34244. return -1;
  34245. }
  34246. };
  34247. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34248. if (this.canUseWebAudio && this._audioContextInitialized) {
  34249. this.masterGain.gain.value = newVolume;
  34250. }
  34251. };
  34252. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34253. if (this._connectedAnalyser) {
  34254. this._connectedAnalyser.stopDebugCanvas();
  34255. }
  34256. if (this.canUseWebAudio && this._audioContextInitialized) {
  34257. this._connectedAnalyser = analyser;
  34258. this.masterGain.disconnect();
  34259. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34260. }
  34261. };
  34262. return AudioEngine;
  34263. })();
  34264. BABYLON.AudioEngine = AudioEngine;
  34265. })(BABYLON || (BABYLON = {}));
  34266. var BABYLON;
  34267. (function (BABYLON) {
  34268. var Sound = (function () {
  34269. /**
  34270. * Create a sound and attach it to a scene
  34271. * @param name Name of your sound
  34272. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34273. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34274. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34275. */
  34276. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34277. var _this = this;
  34278. this.autoplay = false;
  34279. this.loop = false;
  34280. this.useCustomAttenuation = false;
  34281. this.spatialSound = false;
  34282. this.refDistance = 1;
  34283. this.rolloffFactor = 1;
  34284. this.maxDistance = 100;
  34285. this.distanceModel = "linear";
  34286. this._panningModel = "equalpower";
  34287. this._playbackRate = 1;
  34288. this._streaming = false;
  34289. this._startTime = 0;
  34290. this._startOffset = 0;
  34291. this._position = BABYLON.Vector3.Zero();
  34292. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34293. this._volume = 1;
  34294. this._isLoaded = false;
  34295. this._isReadyToPlay = false;
  34296. this.isPlaying = false;
  34297. this.isPaused = false;
  34298. this._isDirectional = false;
  34299. // Used if you'd like to create a directional sound.
  34300. // If not set, the sound will be omnidirectional
  34301. this._coneInnerAngle = 360;
  34302. this._coneOuterAngle = 360;
  34303. this._coneOuterGain = 0;
  34304. this._isOutputConnected = false;
  34305. this.name = name;
  34306. this._scene = scene;
  34307. this._readyToPlayCallback = readyToPlayCallback;
  34308. // Default custom attenuation function is a linear attenuation
  34309. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34310. if (currentDistance < maxDistance) {
  34311. return currentVolume * (1 - currentDistance / maxDistance);
  34312. }
  34313. else {
  34314. return 0;
  34315. }
  34316. };
  34317. if (options) {
  34318. this.autoplay = options.autoplay || false;
  34319. this.loop = options.loop || false;
  34320. // if volume === 0, we need another way to check this option
  34321. if (options.volume !== undefined) {
  34322. this._volume = options.volume;
  34323. }
  34324. this.spatialSound = options.spatialSound || false;
  34325. this.maxDistance = options.maxDistance || 100;
  34326. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34327. this.rolloffFactor = options.rolloffFactor || 1;
  34328. this.refDistance = options.refDistance || 1;
  34329. this.distanceModel = options.distanceModel || "linear";
  34330. this._playbackRate = options.playbackRate || 1;
  34331. this._streaming = options.streaming || false;
  34332. }
  34333. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34334. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34335. this._soundGain.gain.value = this._volume;
  34336. this._inputAudioNode = this._soundGain;
  34337. this._ouputAudioNode = this._soundGain;
  34338. if (this.spatialSound) {
  34339. this._createSpatialParameters();
  34340. }
  34341. this._scene.mainSoundTrack.AddSound(this);
  34342. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34343. if (urlOrArrayBuffer) {
  34344. // If it's an URL
  34345. if (typeof (urlOrArrayBuffer) === "string") {
  34346. // Loading sound using XHR2
  34347. if (!this._streaming) {
  34348. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  34349. }
  34350. else {
  34351. this._htmlAudioElement = new Audio();
  34352. this._htmlAudioElement.src = urlOrArrayBuffer;
  34353. this._htmlAudioElement.controls = false;
  34354. this._htmlAudioElement.loop = this.loop;
  34355. this._htmlAudioElement.crossOrigin = "anonymous";
  34356. this._isReadyToPlay = true;
  34357. document.body.appendChild(this._htmlAudioElement);
  34358. // Simulating a ready to play event for consistent behavior with non streamed audio source
  34359. if (this._readyToPlayCallback) {
  34360. window.setTimeout(function () {
  34361. _this._readyToPlayCallback();
  34362. }, 1000);
  34363. }
  34364. if (this.autoplay) {
  34365. this.play();
  34366. }
  34367. }
  34368. }
  34369. else {
  34370. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34371. if (urlOrArrayBuffer.byteLength > 0) {
  34372. this._soundLoaded(urlOrArrayBuffer);
  34373. }
  34374. }
  34375. else {
  34376. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34377. }
  34378. }
  34379. }
  34380. }
  34381. else {
  34382. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34383. this._scene.mainSoundTrack.AddSound(this);
  34384. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34385. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34386. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34387. }
  34388. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34389. if (this._readyToPlayCallback) {
  34390. window.setTimeout(function () {
  34391. _this._readyToPlayCallback();
  34392. }, 1000);
  34393. }
  34394. }
  34395. }
  34396. Sound.prototype.dispose = function () {
  34397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34398. if (this.isPlaying) {
  34399. this.stop();
  34400. }
  34401. this._isReadyToPlay = false;
  34402. if (this.soundTrackId === -1) {
  34403. this._scene.mainSoundTrack.RemoveSound(this);
  34404. }
  34405. else {
  34406. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34407. }
  34408. if (this._soundGain) {
  34409. this._soundGain.disconnect();
  34410. this._soundGain = null;
  34411. }
  34412. if (this._soundPanner) {
  34413. this._soundPanner.disconnect();
  34414. this._soundPanner = null;
  34415. }
  34416. if (this._soundSource) {
  34417. this._soundSource.disconnect();
  34418. this._soundSource = null;
  34419. }
  34420. this._audioBuffer = null;
  34421. if (this._htmlAudioElement) {
  34422. this._htmlAudioElement.pause();
  34423. this._htmlAudioElement.src = "";
  34424. document.body.removeChild(this._htmlAudioElement);
  34425. }
  34426. if (this._connectedMesh) {
  34427. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34428. this._connectedMesh = null;
  34429. }
  34430. }
  34431. };
  34432. Sound.prototype._soundLoaded = function (audioData) {
  34433. var _this = this;
  34434. this._isLoaded = true;
  34435. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34436. _this._audioBuffer = buffer;
  34437. _this._isReadyToPlay = true;
  34438. if (_this.autoplay) {
  34439. _this.play();
  34440. }
  34441. if (_this._readyToPlayCallback) {
  34442. _this._readyToPlayCallback();
  34443. }
  34444. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34445. };
  34446. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34447. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34448. this._audioBuffer = audioBuffer;
  34449. this._isReadyToPlay = true;
  34450. }
  34451. };
  34452. Sound.prototype.updateOptions = function (options) {
  34453. if (options) {
  34454. this.loop = options.loop || this.loop;
  34455. this.maxDistance = options.maxDistance || this.maxDistance;
  34456. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34457. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34458. this.refDistance = options.refDistance || this.refDistance;
  34459. this.distanceModel = options.distanceModel || this.distanceModel;
  34460. this._playbackRate = options.playbackRate || this._playbackRate;
  34461. this._updateSpatialParameters();
  34462. if (this.isPlaying) {
  34463. if (this._streaming) {
  34464. this._htmlAudioElement.playbackRate = this._playbackRate;
  34465. }
  34466. else {
  34467. this._soundSource.playbackRate.value = this._playbackRate;
  34468. }
  34469. }
  34470. }
  34471. };
  34472. Sound.prototype._createSpatialParameters = function () {
  34473. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34474. if (this._scene.headphone) {
  34475. this._panningModel = "HRTF";
  34476. }
  34477. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34478. this._updateSpatialParameters();
  34479. this._soundPanner.connect(this._ouputAudioNode);
  34480. this._inputAudioNode = this._soundPanner;
  34481. }
  34482. };
  34483. Sound.prototype._updateSpatialParameters = function () {
  34484. if (this.spatialSound) {
  34485. if (this.useCustomAttenuation) {
  34486. // Tricks to disable in a way embedded Web Audio attenuation
  34487. this._soundPanner.distanceModel = "linear";
  34488. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34489. this._soundPanner.refDistance = 1;
  34490. this._soundPanner.rolloffFactor = 1;
  34491. this._soundPanner.panningModel = this._panningModel;
  34492. }
  34493. else {
  34494. this._soundPanner.distanceModel = this.distanceModel;
  34495. this._soundPanner.maxDistance = this.maxDistance;
  34496. this._soundPanner.refDistance = this.refDistance;
  34497. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34498. this._soundPanner.panningModel = this._panningModel;
  34499. }
  34500. }
  34501. };
  34502. Sound.prototype.switchPanningModelToHRTF = function () {
  34503. this._panningModel = "HRTF";
  34504. this._switchPanningModel();
  34505. };
  34506. Sound.prototype.switchPanningModelToEqualPower = function () {
  34507. this._panningModel = "equalpower";
  34508. this._switchPanningModel();
  34509. };
  34510. Sound.prototype._switchPanningModel = function () {
  34511. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34512. this._soundPanner.panningModel = this._panningModel;
  34513. }
  34514. };
  34515. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34516. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34517. if (this._isOutputConnected) {
  34518. this._ouputAudioNode.disconnect();
  34519. }
  34520. this._ouputAudioNode.connect(soundTrackAudioNode);
  34521. this._isOutputConnected = true;
  34522. }
  34523. };
  34524. /**
  34525. * Transform this sound into a directional source
  34526. * @param coneInnerAngle Size of the inner cone in degree
  34527. * @param coneOuterAngle Size of the outer cone in degree
  34528. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34529. */
  34530. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34531. if (coneOuterAngle < coneInnerAngle) {
  34532. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34533. return;
  34534. }
  34535. this._coneInnerAngle = coneInnerAngle;
  34536. this._coneOuterAngle = coneOuterAngle;
  34537. this._coneOuterGain = coneOuterGain;
  34538. this._isDirectional = true;
  34539. if (this.isPlaying && this.loop) {
  34540. this.stop();
  34541. this.play();
  34542. }
  34543. };
  34544. Sound.prototype.setPosition = function (newPosition) {
  34545. this._position = newPosition;
  34546. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34547. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34548. }
  34549. };
  34550. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34551. this._localDirection = newLocalDirection;
  34552. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34553. this._updateDirection();
  34554. }
  34555. };
  34556. Sound.prototype._updateDirection = function () {
  34557. var mat = this._connectedMesh.getWorldMatrix();
  34558. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34559. direction.normalize();
  34560. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34561. };
  34562. Sound.prototype.updateDistanceFromListener = function () {
  34563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34564. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34565. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34566. }
  34567. };
  34568. Sound.prototype.setAttenuationFunction = function (callback) {
  34569. this._customAttenuationFunction = callback;
  34570. };
  34571. /**
  34572. * Play the sound
  34573. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34574. */
  34575. Sound.prototype.play = function (time) {
  34576. var _this = this;
  34577. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34578. try {
  34579. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34580. if (!this._soundSource || !this._streamingSource) {
  34581. if (this.spatialSound) {
  34582. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34583. if (this._isDirectional) {
  34584. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34585. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34586. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34587. if (this._connectedMesh) {
  34588. this._updateDirection();
  34589. }
  34590. else {
  34591. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34592. }
  34593. }
  34594. }
  34595. }
  34596. if (this._streaming) {
  34597. if (!this._streamingSource) {
  34598. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34599. this._htmlAudioElement.onended = function () { _this._onended(); };
  34600. this._htmlAudioElement.playbackRate = this._playbackRate;
  34601. }
  34602. this._streamingSource.disconnect();
  34603. this._streamingSource.connect(this._inputAudioNode);
  34604. this._htmlAudioElement.play();
  34605. }
  34606. else {
  34607. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34608. this._soundSource.buffer = this._audioBuffer;
  34609. this._soundSource.connect(this._inputAudioNode);
  34610. this._soundSource.loop = this.loop;
  34611. this._soundSource.playbackRate.value = this._playbackRate;
  34612. this._soundSource.onended = function () { _this._onended(); };
  34613. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34614. }
  34615. this._startTime = startTime;
  34616. this.isPlaying = true;
  34617. this.isPaused = false;
  34618. }
  34619. catch (ex) {
  34620. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34621. }
  34622. }
  34623. };
  34624. Sound.prototype._onended = function () {
  34625. this.isPlaying = false;
  34626. if (this.onended) {
  34627. this.onended();
  34628. }
  34629. };
  34630. /**
  34631. * Stop the sound
  34632. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34633. */
  34634. Sound.prototype.stop = function (time) {
  34635. if (this.isPlaying) {
  34636. if (this._streaming) {
  34637. this._htmlAudioElement.pause();
  34638. // Test needed for Firefox or it will generate an Invalid State Error
  34639. if (this._htmlAudioElement.currentTime > 0) {
  34640. this._htmlAudioElement.currentTime = 0;
  34641. }
  34642. }
  34643. else {
  34644. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34645. this._soundSource.stop(stopTime);
  34646. }
  34647. this.isPlaying = false;
  34648. }
  34649. };
  34650. Sound.prototype.pause = function () {
  34651. if (this.isPlaying) {
  34652. if (this._streaming) {
  34653. this._htmlAudioElement.pause();
  34654. }
  34655. else {
  34656. this.stop(0);
  34657. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34658. }
  34659. this.isPaused = true;
  34660. }
  34661. };
  34662. Sound.prototype.setVolume = function (newVolume, time) {
  34663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34664. if (time) {
  34665. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34666. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34667. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34668. }
  34669. else {
  34670. this._soundGain.gain.value = newVolume;
  34671. }
  34672. }
  34673. this._volume = newVolume;
  34674. };
  34675. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34676. this._playbackRate = newPlaybackRate;
  34677. if (this.isPlaying) {
  34678. if (this._streaming) {
  34679. this._htmlAudioElement.playbackRate = this._playbackRate;
  34680. }
  34681. else {
  34682. this._soundSource.playbackRate.value = this._playbackRate;
  34683. }
  34684. }
  34685. };
  34686. Sound.prototype.getVolume = function () {
  34687. return this._volume;
  34688. };
  34689. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34690. var _this = this;
  34691. if (this._connectedMesh) {
  34692. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34693. this._registerFunc = null;
  34694. }
  34695. this._connectedMesh = meshToConnectTo;
  34696. if (!this.spatialSound) {
  34697. this.spatialSound = true;
  34698. this._createSpatialParameters();
  34699. if (this.isPlaying && this.loop) {
  34700. this.stop();
  34701. this.play();
  34702. }
  34703. }
  34704. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34705. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34706. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34707. };
  34708. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34709. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34710. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34711. this._updateDirection();
  34712. }
  34713. };
  34714. Sound.prototype.clone = function () {
  34715. var _this = this;
  34716. if (!this._streaming) {
  34717. var setBufferAndRun = function () {
  34718. if (_this._isReadyToPlay) {
  34719. clonedSound._audioBuffer = _this.getAudioBuffer();
  34720. clonedSound._isReadyToPlay = true;
  34721. if (clonedSound.autoplay) {
  34722. clonedSound.play();
  34723. }
  34724. }
  34725. else {
  34726. window.setTimeout(setBufferAndRun, 300);
  34727. }
  34728. };
  34729. var currentOptions = {
  34730. autoplay: this.autoplay, loop: this.loop,
  34731. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34732. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34733. refDistance: this.refDistance, distanceModel: this.distanceModel
  34734. };
  34735. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34736. if (this.useCustomAttenuation) {
  34737. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34738. }
  34739. clonedSound.setPosition(this._position);
  34740. clonedSound.setPlaybackRate(this._playbackRate);
  34741. setBufferAndRun();
  34742. return clonedSound;
  34743. }
  34744. else {
  34745. return null;
  34746. }
  34747. };
  34748. Sound.prototype.getAudioBuffer = function () {
  34749. return this._audioBuffer;
  34750. };
  34751. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34752. var soundName = parsedSound.name;
  34753. var soundUrl;
  34754. if (parsedSound.url) {
  34755. soundUrl = rootUrl + parsedSound.url;
  34756. }
  34757. else {
  34758. soundUrl = rootUrl + soundName;
  34759. }
  34760. var options = {
  34761. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34762. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34763. rolloffFactor: parsedSound.rolloffFactor,
  34764. refDistance: parsedSound.refDistance,
  34765. distanceModel: parsedSound.distanceModel,
  34766. playbackRate: parsedSound.playbackRate
  34767. };
  34768. var newSound;
  34769. if (!sourceSound) {
  34770. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34771. scene._addPendingData(newSound);
  34772. }
  34773. else {
  34774. var setBufferAndRun = function () {
  34775. if (sourceSound._isReadyToPlay) {
  34776. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34777. newSound._isReadyToPlay = true;
  34778. if (newSound.autoplay) {
  34779. newSound.play();
  34780. }
  34781. }
  34782. else {
  34783. window.setTimeout(setBufferAndRun, 300);
  34784. }
  34785. };
  34786. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34787. setBufferAndRun();
  34788. }
  34789. if (parsedSound.position) {
  34790. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34791. newSound.setPosition(soundPosition);
  34792. }
  34793. if (parsedSound.isDirectional) {
  34794. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34795. if (parsedSound.localDirectionToMesh) {
  34796. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34797. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34798. }
  34799. }
  34800. if (parsedSound.connectedMeshId) {
  34801. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34802. if (connectedMesh) {
  34803. newSound.attachToMesh(connectedMesh);
  34804. }
  34805. }
  34806. return newSound;
  34807. };
  34808. return Sound;
  34809. })();
  34810. BABYLON.Sound = Sound;
  34811. })(BABYLON || (BABYLON = {}));
  34812. var BABYLON;
  34813. (function (BABYLON) {
  34814. var SoundTrack = (function () {
  34815. function SoundTrack(scene, options) {
  34816. this.id = -1;
  34817. this._isMainTrack = false;
  34818. this._isInitialized = false;
  34819. this._scene = scene;
  34820. this.soundCollection = new Array();
  34821. this._options = options;
  34822. if (!this._isMainTrack) {
  34823. this._scene.soundTracks.push(this);
  34824. this.id = this._scene.soundTracks.length - 1;
  34825. }
  34826. }
  34827. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34829. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34830. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34831. if (this._options) {
  34832. if (this._options.volume) {
  34833. this._outputAudioNode.gain.value = this._options.volume;
  34834. }
  34835. if (this._options.mainTrack) {
  34836. this._isMainTrack = this._options.mainTrack;
  34837. }
  34838. }
  34839. this._isInitialized = true;
  34840. }
  34841. };
  34842. SoundTrack.prototype.dispose = function () {
  34843. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34844. if (this._connectedAnalyser) {
  34845. this._connectedAnalyser.stopDebugCanvas();
  34846. }
  34847. while (this.soundCollection.length) {
  34848. this.soundCollection[0].dispose();
  34849. }
  34850. if (this._outputAudioNode) {
  34851. this._outputAudioNode.disconnect();
  34852. }
  34853. this._outputAudioNode = null;
  34854. }
  34855. };
  34856. SoundTrack.prototype.AddSound = function (sound) {
  34857. if (!this._isInitialized) {
  34858. this._initializeSoundTrackAudioGraph();
  34859. }
  34860. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34861. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34862. }
  34863. if (sound.soundTrackId) {
  34864. if (sound.soundTrackId === -1) {
  34865. this._scene.mainSoundTrack.RemoveSound(sound);
  34866. }
  34867. else {
  34868. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34869. }
  34870. }
  34871. this.soundCollection.push(sound);
  34872. sound.soundTrackId = this.id;
  34873. };
  34874. SoundTrack.prototype.RemoveSound = function (sound) {
  34875. var index = this.soundCollection.indexOf(sound);
  34876. if (index !== -1) {
  34877. this.soundCollection.splice(index, 1);
  34878. }
  34879. };
  34880. SoundTrack.prototype.setVolume = function (newVolume) {
  34881. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34882. this._outputAudioNode.gain.value = newVolume;
  34883. }
  34884. };
  34885. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34886. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34887. for (var i = 0; i < this.soundCollection.length; i++) {
  34888. this.soundCollection[i].switchPanningModelToHRTF();
  34889. }
  34890. }
  34891. };
  34892. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34894. for (var i = 0; i < this.soundCollection.length; i++) {
  34895. this.soundCollection[i].switchPanningModelToEqualPower();
  34896. }
  34897. }
  34898. };
  34899. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34900. if (this._connectedAnalyser) {
  34901. this._connectedAnalyser.stopDebugCanvas();
  34902. }
  34903. this._connectedAnalyser = analyser;
  34904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34905. this._outputAudioNode.disconnect();
  34906. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34907. }
  34908. };
  34909. return SoundTrack;
  34910. })();
  34911. BABYLON.SoundTrack = SoundTrack;
  34912. })(BABYLON || (BABYLON = {}));
  34913. var BABYLON;
  34914. (function (BABYLON) {
  34915. var DepthRenderer = (function () {
  34916. function DepthRenderer(scene, type) {
  34917. var _this = this;
  34918. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34919. this._viewMatrix = BABYLON.Matrix.Zero();
  34920. this._projectionMatrix = BABYLON.Matrix.Zero();
  34921. this._transformMatrix = BABYLON.Matrix.Zero();
  34922. this._worldViewProjection = BABYLON.Matrix.Zero();
  34923. this._scene = scene;
  34924. var engine = scene.getEngine();
  34925. // Render target
  34926. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34927. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34928. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34929. this._depthMap.refreshRate = 1;
  34930. this._depthMap.renderParticles = false;
  34931. this._depthMap.renderList = null;
  34932. // set default depth value to 1.0 (far away)
  34933. this._depthMap.onClear = function (engine) {
  34934. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34935. };
  34936. // Custom render function
  34937. var renderSubMesh = function (subMesh) {
  34938. var mesh = subMesh.getRenderingMesh();
  34939. var scene = _this._scene;
  34940. var engine = scene.getEngine();
  34941. // Culling
  34942. engine.setState(subMesh.getMaterial().backFaceCulling);
  34943. // Managing instances
  34944. var batch = mesh._getInstancesRenderList(subMesh._id);
  34945. if (batch.mustReturn) {
  34946. return;
  34947. }
  34948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34949. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34950. engine.enableEffect(_this._effect);
  34951. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34952. var material = subMesh.getMaterial();
  34953. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34954. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34955. // Alpha test
  34956. if (material && material.needAlphaTesting()) {
  34957. var alphaTexture = material.getAlphaTestTexture();
  34958. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34959. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34960. }
  34961. // Bones
  34962. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34963. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34964. }
  34965. // Draw
  34966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34967. }
  34968. };
  34969. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34970. var index;
  34971. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34972. renderSubMesh(opaqueSubMeshes.data[index]);
  34973. }
  34974. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34975. renderSubMesh(alphaTestSubMeshes.data[index]);
  34976. }
  34977. };
  34978. }
  34979. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34980. var defines = [];
  34981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34982. var mesh = subMesh.getMesh();
  34983. var scene = mesh.getScene();
  34984. var material = subMesh.getMaterial();
  34985. // Alpha test
  34986. if (material && material.needAlphaTesting()) {
  34987. defines.push("#define ALPHATEST");
  34988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34989. attribs.push(BABYLON.VertexBuffer.UVKind);
  34990. defines.push("#define UV1");
  34991. }
  34992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34993. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34994. defines.push("#define UV2");
  34995. }
  34996. }
  34997. // Bones
  34998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35001. if (mesh.numBoneInfluencers > 4) {
  35002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35004. }
  35005. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35006. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35007. }
  35008. else {
  35009. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35010. }
  35011. // Instances
  35012. if (useInstances) {
  35013. defines.push("#define INSTANCES");
  35014. attribs.push("world0");
  35015. attribs.push("world1");
  35016. attribs.push("world2");
  35017. attribs.push("world3");
  35018. }
  35019. // Get correct effect
  35020. var join = defines.join("\n");
  35021. if (this._cachedDefines !== join) {
  35022. this._cachedDefines = join;
  35023. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35024. }
  35025. return this._effect.isReady();
  35026. };
  35027. DepthRenderer.prototype.getDepthMap = function () {
  35028. return this._depthMap;
  35029. };
  35030. // Methods
  35031. DepthRenderer.prototype.dispose = function () {
  35032. this._depthMap.dispose();
  35033. };
  35034. return DepthRenderer;
  35035. })();
  35036. BABYLON.DepthRenderer = DepthRenderer;
  35037. })(BABYLON || (BABYLON = {}));
  35038. var BABYLON;
  35039. (function (BABYLON) {
  35040. var SSAORenderingPipeline = (function (_super) {
  35041. __extends(SSAORenderingPipeline, _super);
  35042. /**
  35043. * @constructor
  35044. * @param {string} name - The rendering pipeline name
  35045. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35046. * @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 }
  35047. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35048. */
  35049. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35050. var _this = this;
  35051. _super.call(this, scene.getEngine(), name);
  35052. // Members
  35053. /**
  35054. * The PassPostProcess id in the pipeline that contains the original scene color
  35055. * @type {string}
  35056. */
  35057. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35058. /**
  35059. * The SSAO PostProcess id in the pipeline
  35060. * @type {string}
  35061. */
  35062. this.SSAORenderEffect = "SSAORenderEffect";
  35063. /**
  35064. * The horizontal blur PostProcess id in the pipeline
  35065. * @type {string}
  35066. */
  35067. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35068. /**
  35069. * The vertical blur PostProcess id in the pipeline
  35070. * @type {string}
  35071. */
  35072. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35073. /**
  35074. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35075. * @type {string}
  35076. */
  35077. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35078. /**
  35079. * The output strength of the SSAO post-process. Default value is 1.0.
  35080. * @type {number}
  35081. */
  35082. this.totalStrength = 1.0;
  35083. /**
  35084. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35085. * @type {number}
  35086. */
  35087. this.radius = 0.0001;
  35088. /**
  35089. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35090. * Must not be equal to fallOff and superior to fallOff.
  35091. * Default value is 0.975
  35092. * @type {number}
  35093. */
  35094. this.area = 0.0075;
  35095. /**
  35096. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35097. * Must not be equal to area and inferior to area.
  35098. * Default value is 0.0
  35099. * @type {number}
  35100. */
  35101. this.fallOff = 0.000001;
  35102. /**
  35103. * The base color of the SSAO post-process
  35104. * The final result is "base + ssao" between [0, 1]
  35105. * @type {number}
  35106. */
  35107. this.base = 0.5;
  35108. this._firstUpdate = true;
  35109. this._scene = scene;
  35110. // Set up assets
  35111. this._createRandomTexture();
  35112. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35113. var ssaoRatio = ratio.ssaoRatio || ratio;
  35114. var combineRatio = ratio.combineRatio || ratio;
  35115. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35116. this._createSSAOPostProcess(ssaoRatio);
  35117. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35118. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35119. this._createSSAOCombinePostProcess(combineRatio);
  35120. // Set up pipeline
  35121. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35126. // Finish
  35127. scene.postProcessRenderPipelineManager.addPipeline(this);
  35128. if (cameras)
  35129. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35130. }
  35131. // Public Methods
  35132. /**
  35133. * Returns the horizontal blur PostProcess
  35134. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35135. */
  35136. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35137. return this._blurHPostProcess;
  35138. };
  35139. /**
  35140. * Returns the vertical blur PostProcess
  35141. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35142. */
  35143. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35144. return this._blurVPostProcess;
  35145. };
  35146. /**
  35147. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35148. */
  35149. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35150. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35152. this._originalColorPostProcess = undefined;
  35153. this._ssaoPostProcess = undefined;
  35154. this._blurHPostProcess = undefined;
  35155. this._blurVPostProcess = undefined;
  35156. this._ssaoCombinePostProcess = undefined;
  35157. this._randomTexture.dispose();
  35158. if (disableDepthRender)
  35159. this._scene.disableDepthRenderer();
  35160. };
  35161. // Private Methods
  35162. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35163. var _this = this;
  35164. var numSamples = 16;
  35165. var sampleSphere = [
  35166. 0.5381, 0.1856, -0.4319,
  35167. 0.1379, 0.2486, 0.4430,
  35168. 0.3371, 0.5679, -0.0057,
  35169. -0.6999, -0.0451, -0.0019,
  35170. 0.0689, -0.1598, -0.8547,
  35171. 0.0560, 0.0069, -0.1843,
  35172. -0.0146, 0.1402, 0.0762,
  35173. 0.0100, -0.1924, -0.0344,
  35174. -0.3577, -0.5301, -0.4358,
  35175. -0.3169, 0.1063, 0.0158,
  35176. 0.0103, -0.5869, 0.0046,
  35177. -0.0897, -0.4940, 0.3287,
  35178. 0.7119, -0.0154, -0.0918,
  35179. -0.0533, 0.0596, -0.5411,
  35180. 0.0352, -0.0631, 0.5460,
  35181. -0.4776, 0.2847, -0.0271
  35182. ];
  35183. var samplesFactor = 1.0 / numSamples;
  35184. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35185. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35186. "area", "fallOff", "base"
  35187. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35188. this._ssaoPostProcess.onApply = function (effect) {
  35189. if (_this._firstUpdate) {
  35190. effect.setArray3("sampleSphere", sampleSphere);
  35191. effect.setFloat("samplesFactor", samplesFactor);
  35192. effect.setFloat("randTextureTiles", 4.0);
  35193. _this._firstUpdate = false;
  35194. }
  35195. effect.setFloat("totalStrength", _this.totalStrength);
  35196. effect.setFloat("radius", _this.radius);
  35197. effect.setFloat("area", _this.area);
  35198. effect.setFloat("fallOff", _this.fallOff);
  35199. effect.setFloat("base", _this.base);
  35200. effect.setTexture("textureSampler", _this._depthTexture);
  35201. effect.setTexture("randomSampler", _this._randomTexture);
  35202. };
  35203. };
  35204. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35205. var _this = this;
  35206. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35207. this._ssaoCombinePostProcess.onApply = function (effect) {
  35208. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35209. };
  35210. };
  35211. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35212. var size = 512;
  35213. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35214. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35215. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35216. var context = this._randomTexture.getContext();
  35217. var rand = function (min, max) {
  35218. return Math.random() * (max - min) + min;
  35219. };
  35220. var randVector = BABYLON.Vector3.Zero();
  35221. for (var x = 0; x < size; x++) {
  35222. for (var y = 0; y < size; y++) {
  35223. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35224. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35225. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35226. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35227. context.fillRect(x, y, 1, 1);
  35228. }
  35229. }
  35230. this._randomTexture.update(false);
  35231. };
  35232. return SSAORenderingPipeline;
  35233. })(BABYLON.PostProcessRenderPipeline);
  35234. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35235. })(BABYLON || (BABYLON = {}));
  35236. var BABYLON;
  35237. (function (BABYLON) {
  35238. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35239. var VolumetricLightScatteringPostProcess = (function (_super) {
  35240. __extends(VolumetricLightScatteringPostProcess, _super);
  35241. /**
  35242. * @constructor
  35243. * @param {string} name - The post-process name
  35244. * @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)
  35245. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35246. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35247. * @param {number} samples - The post-process quality, default 100
  35248. * @param {number} samplingMode - The post-process filtering mode
  35249. * @param {BABYLON.Engine} engine - The babylon engine
  35250. * @param {boolean} reusable - If the post-process is reusable
  35251. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35252. */
  35253. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35254. var _this = this;
  35255. if (samples === void 0) { samples = 100; }
  35256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35257. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35258. this._screenCoordinates = BABYLON.Vector2.Zero();
  35259. /**
  35260. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35261. * @type {boolean}
  35262. */
  35263. this.useCustomMeshPosition = false;
  35264. /**
  35265. * If the post-process should inverse the light scattering direction
  35266. * @type {boolean}
  35267. */
  35268. this.invert = true;
  35269. /**
  35270. * Set to true to use the diffuseColor instead of the diffuseTexture
  35271. * @type {boolean}
  35272. */
  35273. this.useDiffuseColor = false;
  35274. /**
  35275. * Array containing the excluded meshes not rendered in the internal pass
  35276. */
  35277. this.excludedMeshes = new Array();
  35278. /**
  35279. * Controls the overall intensity of the post-process
  35280. * @type {number}
  35281. */
  35282. this.exposure = 0.3;
  35283. /**
  35284. * Dissipates each sample's contribution in range [0, 1]
  35285. * @type {number}
  35286. */
  35287. this.decay = 0.96815;
  35288. /**
  35289. * Controls the overall intensity of each sample
  35290. * @type {number}
  35291. */
  35292. this.weight = 0.58767;
  35293. /**
  35294. * Controls the density of each sample
  35295. * @type {number}
  35296. */
  35297. this.density = 0.926;
  35298. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35299. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35300. // Configure mesh
  35301. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35302. // Configure
  35303. this._createPass(scene, ratio.passRatio || ratio);
  35304. this.onActivate = function (camera) {
  35305. if (!_this.isSupported) {
  35306. _this.dispose(camera);
  35307. }
  35308. _this.onActivate = null;
  35309. };
  35310. this.onApply = function (effect) {
  35311. _this._updateMeshScreenCoordinates(scene);
  35312. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35313. effect.setFloat("exposure", _this.exposure);
  35314. effect.setFloat("decay", _this.decay);
  35315. effect.setFloat("weight", _this.weight);
  35316. effect.setFloat("density", _this.density);
  35317. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35318. };
  35319. }
  35320. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35321. var mesh = subMesh.getMesh();
  35322. var defines = [];
  35323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35324. var material = subMesh.getMaterial();
  35325. var needUV = false;
  35326. // Render this.mesh as default
  35327. if (mesh === this.mesh) {
  35328. if (this.useDiffuseColor) {
  35329. defines.push("#define DIFFUSE_COLOR_RENDER");
  35330. }
  35331. else if (material) {
  35332. if (material.diffuseTexture !== undefined) {
  35333. defines.push("#define BASIC_RENDER");
  35334. }
  35335. else {
  35336. defines.push("#define DIFFUSE_COLOR_RENDER");
  35337. }
  35338. }
  35339. defines.push("#define NEED_UV");
  35340. needUV = true;
  35341. }
  35342. // Alpha test
  35343. if (material) {
  35344. if (material.needAlphaTesting()) {
  35345. defines.push("#define ALPHATEST");
  35346. }
  35347. if (material.opacityTexture !== undefined) {
  35348. defines.push("#define OPACITY");
  35349. if (material.opacityTexture.getAlphaFromRGB) {
  35350. defines.push("#define OPACITYRGB");
  35351. }
  35352. if (!needUV) {
  35353. defines.push("#define NEED_UV");
  35354. }
  35355. }
  35356. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35357. attribs.push(BABYLON.VertexBuffer.UVKind);
  35358. defines.push("#define UV1");
  35359. }
  35360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35361. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35362. defines.push("#define UV2");
  35363. }
  35364. }
  35365. // Bones
  35366. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35367. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35368. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35369. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35370. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35371. }
  35372. else {
  35373. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35374. }
  35375. // Instances
  35376. if (useInstances) {
  35377. defines.push("#define INSTANCES");
  35378. attribs.push("world0");
  35379. attribs.push("world1");
  35380. attribs.push("world2");
  35381. attribs.push("world3");
  35382. }
  35383. // Get correct effect
  35384. var join = defines.join("\n");
  35385. if (this._cachedDefines !== join) {
  35386. this._cachedDefines = join;
  35387. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35388. }
  35389. return this._volumetricLightScatteringPass.isReady();
  35390. };
  35391. /**
  35392. * Sets the new light position for light scattering effect
  35393. * @param {BABYLON.Vector3} The new custom light position
  35394. */
  35395. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35396. this._customMeshPosition = position;
  35397. };
  35398. /**
  35399. * Returns the light position for light scattering effect
  35400. * @return {BABYLON.Vector3} The custom light position
  35401. */
  35402. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35403. return this._customMeshPosition;
  35404. };
  35405. /**
  35406. * Disposes the internal assets and detaches the post-process from the camera
  35407. */
  35408. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35409. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35410. if (rttIndex !== -1) {
  35411. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35412. }
  35413. this._volumetricLightScatteringRTT.dispose();
  35414. _super.prototype.dispose.call(this, camera);
  35415. };
  35416. /**
  35417. * Returns the render target texture used by the post-process
  35418. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35419. */
  35420. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35421. return this._volumetricLightScatteringRTT;
  35422. };
  35423. // Private methods
  35424. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35425. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35426. return true;
  35427. }
  35428. return false;
  35429. };
  35430. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35431. var _this = this;
  35432. var engine = scene.getEngine();
  35433. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35434. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35435. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35436. this._volumetricLightScatteringRTT.renderList = null;
  35437. this._volumetricLightScatteringRTT.renderParticles = false;
  35438. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35439. // Custom render function for submeshes
  35440. var renderSubMesh = function (subMesh) {
  35441. var mesh = subMesh.getRenderingMesh();
  35442. if (_this._meshExcluded(mesh)) {
  35443. return;
  35444. }
  35445. var scene = mesh.getScene();
  35446. var engine = scene.getEngine();
  35447. // Culling
  35448. engine.setState(subMesh.getMaterial().backFaceCulling);
  35449. // Managing instances
  35450. var batch = mesh._getInstancesRenderList(subMesh._id);
  35451. if (batch.mustReturn) {
  35452. return;
  35453. }
  35454. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35455. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35456. engine.enableEffect(_this._volumetricLightScatteringPass);
  35457. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35458. var material = subMesh.getMaterial();
  35459. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35460. // Alpha test
  35461. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35462. var alphaTexture = material.getAlphaTestTexture();
  35463. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35464. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35465. }
  35466. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35467. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35468. if (alphaTexture) {
  35469. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35470. }
  35471. }
  35472. if (material.opacityTexture !== undefined) {
  35473. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35474. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35475. }
  35476. }
  35477. // Bones
  35478. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35479. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35480. }
  35481. // Draw
  35482. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35483. }
  35484. };
  35485. // Render target texture callbacks
  35486. var savedSceneClearColor;
  35487. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35488. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35489. savedSceneClearColor = scene.clearColor;
  35490. scene.clearColor = sceneClearColor;
  35491. };
  35492. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35493. scene.clearColor = savedSceneClearColor;
  35494. };
  35495. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35496. var engine = scene.getEngine();
  35497. var index;
  35498. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35499. renderSubMesh(opaqueSubMeshes.data[index]);
  35500. }
  35501. engine.setAlphaTesting(true);
  35502. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35503. renderSubMesh(alphaTestSubMeshes.data[index]);
  35504. }
  35505. engine.setAlphaTesting(false);
  35506. if (transparentSubMeshes.length) {
  35507. // Sort sub meshes
  35508. for (index = 0; index < transparentSubMeshes.length; index++) {
  35509. var submesh = transparentSubMeshes.data[index];
  35510. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35511. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35512. }
  35513. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35514. sortedArray.sort(function (a, b) {
  35515. // Alpha index first
  35516. if (a._alphaIndex > b._alphaIndex) {
  35517. return 1;
  35518. }
  35519. if (a._alphaIndex < b._alphaIndex) {
  35520. return -1;
  35521. }
  35522. // Then distance to camera
  35523. if (a._distanceToCamera < b._distanceToCamera) {
  35524. return 1;
  35525. }
  35526. if (a._distanceToCamera > b._distanceToCamera) {
  35527. return -1;
  35528. }
  35529. return 0;
  35530. });
  35531. // Render sub meshes
  35532. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35533. for (index = 0; index < sortedArray.length; index++) {
  35534. renderSubMesh(sortedArray[index]);
  35535. }
  35536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35537. }
  35538. };
  35539. };
  35540. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35541. var transform = scene.getTransformMatrix();
  35542. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35543. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35544. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35545. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35546. if (this.invert)
  35547. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35548. };
  35549. // Static methods
  35550. /**
  35551. * Creates a default mesh for the Volumeric Light Scattering post-process
  35552. * @param {string} The mesh name
  35553. * @param {BABYLON.Scene} The scene where to create the mesh
  35554. * @return {BABYLON.Mesh} the default mesh
  35555. */
  35556. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35557. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35558. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35559. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35560. return mesh;
  35561. };
  35562. return VolumetricLightScatteringPostProcess;
  35563. })(BABYLON.PostProcess);
  35564. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35565. })(BABYLON || (BABYLON = {}));
  35566. // BABYLON.JS Chromatic Aberration GLSL Shader
  35567. // Author: Olivier Guyot
  35568. // Separates very slightly R, G and B colors on the edges of the screen
  35569. // Inspired by Francois Tarlier & Martins Upitis
  35570. var BABYLON;
  35571. (function (BABYLON) {
  35572. var LensRenderingPipeline = (function (_super) {
  35573. __extends(LensRenderingPipeline, _super);
  35574. /**
  35575. * @constructor
  35576. *
  35577. * Effect parameters are as follow:
  35578. * {
  35579. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35580. * edge_blur: number; // from 0 to x (1 for realism)
  35581. * distortion: number; // from 0 to x (1 for realism)
  35582. * grain_amount: number; // from 0 to 1
  35583. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35584. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35585. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35586. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35587. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35588. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35589. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35590. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35591. * }
  35592. * Note: if an effect parameter is unset, effect is disabled
  35593. *
  35594. * @param {string} name - The rendering pipeline name
  35595. * @param {object} parameters - An object containing all parameters (see above)
  35596. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35597. * @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)
  35598. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35599. */
  35600. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35601. var _this = this;
  35602. if (ratio === void 0) { ratio = 1.0; }
  35603. _super.call(this, scene.getEngine(), name);
  35604. // Lens effects can be of the following:
  35605. // - chromatic aberration (slight shift of RGB colors)
  35606. // - blur on the edge of the lens
  35607. // - lens distortion
  35608. // - depth-of-field blur & highlights enhancing
  35609. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35610. // - grain effect (noise or custom texture)
  35611. // Two additional texture samplers are needed:
  35612. // - depth map (for depth-of-field)
  35613. // - grain texture
  35614. /**
  35615. * The chromatic aberration PostProcess id in the pipeline
  35616. * @type {string}
  35617. */
  35618. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35619. /**
  35620. * The highlights enhancing PostProcess id in the pipeline
  35621. * @type {string}
  35622. */
  35623. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35624. /**
  35625. * The depth-of-field PostProcess id in the pipeline
  35626. * @type {string}
  35627. */
  35628. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35629. this._scene = scene;
  35630. // Fetch texture samplers
  35631. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35632. if (parameters.grain_texture) {
  35633. this._grainTexture = parameters.grain_texture;
  35634. }
  35635. else {
  35636. this._createGrainTexture();
  35637. }
  35638. // save parameters
  35639. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35640. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35641. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35642. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35643. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35644. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35645. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35646. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35647. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35648. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35649. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35650. // Create effects
  35651. this._createChromaticAberrationPostProcess(ratio);
  35652. this._createHighlightsPostProcess(ratio);
  35653. this._createDepthOfFieldPostProcess(ratio / 4);
  35654. // Set up pipeline
  35655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35658. if (this._highlightsGain === -1) {
  35659. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35660. }
  35661. // Finish
  35662. scene.postProcessRenderPipelineManager.addPipeline(this);
  35663. if (cameras) {
  35664. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35665. }
  35666. }
  35667. // public methods (self explanatory)
  35668. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35669. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35670. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35671. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35672. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35673. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35674. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35675. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35676. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35677. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35678. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35679. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35680. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35681. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35682. };
  35683. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35684. this._highlightsPostProcess.updateEffect();
  35685. };
  35686. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35687. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35688. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35689. this._highlightsGain = amount;
  35690. };
  35691. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35692. if (this._highlightsGain === -1) {
  35693. this._highlightsGain = 1.0;
  35694. }
  35695. this._highlightsThreshold = amount;
  35696. };
  35697. LensRenderingPipeline.prototype.disableHighlights = function () {
  35698. this._highlightsGain = -1;
  35699. };
  35700. /**
  35701. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35702. */
  35703. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35704. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35705. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35706. this._chromaticAberrationPostProcess = undefined;
  35707. this._highlightsPostProcess = undefined;
  35708. this._depthOfFieldPostProcess = undefined;
  35709. this._grainTexture.dispose();
  35710. if (disableDepthRender)
  35711. this._scene.disableDepthRenderer();
  35712. };
  35713. // colors shifting and distortion
  35714. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35715. var _this = this;
  35716. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35717. [], // samplers
  35718. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35719. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35720. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35721. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35722. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35723. };
  35724. };
  35725. // highlights enhancing
  35726. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35727. var _this = this;
  35728. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35729. [], // samplers
  35730. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35731. this._highlightsPostProcess.onApply = function (effect) {
  35732. effect.setFloat('gain', _this._highlightsGain);
  35733. effect.setFloat('threshold', _this._highlightsThreshold);
  35734. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35735. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35736. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35737. };
  35738. };
  35739. // colors shifting and distortion
  35740. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35741. var _this = this;
  35742. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35743. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35744. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35745. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35746. this._depthOfFieldPostProcess.onApply = function (effect) {
  35747. effect.setTexture("depthSampler", _this._depthTexture);
  35748. effect.setTexture("grainSampler", _this._grainTexture);
  35749. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35750. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35751. effect.setFloat('grain_amount', _this._grainAmount);
  35752. effect.setBool('blur_noise', _this._blurNoise);
  35753. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35754. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35755. effect.setFloat('distortion', _this._distortion);
  35756. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35757. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35758. effect.setFloat('aperture', _this._dofAperture);
  35759. effect.setFloat('darken', _this._dofDarken);
  35760. effect.setFloat('edge_blur', _this._edgeBlur);
  35761. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35762. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35763. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35764. };
  35765. };
  35766. // creates a black and white random noise texture, 512x512
  35767. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35768. var size = 512;
  35769. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35770. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35771. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35772. var context = this._grainTexture.getContext();
  35773. var rand = function (min, max) {
  35774. return Math.random() * (max - min) + min;
  35775. };
  35776. var value;
  35777. for (var x = 0; x < size; x++) {
  35778. for (var y = 0; y < size; y++) {
  35779. value = Math.floor(rand(0.42, 0.58) * 255);
  35780. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35781. context.fillRect(x, y, 1, 1);
  35782. }
  35783. }
  35784. this._grainTexture.update(false);
  35785. };
  35786. return LensRenderingPipeline;
  35787. })(BABYLON.PostProcessRenderPipeline);
  35788. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35789. })(BABYLON || (BABYLON = {}));
  35790. //
  35791. // This post-process allows the modification of rendered colors by using
  35792. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35793. //
  35794. // The object needs to be provided an url to a texture containing the color
  35795. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35796. // Use an image editing software to tweak the LUT to match your needs.
  35797. //
  35798. // For an example of a color LUT, see here:
  35799. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35800. // For explanations on color grading, see here:
  35801. // http://udn.epicgames.com/Three/ColorGrading.html
  35802. //
  35803. var BABYLON;
  35804. (function (BABYLON) {
  35805. var ColorCorrectionPostProcess = (function (_super) {
  35806. __extends(ColorCorrectionPostProcess, _super);
  35807. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35808. var _this = this;
  35809. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35810. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35811. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35812. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35813. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35814. this.onApply = function (effect) {
  35815. effect.setTexture("colorTable", _this._colorTableTexture);
  35816. };
  35817. }
  35818. return ColorCorrectionPostProcess;
  35819. })(BABYLON.PostProcess);
  35820. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35821. })(BABYLON || (BABYLON = {}));
  35822. var BABYLON;
  35823. (function (BABYLON) {
  35824. var AnaglyphFreeCamera = (function (_super) {
  35825. __extends(AnaglyphFreeCamera, _super);
  35826. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35827. _super.call(this, name, position, scene);
  35828. this.interaxialDistance = interaxialDistance;
  35829. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35830. }
  35831. return AnaglyphFreeCamera;
  35832. })(BABYLON.FreeCamera);
  35833. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35834. var AnaglyphArcRotateCamera = (function (_super) {
  35835. __extends(AnaglyphArcRotateCamera, _super);
  35836. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35837. _super.call(this, name, alpha, beta, radius, target, scene);
  35838. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35839. }
  35840. return AnaglyphArcRotateCamera;
  35841. })(BABYLON.ArcRotateCamera);
  35842. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35843. var AnaglyphGamepadCamera = (function (_super) {
  35844. __extends(AnaglyphGamepadCamera, _super);
  35845. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35846. _super.call(this, name, position, scene);
  35847. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35848. }
  35849. return AnaglyphGamepadCamera;
  35850. })(BABYLON.GamepadCamera);
  35851. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35852. var StereoscopicFreeCamera = (function (_super) {
  35853. __extends(StereoscopicFreeCamera, _super);
  35854. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35855. _super.call(this, name, position, scene);
  35856. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35857. }
  35858. return StereoscopicFreeCamera;
  35859. })(BABYLON.FreeCamera);
  35860. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35861. var StereoscopicArcRotateCamera = (function (_super) {
  35862. __extends(StereoscopicArcRotateCamera, _super);
  35863. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35864. _super.call(this, name, alpha, beta, radius, target, scene);
  35865. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35866. }
  35867. return StereoscopicArcRotateCamera;
  35868. })(BABYLON.ArcRotateCamera);
  35869. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35870. var StereoscopicGamepadCamera = (function (_super) {
  35871. __extends(StereoscopicGamepadCamera, _super);
  35872. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35873. _super.call(this, name, position, scene);
  35874. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35875. }
  35876. return StereoscopicGamepadCamera;
  35877. })(BABYLON.GamepadCamera);
  35878. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35879. })(BABYLON || (BABYLON = {}));
  35880. var BABYLON;
  35881. (function (BABYLON) {
  35882. var HDRRenderingPipeline = (function (_super) {
  35883. __extends(HDRRenderingPipeline, _super);
  35884. /**
  35885. * @constructor
  35886. * @param {string} name - The rendering pipeline name
  35887. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35888. * @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)
  35889. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35890. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35891. */
  35892. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35893. var _this = this;
  35894. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35895. _super.call(this, scene.getEngine(), name);
  35896. /**
  35897. * Public members
  35898. */
  35899. // Gaussian Blur
  35900. /**
  35901. * Gaussian blur coefficient
  35902. * @type {number}
  35903. */
  35904. this.gaussCoeff = 0.3;
  35905. /**
  35906. * Gaussian blur mean
  35907. * @type {number}
  35908. */
  35909. this.gaussMean = 1.0;
  35910. /**
  35911. * Gaussian blur standard deviation
  35912. * @type {number}
  35913. */
  35914. this.gaussStandDev = 0.8;
  35915. /**
  35916. * Gaussian blur multiplier. Multiplies the blur effect
  35917. * @type {number}
  35918. */
  35919. this.gaussMultiplier = 4.0;
  35920. // HDR
  35921. /**
  35922. * Exposure, controls the overall intensity of the pipeline
  35923. * @type {number}
  35924. */
  35925. this.exposure = 1.0;
  35926. /**
  35927. * Minimum luminance that the post-process can output. Luminance is >= 0
  35928. * @type {number}
  35929. */
  35930. this.minimumLuminance = 1.0;
  35931. /**
  35932. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35933. * @type {number}
  35934. */
  35935. this.maximumLuminance = 1e20;
  35936. /**
  35937. * Increase rate for luminance: eye adaptation speed to dark
  35938. * @type {number}
  35939. */
  35940. this.luminanceIncreaserate = 0.5;
  35941. /**
  35942. * Decrease rate for luminance: eye adaptation speed to bright
  35943. * @type {number}
  35944. */
  35945. this.luminanceDecreaseRate = 0.5;
  35946. // Bright pass
  35947. /**
  35948. * Minimum luminance needed to compute HDR
  35949. * @type {number}
  35950. */
  35951. this.brightThreshold = 0.8;
  35952. this._needUpdate = true;
  35953. this._scene = scene;
  35954. // Bright pass
  35955. this._createBrightPassPostProcess(scene, ratio);
  35956. // Down sample X4
  35957. this._createDownSampleX4PostProcess(scene, ratio);
  35958. // Create gaussian blur post-processes
  35959. this._createGaussianBlurPostProcess(scene, ratio);
  35960. // Texture adder
  35961. this._createTextureAdderPostProcess(scene, ratio);
  35962. // Luminance generator
  35963. this._createLuminanceGeneratorPostProcess(scene);
  35964. // HDR
  35965. this._createHDRPostProcess(scene, ratio);
  35966. // Pass postprocess
  35967. if (originalPostProcess === null) {
  35968. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35969. }
  35970. else {
  35971. this._originalPostProcess = originalPostProcess;
  35972. }
  35973. // Configure pipeline
  35974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35979. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35980. var addDownSamplerPostProcess = function (id) {
  35981. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35982. };
  35983. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35984. addDownSamplerPostProcess(i);
  35985. }
  35986. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35987. // Finish
  35988. scene.postProcessRenderPipelineManager.addPipeline(this);
  35989. if (cameras !== null) {
  35990. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35991. }
  35992. this.update();
  35993. }
  35994. /**
  35995. * Tells the pipeline to update its post-processes
  35996. */
  35997. HDRRenderingPipeline.prototype.update = function () {
  35998. this._needUpdate = true;
  35999. };
  36000. /**
  36001. * Returns the current calculated luminance
  36002. */
  36003. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36004. return this._hdrCurrentLuminance;
  36005. };
  36006. /**
  36007. * Returns the currently drawn luminance
  36008. */
  36009. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36010. return this._hdrOutputLuminance;
  36011. };
  36012. /**
  36013. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36014. */
  36015. HDRRenderingPipeline.prototype.dispose = function () {
  36016. this._originalPostProcess = undefined;
  36017. this._brightPassPostProcess = undefined;
  36018. this._downSampleX4PostProcess = undefined;
  36019. this._guassianBlurHPostProcess = undefined;
  36020. this._guassianBlurVPostProcess = undefined;
  36021. this._textureAdderPostProcess = undefined;
  36022. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36023. this._downSamplePostProcesses[i] = undefined;
  36024. }
  36025. this._hdrPostProcess = undefined;
  36026. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36027. };
  36028. /**
  36029. * Creates the HDR post-process and computes the luminance adaptation
  36030. */
  36031. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36032. var _this = this;
  36033. var hdrLastLuminance = 0.0;
  36034. this._hdrOutputLuminance = -1.0;
  36035. this._hdrCurrentLuminance = 1.0;
  36036. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36037. this._hdrPostProcess.onApply = function (effect) {
  36038. if (_this._hdrOutputLuminance < 0.0) {
  36039. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36040. }
  36041. else {
  36042. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36043. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36044. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36045. }
  36046. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36047. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36048. }
  36049. else {
  36050. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36051. }
  36052. }
  36053. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36054. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36055. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36056. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36057. effect.setFloat("exposure", _this.exposure);
  36058. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36059. _this._needUpdate = false;
  36060. };
  36061. };
  36062. /**
  36063. * Texture Adder post-process
  36064. */
  36065. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36066. var _this = this;
  36067. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36068. this._textureAdderPostProcess.onApply = function (effect) {
  36069. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36070. };
  36071. };
  36072. /**
  36073. * Down sample X4 post-process
  36074. */
  36075. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36076. var _this = this;
  36077. var downSampleX4Offsets = new Array(32);
  36078. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36079. this._downSampleX4PostProcess.onApply = function (effect) {
  36080. if (_this._needUpdate) {
  36081. var id = 0;
  36082. for (var i = -2; i < 2; i++) {
  36083. for (var j = -2; j < 2; j++) {
  36084. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36085. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36086. id += 2;
  36087. }
  36088. }
  36089. }
  36090. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36091. };
  36092. };
  36093. /**
  36094. * Bright pass post-process
  36095. */
  36096. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36097. var _this = this;
  36098. var brightOffsets = new Array(8);
  36099. var brightPassCallback = function (effect) {
  36100. if (_this._needUpdate) {
  36101. var sU = (1.0 / _this._brightPassPostProcess.width);
  36102. var sV = (1.0 / _this._brightPassPostProcess.height);
  36103. brightOffsets[0] = -0.5 * sU;
  36104. brightOffsets[1] = 0.5 * sV;
  36105. brightOffsets[2] = 0.5 * sU;
  36106. brightOffsets[3] = 0.5 * sV;
  36107. brightOffsets[4] = -0.5 * sU;
  36108. brightOffsets[5] = -0.5 * sV;
  36109. brightOffsets[6] = 0.5 * sU;
  36110. brightOffsets[7] = -0.5 * sV;
  36111. }
  36112. effect.setArray2("dsOffsets", brightOffsets);
  36113. effect.setFloat("brightThreshold", _this.brightThreshold);
  36114. };
  36115. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36116. this._brightPassPostProcess.onApply = brightPassCallback;
  36117. };
  36118. /**
  36119. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36120. */
  36121. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36122. var _this = this;
  36123. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36124. var luminanceOffsets = new Array(8);
  36125. var downSampleOffsets = new Array(18);
  36126. var halfDestPixelSize;
  36127. this._downSamplePostProcesses = new Array(lumSteps);
  36128. // Utils for luminance
  36129. var luminanceUpdateSourceOffsets = function (width, height) {
  36130. var sU = (1.0 / width);
  36131. var sV = (1.0 / height);
  36132. luminanceOffsets[0] = -0.5 * sU;
  36133. luminanceOffsets[1] = 0.5 * sV;
  36134. luminanceOffsets[2] = 0.5 * sU;
  36135. luminanceOffsets[3] = 0.5 * sV;
  36136. luminanceOffsets[4] = -0.5 * sU;
  36137. luminanceOffsets[5] = -0.5 * sV;
  36138. luminanceOffsets[6] = 0.5 * sU;
  36139. luminanceOffsets[7] = -0.5 * sV;
  36140. };
  36141. var luminanceUpdateDestOffsets = function (width, height) {
  36142. var id = 0;
  36143. for (var x = -1; x < 2; x++) {
  36144. for (var y = -1; y < 2; y++) {
  36145. downSampleOffsets[id] = (x) / width;
  36146. downSampleOffsets[id + 1] = (y) / height;
  36147. id += 2;
  36148. }
  36149. }
  36150. };
  36151. // Luminance callback
  36152. var luminanceCallback = function (effect) {
  36153. if (_this._needUpdate) {
  36154. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36155. }
  36156. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36157. effect.setArray2("lumOffsets", luminanceOffsets);
  36158. };
  36159. // Down sample callbacks
  36160. var downSampleCallback = function (indice) {
  36161. var i = indice;
  36162. return function (effect) {
  36163. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36164. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36165. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36166. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36167. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36168. effect.setArray2("dsOffsets", downSampleOffsets);
  36169. };
  36170. };
  36171. var downSampleAfterRenderCallback = function (effect) {
  36172. // Unpack result
  36173. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36174. 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);
  36175. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36176. };
  36177. // Create luminance post-process
  36178. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36179. 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);
  36180. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36181. // Create down sample post-processes
  36182. for (var i = lumSteps - 2; i >= 0; i--) {
  36183. var length = Math.pow(3, i);
  36184. ratio = { width: length, height: length };
  36185. var defines = "#define DOWN_SAMPLE\n";
  36186. if (i === 0) {
  36187. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36188. }
  36189. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36190. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36191. if (i === 0) {
  36192. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36193. }
  36194. }
  36195. };
  36196. /**
  36197. * Gaussian blur post-processes. Horizontal and Vertical
  36198. */
  36199. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36200. var _this = this;
  36201. var blurOffsetsW = new Array(9);
  36202. var blurOffsetsH = new Array(9);
  36203. var blurWeights = new Array(9);
  36204. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36205. // Utils for gaussian blur
  36206. var calculateBlurOffsets = function (height) {
  36207. var lastOutputDimensions = {
  36208. width: scene.getEngine().getRenderWidth(),
  36209. height: scene.getEngine().getRenderHeight()
  36210. };
  36211. for (var i = 0; i < 9; i++) {
  36212. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36213. if (height) {
  36214. blurOffsetsH[i] = value;
  36215. }
  36216. else {
  36217. blurOffsetsW[i] = value;
  36218. }
  36219. }
  36220. };
  36221. var calculateWeights = function () {
  36222. var x = 0.0;
  36223. for (var i = 0; i < 9; i++) {
  36224. x = (i - 4.0) / 4.0;
  36225. 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));
  36226. }
  36227. };
  36228. // Callback
  36229. var gaussianBlurCallback = function (height) {
  36230. return function (effect) {
  36231. if (_this._needUpdate) {
  36232. calculateWeights();
  36233. calculateBlurOffsets(height);
  36234. }
  36235. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36236. effect.setArray("blurWeights", blurWeights);
  36237. effect.setFloat("multiplier", _this.gaussMultiplier);
  36238. };
  36239. };
  36240. // Create horizontal gaussian blur post-processes
  36241. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36242. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36243. // Create vertical gaussian blur post-process
  36244. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36245. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36246. };
  36247. // Luminance generator
  36248. HDRRenderingPipeline.LUM_STEPS = 6;
  36249. return HDRRenderingPipeline;
  36250. })(BABYLON.PostProcessRenderPipeline);
  36251. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36252. })(BABYLON || (BABYLON = {}));
  36253. var BABYLON;
  36254. (function (BABYLON) {
  36255. var FaceAdjacencies = (function () {
  36256. function FaceAdjacencies() {
  36257. this.edges = new Array();
  36258. this.edgesConnectedCount = 0;
  36259. }
  36260. return FaceAdjacencies;
  36261. })();
  36262. var EdgesRenderer = (function () {
  36263. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36264. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36265. if (epsilon === void 0) { epsilon = 0.95; }
  36266. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36267. this.edgesWidthScalerForOrthographic = 1000.0;
  36268. this.edgesWidthScalerForPerspective = 50.0;
  36269. this._linesPositions = new Array();
  36270. this._linesNormals = new Array();
  36271. this._linesIndices = new Array();
  36272. this._buffers = new Array();
  36273. this._checkVerticesInsteadOfIndices = false;
  36274. this._source = source;
  36275. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36276. this._epsilon = epsilon;
  36277. this._prepareRessources();
  36278. this._generateEdgesLines();
  36279. }
  36280. EdgesRenderer.prototype._prepareRessources = function () {
  36281. if (this._lineShader) {
  36282. return;
  36283. }
  36284. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36285. attributes: ["position", "normal"],
  36286. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36287. });
  36288. this._lineShader.disableDepthWrite = true;
  36289. this._lineShader.backFaceCulling = false;
  36290. };
  36291. EdgesRenderer.prototype.dispose = function () {
  36292. this._vb0.dispose();
  36293. this._vb1.dispose();
  36294. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36295. this._lineShader.dispose();
  36296. };
  36297. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36298. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36299. return 0;
  36300. }
  36301. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36302. return 1;
  36303. }
  36304. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36305. return 2;
  36306. }
  36307. return -1;
  36308. };
  36309. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36310. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36311. return 0;
  36312. }
  36313. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36314. return 1;
  36315. }
  36316. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36317. return 2;
  36318. }
  36319. return -1;
  36320. };
  36321. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36322. var needToCreateLine;
  36323. if (edge === undefined) {
  36324. needToCreateLine = true;
  36325. }
  36326. else {
  36327. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36328. needToCreateLine = dotProduct < this._epsilon;
  36329. }
  36330. if (needToCreateLine) {
  36331. var offset = this._linesPositions.length / 3;
  36332. var normal = p0.subtract(p1);
  36333. normal.normalize();
  36334. // Positions
  36335. this._linesPositions.push(p0.x);
  36336. this._linesPositions.push(p0.y);
  36337. this._linesPositions.push(p0.z);
  36338. this._linesPositions.push(p0.x);
  36339. this._linesPositions.push(p0.y);
  36340. this._linesPositions.push(p0.z);
  36341. this._linesPositions.push(p1.x);
  36342. this._linesPositions.push(p1.y);
  36343. this._linesPositions.push(p1.z);
  36344. this._linesPositions.push(p1.x);
  36345. this._linesPositions.push(p1.y);
  36346. this._linesPositions.push(p1.z);
  36347. // Normals
  36348. this._linesNormals.push(p1.x);
  36349. this._linesNormals.push(p1.y);
  36350. this._linesNormals.push(p1.z);
  36351. this._linesNormals.push(-1);
  36352. this._linesNormals.push(p1.x);
  36353. this._linesNormals.push(p1.y);
  36354. this._linesNormals.push(p1.z);
  36355. this._linesNormals.push(1);
  36356. this._linesNormals.push(p0.x);
  36357. this._linesNormals.push(p0.y);
  36358. this._linesNormals.push(p0.z);
  36359. this._linesNormals.push(-1);
  36360. this._linesNormals.push(p0.x);
  36361. this._linesNormals.push(p0.y);
  36362. this._linesNormals.push(p0.z);
  36363. this._linesNormals.push(1);
  36364. // Indices
  36365. this._linesIndices.push(offset);
  36366. this._linesIndices.push(offset + 1);
  36367. this._linesIndices.push(offset + 2);
  36368. this._linesIndices.push(offset);
  36369. this._linesIndices.push(offset + 2);
  36370. this._linesIndices.push(offset + 3);
  36371. }
  36372. };
  36373. EdgesRenderer.prototype._generateEdgesLines = function () {
  36374. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36375. var indices = this._source.getIndices();
  36376. // First let's find adjacencies
  36377. var adjacencies = new Array();
  36378. var faceNormals = new Array();
  36379. var index;
  36380. var faceAdjacencies;
  36381. // Prepare faces
  36382. for (index = 0; index < indices.length; index += 3) {
  36383. faceAdjacencies = new FaceAdjacencies();
  36384. var p0Index = indices[index];
  36385. var p1Index = indices[index + 1];
  36386. var p2Index = indices[index + 2];
  36387. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36388. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36389. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36390. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36391. faceNormal.normalize();
  36392. faceNormals.push(faceNormal);
  36393. adjacencies.push(faceAdjacencies);
  36394. }
  36395. // Scan
  36396. for (index = 0; index < adjacencies.length; index++) {
  36397. faceAdjacencies = adjacencies[index];
  36398. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36399. var otherFaceAdjacencies = adjacencies[otherIndex];
  36400. if (faceAdjacencies.edgesConnectedCount === 3) {
  36401. break;
  36402. }
  36403. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36404. continue;
  36405. }
  36406. var otherP0 = indices[otherIndex * 3];
  36407. var otherP1 = indices[otherIndex * 3 + 1];
  36408. var otherP2 = indices[otherIndex * 3 + 2];
  36409. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36410. var otherEdgeIndex;
  36411. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36412. continue;
  36413. }
  36414. switch (edgeIndex) {
  36415. case 0:
  36416. if (this._checkVerticesInsteadOfIndices) {
  36417. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36418. }
  36419. else {
  36420. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36421. }
  36422. break;
  36423. case 1:
  36424. if (this._checkVerticesInsteadOfIndices) {
  36425. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36426. }
  36427. else {
  36428. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36429. }
  36430. break;
  36431. case 2:
  36432. if (this._checkVerticesInsteadOfIndices) {
  36433. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36434. }
  36435. else {
  36436. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36437. }
  36438. break;
  36439. }
  36440. if (otherEdgeIndex === -1) {
  36441. continue;
  36442. }
  36443. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36444. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36445. faceAdjacencies.edgesConnectedCount++;
  36446. otherFaceAdjacencies.edgesConnectedCount++;
  36447. if (faceAdjacencies.edgesConnectedCount === 3) {
  36448. break;
  36449. }
  36450. }
  36451. }
  36452. }
  36453. // Create lines
  36454. for (index = 0; index < adjacencies.length; index++) {
  36455. // 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
  36456. var current = adjacencies[index];
  36457. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36458. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36459. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36460. }
  36461. // Merge into a single mesh
  36462. var engine = this._source.getScene().getEngine();
  36463. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36464. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36465. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36466. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36467. this._ib = engine.createIndexBuffer(this._linesIndices);
  36468. this._indicesCount = this._linesIndices.length;
  36469. };
  36470. EdgesRenderer.prototype.render = function () {
  36471. if (!this._lineShader.isReady()) {
  36472. return;
  36473. }
  36474. var scene = this._source.getScene();
  36475. var engine = scene.getEngine();
  36476. this._lineShader._preBind();
  36477. // VBOs
  36478. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36479. scene.resetCachedMaterial();
  36480. this._lineShader.setColor4("color", this._source.edgesColor);
  36481. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36482. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36483. }
  36484. else {
  36485. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36486. }
  36487. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36488. this._lineShader.bind(this._source.getWorldMatrix());
  36489. // Draw order
  36490. engine.draw(true, 0, this._indicesCount);
  36491. this._lineShader.unbind();
  36492. engine.setDepthWrite(true);
  36493. };
  36494. return EdgesRenderer;
  36495. })();
  36496. BABYLON.EdgesRenderer = EdgesRenderer;
  36497. })(BABYLON || (BABYLON = {}));
  36498. var BABYLON;
  36499. (function (BABYLON) {
  36500. (function (TonemappingOperator) {
  36501. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36502. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36503. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36504. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36505. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36506. var TonemappingOperator = BABYLON.TonemappingOperator;
  36507. ;
  36508. var TonemapPostProcess = (function (_super) {
  36509. __extends(TonemapPostProcess, _super);
  36510. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36511. var _this = this;
  36512. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36513. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36514. this._operator = operator;
  36515. this._exposureAdjustment = exposureAdjustment;
  36516. var params = ["_ExposureAdjustment"];
  36517. var defines = "#define ";
  36518. if (operator === TonemappingOperator.Hable)
  36519. defines += "HABLE_TONEMAPPING";
  36520. else if (operator === TonemappingOperator.Reinhard)
  36521. defines += "REINHARD_TONEMAPPING";
  36522. else if (operator === TonemappingOperator.HejiDawson)
  36523. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36524. else if (operator === TonemappingOperator.Photographic)
  36525. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36526. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36527. this.onApply = function (effect) {
  36528. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36529. };
  36530. }
  36531. return TonemapPostProcess;
  36532. })(BABYLON.PostProcess);
  36533. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36534. })(BABYLON || (BABYLON = {}));
  36535. var BABYLON;
  36536. (function (BABYLON) {
  36537. var ReflectionProbe = (function () {
  36538. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36539. var _this = this;
  36540. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36541. this.name = name;
  36542. this._viewMatrix = BABYLON.Matrix.Identity();
  36543. this._target = BABYLON.Vector3.Zero();
  36544. this._add = BABYLON.Vector3.Zero();
  36545. this.position = BABYLON.Vector3.Zero();
  36546. this._scene = scene;
  36547. this._scene.reflectionProbes.push(this);
  36548. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36549. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36550. switch (faceIndex) {
  36551. case 0:
  36552. _this._add.copyFromFloats(1, 0, 0);
  36553. break;
  36554. case 1:
  36555. _this._add.copyFromFloats(-1, 0, 0);
  36556. break;
  36557. case 2:
  36558. _this._add.copyFromFloats(0, -1, 0);
  36559. break;
  36560. case 3:
  36561. _this._add.copyFromFloats(0, 1, 0);
  36562. break;
  36563. case 4:
  36564. _this._add.copyFromFloats(0, 0, 1);
  36565. break;
  36566. case 5:
  36567. _this._add.copyFromFloats(0, 0, -1);
  36568. break;
  36569. }
  36570. if (_this._attachedMesh) {
  36571. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36572. }
  36573. _this.position.addToRef(_this._add, _this._target);
  36574. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36575. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36576. };
  36577. this._renderTargetTexture.onAfterUnbind = function () {
  36578. scene.updateTransformMatrix(true);
  36579. };
  36580. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36581. }
  36582. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36583. get: function () {
  36584. return this._renderTargetTexture.refreshRate;
  36585. },
  36586. set: function (value) {
  36587. this._renderTargetTexture.refreshRate = value;
  36588. },
  36589. enumerable: true,
  36590. configurable: true
  36591. });
  36592. ReflectionProbe.prototype.getScene = function () {
  36593. return this._scene;
  36594. };
  36595. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36596. get: function () {
  36597. return this._renderTargetTexture;
  36598. },
  36599. enumerable: true,
  36600. configurable: true
  36601. });
  36602. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36603. get: function () {
  36604. return this._renderTargetTexture.renderList;
  36605. },
  36606. enumerable: true,
  36607. configurable: true
  36608. });
  36609. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36610. this._attachedMesh = mesh;
  36611. };
  36612. ReflectionProbe.prototype.dispose = function () {
  36613. var index = this._scene.reflectionProbes.indexOf(this);
  36614. if (index !== -1) {
  36615. // Remove from the scene if found
  36616. this._scene.reflectionProbes.splice(index, 1);
  36617. }
  36618. if (this._renderTargetTexture) {
  36619. this._renderTargetTexture.dispose();
  36620. this._renderTargetTexture = null;
  36621. }
  36622. };
  36623. return ReflectionProbe;
  36624. })();
  36625. BABYLON.ReflectionProbe = ReflectionProbe;
  36626. })(BABYLON || (BABYLON = {}));
  36627. var BABYLON;
  36628. (function (BABYLON) {
  36629. var SolidParticle = (function () {
  36630. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36631. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36632. this.position = BABYLON.Vector3.Zero(); // position
  36633. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36634. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36635. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36636. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36637. this.alive = true; // alive
  36638. this.idx = particleIndex;
  36639. this._pos = positionIndex;
  36640. this._model = model;
  36641. this.shapeId = shapeId;
  36642. this.idxInShape = idxInShape;
  36643. }
  36644. return SolidParticle;
  36645. })();
  36646. BABYLON.SolidParticle = SolidParticle;
  36647. var ModelShape = (function () {
  36648. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36649. this.shapeID = id;
  36650. this._shape = shape;
  36651. this._shapeUV = shapeUV;
  36652. this._positionFunction = posFunction;
  36653. this._vertexFunction = vtxFunction;
  36654. }
  36655. return ModelShape;
  36656. })();
  36657. BABYLON.ModelShape = ModelShape;
  36658. })(BABYLON || (BABYLON = {}));
  36659. var BABYLON;
  36660. (function (BABYLON) {
  36661. /**
  36662. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36663. */
  36664. var SolidParticleSystem = (function () {
  36665. /**
  36666. * Creates a SPS (Solid Particle System) object.
  36667. * @param name the SPS name, this will be the underlying mesh name
  36668. * @param updatable (default true) if the SPS must be updatable or immutable
  36669. * @param isPickable (default false) if the solid particles must be pickable
  36670. */
  36671. function SolidParticleSystem(name, scene, options) {
  36672. // public members
  36673. this.particles = new Array();
  36674. this.nbParticles = 0;
  36675. this.billboard = false;
  36676. this.counter = 0;
  36677. this.vars = {};
  36678. this._positions = new Array();
  36679. this._indices = new Array();
  36680. this._normals = new Array();
  36681. this._colors = new Array();
  36682. this._uvs = new Array();
  36683. this._index = 0; // indices index
  36684. this._updatable = true;
  36685. this._pickable = false;
  36686. this._alwaysVisible = false;
  36687. this._shapeCounter = 0;
  36688. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36689. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36690. this._computeParticleColor = true;
  36691. this._computeParticleTexture = true;
  36692. this._computeParticleRotation = true;
  36693. this._computeParticleVertex = false;
  36694. this._cam_axisZ = BABYLON.Vector3.Zero();
  36695. this._cam_axisY = BABYLON.Vector3.Zero();
  36696. this._cam_axisX = BABYLON.Vector3.Zero();
  36697. this._axisX = BABYLON.Axis.X;
  36698. this._axisY = BABYLON.Axis.Y;
  36699. this._axisZ = BABYLON.Axis.Z;
  36700. this._fakeCamPos = BABYLON.Vector3.Zero();
  36701. this._rotMatrix = new BABYLON.Matrix();
  36702. this._invertMatrix = new BABYLON.Matrix();
  36703. this._rotated = BABYLON.Vector3.Zero();
  36704. this._quaternion = new BABYLON.Quaternion();
  36705. this._vertex = BABYLON.Vector3.Zero();
  36706. this._normal = BABYLON.Vector3.Zero();
  36707. this._yaw = 0.0;
  36708. this._pitch = 0.0;
  36709. this._roll = 0.0;
  36710. this._halfroll = 0.0;
  36711. this._halfpitch = 0.0;
  36712. this._halfyaw = 0.0;
  36713. this._sinRoll = 0.0;
  36714. this._cosRoll = 0.0;
  36715. this._sinPitch = 0.0;
  36716. this._cosPitch = 0.0;
  36717. this._sinYaw = 0.0;
  36718. this._cosYaw = 0.0;
  36719. this._w = 0.0;
  36720. this.name = name;
  36721. this._scene = scene;
  36722. this._camera = scene.activeCamera;
  36723. this._pickable = options ? options.isPickable : false;
  36724. if (options && options.updatable) {
  36725. this._updatable = options.updatable;
  36726. }
  36727. else {
  36728. this._updatable = true;
  36729. }
  36730. if (this._pickable) {
  36731. this.pickedParticles = [];
  36732. }
  36733. }
  36734. /**
  36735. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36736. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36737. */
  36738. SolidParticleSystem.prototype.buildMesh = function () {
  36739. if (this.nbParticles === 0) {
  36740. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36741. this.addShape(triangle, 1);
  36742. triangle.dispose();
  36743. }
  36744. this._positions32 = new Float32Array(this._positions);
  36745. this._uvs32 = new Float32Array(this._uvs);
  36746. this._colors32 = new Float32Array(this._colors);
  36747. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36748. this._normals32 = new Float32Array(this._normals);
  36749. this._fixedNormal32 = new Float32Array(this._normals);
  36750. var vertexData = new BABYLON.VertexData();
  36751. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36752. vertexData.indices = this._indices;
  36753. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36754. if (this._uvs32) {
  36755. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36756. ;
  36757. }
  36758. if (this._colors32) {
  36759. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36760. }
  36761. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36762. vertexData.applyToMesh(mesh, this._updatable);
  36763. this.mesh = mesh;
  36764. this.mesh.isPickable = this._pickable;
  36765. // free memory
  36766. this._positions = null;
  36767. this._normals = null;
  36768. this._uvs = null;
  36769. this._colors = null;
  36770. if (!this._updatable) {
  36771. this.particles.length = 0;
  36772. }
  36773. return mesh;
  36774. };
  36775. //reset copy
  36776. SolidParticleSystem.prototype._resetCopy = function () {
  36777. this._copy.position.x = 0;
  36778. this._copy.position.y = 0;
  36779. this._copy.position.z = 0;
  36780. this._copy.rotation.x = 0;
  36781. this._copy.rotation.y = 0;
  36782. this._copy.rotation.z = 0;
  36783. this._copy.quaternion = null;
  36784. this._copy.scale.x = 1;
  36785. this._copy.scale.y = 1;
  36786. this._copy.scale.z = 1;
  36787. this._copy.uvs.x = 0;
  36788. this._copy.uvs.y = 0;
  36789. this._copy.uvs.z = 1;
  36790. this._copy.uvs.w = 1;
  36791. this._copy.color = null;
  36792. };
  36793. // _meshBuilder : inserts the shape model in the global SPS mesh
  36794. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36795. var i;
  36796. var u = 0;
  36797. var c = 0;
  36798. this._resetCopy();
  36799. if (options && options.positionFunction) {
  36800. options.positionFunction(this._copy, idx, idxInShape);
  36801. }
  36802. if (this._copy.quaternion) {
  36803. this._quaternion.x = this._copy.quaternion.x;
  36804. this._quaternion.y = this._copy.quaternion.y;
  36805. this._quaternion.z = this._copy.quaternion.z;
  36806. this._quaternion.w = this._copy.quaternion.w;
  36807. }
  36808. else {
  36809. this._yaw = this._copy.rotation.y;
  36810. this._pitch = this._copy.rotation.x;
  36811. this._roll = this._copy.rotation.z;
  36812. this._quaternionRotationYPR();
  36813. }
  36814. this._quaternionToRotationMatrix();
  36815. for (i = 0; i < shape.length; i++) {
  36816. this._vertex.x = shape[i].x;
  36817. this._vertex.y = shape[i].y;
  36818. this._vertex.z = shape[i].z;
  36819. if (options && options.vertexFunction) {
  36820. options.vertexFunction(this._copy, this._vertex, i);
  36821. }
  36822. this._vertex.x *= this._copy.scale.x;
  36823. this._vertex.y *= this._copy.scale.y;
  36824. this._vertex.z *= this._copy.scale.z;
  36825. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36826. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36827. if (meshUV) {
  36828. 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);
  36829. u += 2;
  36830. }
  36831. if (this._copy.color) {
  36832. this._color = this._copy.color;
  36833. }
  36834. else if (meshCol && meshCol[c]) {
  36835. this._color.r = meshCol[c];
  36836. this._color.g = meshCol[c + 1];
  36837. this._color.b = meshCol[c + 2];
  36838. this._color.a = meshCol[c + 3];
  36839. }
  36840. else {
  36841. this._color.r = 1;
  36842. this._color.g = 1;
  36843. this._color.b = 1;
  36844. this._color.a = 1;
  36845. }
  36846. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36847. c += 4;
  36848. }
  36849. for (i = 0; i < meshInd.length; i++) {
  36850. indices.push(p + meshInd[i]);
  36851. }
  36852. if (this._pickable) {
  36853. var nbfaces = meshInd.length / 3;
  36854. for (i = 0; i < nbfaces; i++) {
  36855. this.pickedParticles.push({ idx: idx, faceId: i });
  36856. }
  36857. }
  36858. };
  36859. // returns a shape array from positions array
  36860. SolidParticleSystem.prototype._posToShape = function (positions) {
  36861. var shape = [];
  36862. for (var i = 0; i < positions.length; i += 3) {
  36863. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36864. }
  36865. return shape;
  36866. };
  36867. // returns a shapeUV array from a Vector4 uvs
  36868. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36869. var shapeUV = [];
  36870. if (uvs) {
  36871. for (var i = 0; i < uvs.length; i++)
  36872. shapeUV.push(uvs[i]);
  36873. }
  36874. return shapeUV;
  36875. };
  36876. // adds a new particle object in the particles array
  36877. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36878. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36879. };
  36880. /**
  36881. * Adds some particles to the SPS from the model shape.
  36882. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  36883. * @param mesh any Mesh object that will be used as a model for the solid particles.
  36884. * @param nb the number of particles to be created from this model
  36885. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  36886. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  36887. */
  36888. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36889. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36890. var meshInd = mesh.getIndices();
  36891. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36892. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36893. var shape = this._posToShape(meshPos);
  36894. var shapeUV = this._uvsToShapeUV(meshUV);
  36895. var posfunc = options ? options.positionFunction : null;
  36896. var vtxfunc = options ? options.vertexFunction : null;
  36897. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36898. // particles
  36899. var idx = this.nbParticles;
  36900. for (var i = 0; i < nb; i++) {
  36901. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36902. if (this._updatable) {
  36903. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36904. }
  36905. this._index += shape.length;
  36906. idx++;
  36907. }
  36908. this.nbParticles += nb;
  36909. this._shapeCounter++;
  36910. return this._shapeCounter;
  36911. };
  36912. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36913. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36914. this._resetCopy();
  36915. if (particle._model._positionFunction) {
  36916. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36917. }
  36918. if (this._copy.quaternion) {
  36919. this._quaternion.x = this._copy.quaternion.x;
  36920. this._quaternion.y = this._copy.quaternion.y;
  36921. this._quaternion.z = this._copy.quaternion.z;
  36922. this._quaternion.w = this._copy.quaternion.w;
  36923. }
  36924. else {
  36925. this._yaw = this._copy.rotation.y;
  36926. this._pitch = this._copy.rotation.x;
  36927. this._roll = this._copy.rotation.z;
  36928. this._quaternionRotationYPR();
  36929. }
  36930. this._quaternionToRotationMatrix();
  36931. this._shape = particle._model._shape;
  36932. for (var pt = 0; pt < this._shape.length; pt++) {
  36933. this._vertex.x = this._shape[pt].x;
  36934. this._vertex.y = this._shape[pt].y;
  36935. this._vertex.z = this._shape[pt].z;
  36936. if (particle._model._vertexFunction) {
  36937. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36938. }
  36939. this._vertex.x *= this._copy.scale.x;
  36940. this._vertex.y *= this._copy.scale.y;
  36941. this._vertex.z *= this._copy.scale.z;
  36942. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36943. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36944. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36945. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36946. }
  36947. particle.position.x = 0;
  36948. particle.position.y = 0;
  36949. particle.position.z = 0;
  36950. particle.rotation.x = 0;
  36951. particle.rotation.y = 0;
  36952. particle.rotation.z = 0;
  36953. particle.quaternion = null;
  36954. particle.scale.x = 1;
  36955. particle.scale.y = 1;
  36956. particle.scale.z = 1;
  36957. };
  36958. /**
  36959. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36960. */
  36961. SolidParticleSystem.prototype.rebuildMesh = function () {
  36962. for (var p = 0; p < this.particles.length; p++) {
  36963. this._rebuildParticle(this.particles[p]);
  36964. }
  36965. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36966. };
  36967. /**
  36968. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36969. * This method calls updateParticle() for each particles of the SPS.
  36970. * For an animated SPS, it is usually called within the render loop.
  36971. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  36972. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  36973. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  36974. */
  36975. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36976. if (start === void 0) { start = 0; }
  36977. if (end === void 0) { end = this.nbParticles - 1; }
  36978. if (update === void 0) { update = true; }
  36979. if (!this._updatable) {
  36980. return;
  36981. }
  36982. // custom beforeUpdate
  36983. this.beforeUpdateParticles(start, end, update);
  36984. this._cam_axisX.x = 1;
  36985. this._cam_axisX.y = 0;
  36986. this._cam_axisX.z = 0;
  36987. this._cam_axisY.x = 0;
  36988. this._cam_axisY.y = 1;
  36989. this._cam_axisY.z = 0;
  36990. this._cam_axisZ.x = 0;
  36991. this._cam_axisZ.y = 0;
  36992. this._cam_axisZ.z = 1;
  36993. // if the particles will always face the camera
  36994. if (this.billboard) {
  36995. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36996. this._yaw = this.mesh.rotation.y;
  36997. this._pitch = this.mesh.rotation.x;
  36998. this._roll = this.mesh.rotation.z;
  36999. this._quaternionRotationYPR();
  37000. this._quaternionToRotationMatrix();
  37001. this._rotMatrix.invertToRef(this._invertMatrix);
  37002. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37003. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37004. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37005. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37006. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37007. this._cam_axisY.normalize();
  37008. this._cam_axisX.normalize();
  37009. this._cam_axisZ.normalize();
  37010. }
  37011. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37012. var idx = 0;
  37013. var index = 0;
  37014. var colidx = 0;
  37015. var colorIndex = 0;
  37016. var uvidx = 0;
  37017. var uvIndex = 0;
  37018. // particle loop
  37019. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37020. for (var p = start; p <= end; p++) {
  37021. this._particle = this.particles[p];
  37022. this._shape = this._particle._model._shape;
  37023. this._shapeUV = this._particle._model._shapeUV;
  37024. // call to custom user function to update the particle properties
  37025. this.updateParticle(this._particle);
  37026. // particle rotation matrix
  37027. if (this.billboard) {
  37028. this._particle.rotation.x = 0.0;
  37029. this._particle.rotation.y = 0.0;
  37030. }
  37031. if (this._computeParticleRotation) {
  37032. if (this._particle.quaternion) {
  37033. this._quaternion.x = this._particle.quaternion.x;
  37034. this._quaternion.y = this._particle.quaternion.y;
  37035. this._quaternion.z = this._particle.quaternion.z;
  37036. this._quaternion.w = this._particle.quaternion.w;
  37037. }
  37038. else {
  37039. this._yaw = this._particle.rotation.y;
  37040. this._pitch = this._particle.rotation.x;
  37041. this._roll = this._particle.rotation.z;
  37042. this._quaternionRotationYPR();
  37043. }
  37044. this._quaternionToRotationMatrix();
  37045. }
  37046. for (var pt = 0; pt < this._shape.length; pt++) {
  37047. idx = index + pt * 3;
  37048. colidx = colorIndex + pt * 4;
  37049. uvidx = uvIndex + pt * 2;
  37050. this._vertex.x = this._shape[pt].x;
  37051. this._vertex.y = this._shape[pt].y;
  37052. this._vertex.z = this._shape[pt].z;
  37053. if (this._computeParticleVertex) {
  37054. this.updateParticleVertex(this._particle, this._vertex, pt);
  37055. }
  37056. // positions
  37057. this._vertex.x *= this._particle.scale.x;
  37058. this._vertex.y *= this._particle.scale.y;
  37059. this._vertex.z *= this._particle.scale.z;
  37060. 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];
  37061. 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;
  37062. 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;
  37063. 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;
  37064. 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;
  37065. 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;
  37066. 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;
  37067. // normals : if the particles can't be morphed then just rotate the normals
  37068. if (!this._computeParticleVertex && !this.billboard) {
  37069. this._normal.x = this._fixedNormal32[idx];
  37070. this._normal.y = this._fixedNormal32[idx + 1];
  37071. this._normal.z = this._fixedNormal32[idx + 2];
  37072. 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];
  37073. 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;
  37074. 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;
  37075. 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;
  37076. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37077. 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;
  37078. 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;
  37079. }
  37080. if (this._computeParticleColor) {
  37081. this._colors32[colidx] = this._particle.color.r;
  37082. this._colors32[colidx + 1] = this._particle.color.g;
  37083. this._colors32[colidx + 2] = this._particle.color.b;
  37084. this._colors32[colidx + 3] = this._particle.color.a;
  37085. }
  37086. if (this._computeParticleTexture) {
  37087. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37088. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37089. }
  37090. }
  37091. index = idx + 3;
  37092. colorIndex = colidx + 4;
  37093. uvIndex = uvidx + 2;
  37094. }
  37095. if (update) {
  37096. if (this._computeParticleColor) {
  37097. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37098. }
  37099. if (this._computeParticleTexture) {
  37100. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37101. }
  37102. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37103. if (!this.mesh.areNormalsFrozen) {
  37104. if (this._computeParticleVertex || this.billboard) {
  37105. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37106. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37107. for (var i = 0; i < this._normals32.length; i++) {
  37108. this._fixedNormal32[i] = this._normals32[i];
  37109. }
  37110. }
  37111. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37112. }
  37113. }
  37114. this.afterUpdateParticles(start, end, update);
  37115. };
  37116. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37117. this._halfroll = this._roll * 0.5;
  37118. this._halfpitch = this._pitch * 0.5;
  37119. this._halfyaw = this._yaw * 0.5;
  37120. this._sinRoll = Math.sin(this._halfroll);
  37121. this._cosRoll = Math.cos(this._halfroll);
  37122. this._sinPitch = Math.sin(this._halfpitch);
  37123. this._cosPitch = Math.cos(this._halfpitch);
  37124. this._sinYaw = Math.sin(this._halfyaw);
  37125. this._cosYaw = Math.cos(this._halfyaw);
  37126. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37127. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37128. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37129. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37130. };
  37131. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37132. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37133. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37134. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37135. this._rotMatrix.m[3] = 0;
  37136. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37137. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37138. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37139. this._rotMatrix.m[7] = 0;
  37140. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37141. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37142. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37143. this._rotMatrix.m[11] = 0;
  37144. this._rotMatrix.m[12] = 0;
  37145. this._rotMatrix.m[13] = 0;
  37146. this._rotMatrix.m[14] = 0;
  37147. this._rotMatrix.m[15] = 1.0;
  37148. };
  37149. /**
  37150. * Disposes the SPS
  37151. */
  37152. SolidParticleSystem.prototype.dispose = function () {
  37153. this.mesh.dispose();
  37154. this.vars = null;
  37155. // drop references to internal big arrays for the GC
  37156. this._positions = null;
  37157. this._indices = null;
  37158. this._normals = null;
  37159. this._uvs = null;
  37160. this._colors = null;
  37161. this._positions32 = null;
  37162. this._normals32 = null;
  37163. this._fixedNormal32 = null;
  37164. this._uvs32 = null;
  37165. this._colors32 = null;
  37166. this.pickedParticles = null;
  37167. };
  37168. /**
  37169. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37170. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37171. */
  37172. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37173. this.mesh.refreshBoundingInfo();
  37174. };
  37175. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37176. // getter and setter
  37177. /**
  37178. * True if the SPS is set as always visible
  37179. */
  37180. get: function () {
  37181. return this._alwaysVisible;
  37182. },
  37183. /**
  37184. * Sets the SPS as always visible or not
  37185. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37186. */
  37187. set: function (val) {
  37188. this._alwaysVisible = val;
  37189. this.mesh.alwaysSelectAsActiveMesh = val;
  37190. },
  37191. enumerable: true,
  37192. configurable: true
  37193. });
  37194. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37195. // getters
  37196. get: function () {
  37197. return this._computeParticleRotation;
  37198. },
  37199. // Optimizer setters
  37200. /**
  37201. * Tells to setParticle() to compute the particle rotations or not.
  37202. * Default value : true. The SPS is faster when it's set to false.
  37203. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37204. */
  37205. set: function (val) {
  37206. this._computeParticleRotation = val;
  37207. },
  37208. enumerable: true,
  37209. configurable: true
  37210. });
  37211. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37212. get: function () {
  37213. return this._computeParticleColor;
  37214. },
  37215. /**
  37216. * Tells to setParticle() to compute the particle colors or not.
  37217. * Default value : true. The SPS is faster when it's set to false.
  37218. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37219. */
  37220. set: function (val) {
  37221. this._computeParticleColor = val;
  37222. },
  37223. enumerable: true,
  37224. configurable: true
  37225. });
  37226. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37227. get: function () {
  37228. return this._computeParticleTexture;
  37229. },
  37230. /**
  37231. * Tells to setParticle() to compute the particle textures or not.
  37232. * Default value : true. The SPS is faster when it's set to false.
  37233. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37234. */
  37235. set: function (val) {
  37236. this._computeParticleTexture = val;
  37237. },
  37238. enumerable: true,
  37239. configurable: true
  37240. });
  37241. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37242. get: function () {
  37243. return this._computeParticleVertex;
  37244. },
  37245. /**
  37246. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37247. * Default value : false. The SPS is faster when it's set to false.
  37248. * Note : the particle custom vertex positions aren't stored values.
  37249. */
  37250. set: function (val) {
  37251. this._computeParticleVertex = val;
  37252. },
  37253. enumerable: true,
  37254. configurable: true
  37255. });
  37256. // =======================================================================
  37257. // Particle behavior logic
  37258. // these following methods may be overwritten by the user to fit his needs
  37259. /**
  37260. * This function does nothing. It may be overwritten to set all the particles first values.
  37261. * The SPS doesn't call this function, you may have to call it by your own.
  37262. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37263. */
  37264. SolidParticleSystem.prototype.initParticles = function () {
  37265. };
  37266. /**
  37267. * This function does nothing. It may be overwritten to recycle a particle.
  37268. * The SPS doesn't call this function, you may have to call it by your own.
  37269. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37270. */
  37271. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37272. return particle;
  37273. };
  37274. /**
  37275. * Updates a particle : this function should be overwritten by the user.
  37276. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37277. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37278. * ex : just set a particle position or velocity and recycle conditions
  37279. */
  37280. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37281. return particle;
  37282. };
  37283. /**
  37284. * Updates a vertex of a particle : it can be overwritten by the user.
  37285. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37286. * @param particle the current particle
  37287. * @param vertex the current index of the current particle
  37288. * @param pt the index of the current vertex in the particle shape
  37289. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37290. * ex : just set a vertex particle position
  37291. */
  37292. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37293. return vertex;
  37294. };
  37295. /**
  37296. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37297. * This does nothing and may be overwritten by the user.
  37298. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37299. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37300. * @param update the boolean update value actually passed to setParticles()
  37301. */
  37302. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37303. };
  37304. /**
  37305. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37306. * This will be passed three parameters.
  37307. * This does nothing and may be overwritten by the user.
  37308. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37309. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37310. * @param update the boolean update value actually passed to setParticles()
  37311. */
  37312. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37313. };
  37314. return SolidParticleSystem;
  37315. })();
  37316. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37317. })(BABYLON || (BABYLON = {}));
  37318. 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(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#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\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// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\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 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, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, 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}"};
  37319. 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=g*(2*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=g*(2*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=g*(2*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(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),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},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(),\nn.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;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=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={}));";
  37320. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37321. module.exports = BABYLON;
  37322. };